dev1/backend/server.js

279 lines
9.3 KiB
JavaScript
Executable File

import express from 'express';
import axios from 'axios';
import cors from 'cors';
import dotenv from 'dotenv';
import { fileURLToPath } from 'url';
import path from 'path';
import sqlite3 from 'sqlite3'; // Import SQLite
import bodyParser from 'body-parser';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken'; // For token-based authentication
// Derive __dirname for ES modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const dbPath = path.resolve('/home/jcoakley/user_profile.db');
const db = new sqlite3.Database(dbPath, (err) => {
if (err) {
console.error('Error connecting to database:', err.message);
} else {
console.log('Connected to user_profile.db');
}
});
dotenv.config({ path: path.resolve(__dirname, '.env') }); // Load environment variables
const SECRET_KEY = process.env.SECRET_KEY || 'supersecurekey'; // Use a secure key in production
console.log('ONET_USERNAME:', process.env.ONET_USERNAME);
console.log('ONET_PASSWORD:', process.env.ONET_PASSWORD);
console.log('Current Working Directory:', process.cwd());
const app = express();
const PORT = 5000;
const allowedOrigins = ['http://localhost:3000', 'http://34.16.120.118:3000', 'https://dev.aptivaai.com'];
app.disable('x-powered-by');
app.use(bodyParser.json());
app.use(express.json());
// Enable CORS with dynamic origin checking
app.use(
cors({
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
console.error('Blocked by CORS:', origin);
callback(new Error('Not allowed by CORS'));
}
},
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Authorization', 'Content-Type', 'Accept', 'Origin', 'X-Requested-With'],
credentials: true,
})
);
// Add HTTP headers for security and caching
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
res.setHeader('Content-Security-Policy', "default-src 'self';");
res.removeHeader('X-Powered-By');
next();
});
// Route for user registration
app.post('/api/register', async (req, res) => {
const { userId, username, password } = req.body;
if (!userId || !username || !password) {
return res.status(400).json({ error: 'All fields are required' });
}
try {
const hashedPassword = await bcrypt.hash(password, 10); // Hash the password
// Step 1: Insert into user_auth
const authQuery = `
INSERT INTO user_auth (username, hashed_password)
VALUES (?, ?)
`;
db.run(authQuery, [username, hashedPassword], function (err) {
if (err) {
console.error('Error inserting into user_auth:', err.message);
if (err.message.includes('UNIQUE constraint failed')) {
return res.status(400).json({ error: 'Username already exists' });
}
return res.status(500).json({ error: 'Failed to register user' });
}
const user_id = this.lastID; // Retrieve the auto-generated id from user_auth
// Step 2: Insert into user_profile
const profileQuery = `
INSERT INTO user_profile (id, user_id, firstname, lastname, email, zipcode, state, area)
VALUES (?, ?, NULL, NULL, NULL, NULL, NULL, NULL)
`;
db.run(profileQuery, [user_id, user_id], (err) => {
if (err) {
console.error('Error inserting into user_profile:', err.message);
return res.status(500).json({ error: 'Failed to create user profile' });
}
// Return success response after both inserts
res.status(201).json({ message: 'User registered successfully', user_id });
});
});
} catch (error) {
console.error('Error during registration:', error.message);
res.status(500).json({ error: 'Internal server error' });
}
});
// Route to save user profile data
app.post('/api/user-profile', (req, res) => {
const { firstName, lastName, email, zipCode, state, area } = req.body;
if (!firstName || !lastName || !email || !zipCode || !state || !area) {
return res.status(400).json({ error: 'All fields are required' });
}
const query = `
INSERT INTO user_profile (firstname, lastname, email, zipcode, state, area)
VALUES (?, ?, ?, ?, ?, ?)
`;
const params = [firstName, lastName, email, zipCode, state, area];
db.run(query, params, function (err) {
if (err) {
console.error('Error inserting data:', err.message);
if (err.message.includes('UNIQUE constraint failed')) {
return res.status(400).json({ error: 'Email already exists' });
}
return res.status(500).json({ error: 'Failed to save user profile' });
}
res.status(201).json({ message: 'User profile saved successfully', id: this.lastID });
});
});
// Route for login
app.post('/api/login', (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Username and password are required' });
}
const query = 'SELECT * FROM user_auth WHERE username = ?';
db.get(query, [username], async (err, row) => {
if (err) {
console.error('Error fetching user:', err.message);
return res.status(500).json({ error: 'Internal server error' });
}
if (!row) {
return res.status(401).json({ error: 'Invalid username or password' });
}
// Verify password
const isPasswordValid = await bcrypt.compare(password, row.hashed_password);
if (!isPasswordValid) {
return res.status(401).json({ error: 'Invalid username or password' });
}
// Generate JWT
const token = jwt.sign({ userId: row.user_id }, SECRET_KEY, { expiresIn: '1h' });
res.status(200).json({ token });
});
});
// Route to handle user sign-in (customized)
app.post('/api/signin', async (req, res) => {
const { username, password } = req.body;
if (!username || !password) {
return res.status(400).json({ error: 'Both username and password are required' });
}
const query = `SELECT hashed_password, user_id FROM user_auth WHERE username = ?`;
db.get(query, [username], async (err, row) => {
if (err) {
console.error('Error querying user_auth:', err.message);
return res.status(500).json({ error: 'Failed to query user authentication data' });
}
if (!row) {
return res.status(401).json({ error: 'Invalid username or password' }); // User not found
}
try {
const isMatch = await bcrypt.compare(password, row.hashed_password);
if (isMatch) {
const token = jwt.sign({ userId: row.user_id }, SECRET_KEY, { expiresIn: '1h' });
res.status(200).json({ message: 'Login successful', token, userId: row.user_id });
} else {
res.status(401).json({ error: 'Invalid username or password' });
}
} catch (error) {
console.error('Error comparing passwords:', error.message);
res.status(500).json({ error: 'Failed to compare passwords' });
}
});
});
// Route to fetch user profile
app.get('/api/user-profile', (req, res) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({ error: 'Authorization token is required' });
}
try {
// Extract the userId (user_id) from the token
const { userId } = jwt.verify(token, SECRET_KEY);
// Query user_profile using user_id
const query = 'SELECT * FROM user_profile WHERE user_id = ?';
db.get(query, [userId], (err, row) => {
if (err) {
console.error('Error fetching user profile:', err.message);
return res.status(500).json({ error: 'Internal server error' });
}
if (!row) {
return res.status(404).json({ error: 'User profile not found' });
}
res.status(200).json(row); // Return the profile row
});
} catch (error) {
console.error('Error verifying token:', error.message);
res.status(401).json({ error: 'Invalid or expired token' });
}
});
// Route to fetch areas by state
app.get('/api/areas', (req, res) => {
const { state } = req.query;
if (!state) {
return res.status(400).json({ error: 'State parameter is required' });
}
const dbPath = path.resolve('/home/jcoakley/salary_info.db'); // Path to salary_info.db
const db = new sqlite3.Database(dbPath, sqlite3.OPEN_READONLY, (err) => {
if (err) {
console.error('Error connecting to database:', err.message);
return res.status(500).json({ error: 'Failed to connect to database' });
}
});
const query = `SELECT DISTINCT AREA_TITLE FROM salary_data WHERE PRIM_STATE = ?`;
db.all(query, [state], (err, rows) => {
if (err) {
console.error('Error executing query:', err.message);
return res.status(500).json({ error: 'Failed to fetch areas' });
}
const areas = rows.map((row) => row.AREA_TITLE);
res.json({ areas });
});
db.close((err) => {
if (err) {
console.error('Error closing the database:', err.message);
}
});
});
// Start the server
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on http://34.16.120.118:${PORT}`);
});