chnages
This commit is contained in:
Sizzy committed 2026-07-01 01:10:13 +05:45
1 parent 3e22355510
commit e22a8dc248
71 files changed
+24775 -1

No files matched your search

+158
View File
@@ -0,0 +1,158 @@
// ============================================================
// adminController.js — Admin-only operations
// ============================================================
// The admin area has a single purpose: review the customer
// inquiries submitted through the public "Contact Us" form.
// (No user/role management — there is only the admin role.)
// ============================================================
const pool = require('../db');
const { log } = require('../utils/logger');
// ------------------------------------------------------------
// GET /api/admin/stats
// Dashboard headline figures + the distinct country list used to
// populate the table's country filter.
// ------------------------------------------------------------
async function getStats(req, res, next) {
try {
const [total, unread, last7, today, countries] = await Promise.all([
pool.query('SELECT COUNT(*) FROM inquiries'),
pool.query('SELECT COUNT(*) FROM inquiries WHERE is_read = false'),
pool.query("SELECT COUNT(*) FROM inquiries WHERE created_at >= NOW() - INTERVAL '7 days'"),
pool.query('SELECT COUNT(*) FROM inquiries WHERE created_at::date = CURRENT_DATE'),
pool.query("SELECT DISTINCT country FROM inquiries WHERE country IS NOT NULL AND country <> '' ORDER BY country ASC"),
]);
return res.json({
totalInquiries: parseInt(total.rows[0].count, 10),
unreadInquiries: parseInt(unread.rows[0].count, 10),
last7Days: parseInt(last7.rows[0].count, 10),
today: parseInt(today.rows[0].count, 10),
countries: countries.rows.map(r => r.country),
});
} catch (err) {
next(err);
}
}
// ------------------------------------------------------------
// GET /api/admin/inquiries?page=&limit=&search=&country=&status=
// Paginated, searchable, filterable list for the dashboard table.
// ------------------------------------------------------------
async function getInquiries(req, res, next) {
try {
const page = Math.max(1, parseInt(req.query.page, 10) || 1);
const limit = Math.min(100, Math.max(1, parseInt(req.query.limit, 10) || 10));
const offset = (page - 1) * limit;
const { search, country, status } = req.query;
const conditions = [];
const params = [];
if (search) {
params.push(`%${search}%`);
const p = `$${params.length}`;
conditions.push(
`(full_name ILIKE ${p} OR email ILIKE ${p} OR company ILIKE ${p} OR job_title ILIKE ${p} OR job_details ILIKE ${p})`
);
}
if (country) {
params.push(country);
conditions.push(`country = $${params.length}`);
}
if (status === 'read') conditions.push('is_read = true');
if (status === 'unread') conditions.push('is_read = false');
const whereClause = conditions.length ? 'WHERE ' + conditions.join(' AND ') : '';
const countResult = await pool.query(`SELECT COUNT(*) FROM inquiries ${whereClause}`, params);
const totalCount = parseInt(countResult.rows[0].count, 10);
const dataResult = await pool.query(
`SELECT id, full_name, email, phone, company, country, job_title, job_details, is_read, created_at
FROM inquiries
${whereClause}
ORDER BY created_at DESC
LIMIT $${params.length + 1} OFFSET $${params.length + 2}`,
[...params, limit, offset]
);
return res.json({
inquiries: dataResult.rows,
pagination: {
page,
limit,
totalCount,
totalPages: Math.max(1, Math.ceil(totalCount / limit)),
},
});
} catch (err) {
next(err);
}
}
// ------------------------------------------------------------
// GET /api/admin/inquiries/:id — full detail of one inquiry
// Viewing an inquiry marks it as read.
// ------------------------------------------------------------
async function getInquiry(req, res, next) {
try {
const { id } = req.params;
const result = await pool.query('SELECT * FROM inquiries WHERE id = $1', [id]);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Inquiry not found.' });
}
// Mark as read on open (idempotent).
await pool.query('UPDATE inquiries SET is_read = true WHERE id = $1 AND is_read = false', [id]);
const inquiry = { ...result.rows[0], is_read: true };
return res.json({ inquiry });
} catch (err) {
next(err);
}
}
// ------------------------------------------------------------
// PATCH /api/admin/inquiries/:id/read body: { is_read }
// ------------------------------------------------------------
async function setInquiryRead(req, res, next) {
try {
const { id } = req.params;
const isRead = req.body.is_read !== false; // default true
const result = await pool.query(
'UPDATE inquiries SET is_read = $1 WHERE id = $2 RETURNING id',
[isRead, id]
);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Inquiry not found.' });
}
return res.json({ message: isRead ? 'Marked as read.' : 'Marked as unread.' });
} catch (err) {
next(err);
}
}
// ------------------------------------------------------------
// DELETE /api/admin/inquiries/:id
// ------------------------------------------------------------
async function deleteInquiry(req, res, next) {
try {
const { id } = req.params;
const result = await pool.query('DELETE FROM inquiries WHERE id = $1 RETURNING email', [id]);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Inquiry not found.' });
}
await log(req.user.id, 'ADMIN_DELETE_INQUIRY', 'success',
`Admin "${req.user.username}" deleted inquiry from ${result.rows[0].email}`, req);
return res.json({ message: 'Inquiry deleted.' });
} catch (err) {
next(err);
}
}
module.exports = {
getStats,
getInquiries,
getInquiry,
setInquiryRead,
deleteInquiry,
};
+839
View File
@@ -0,0 +1,839 @@
// ============================================================
// authController.js — All authentication logic
// ============================================================
const axios = require('axios');
const jwt = require('jsonwebtoken');
const pool = require('../db');
const crypto = require('crypto');
const { hashPassword, verifyPassword, generateSalt } = require('../utils/hash');
const { generateOTP, getOTPExpiry, hashOTP, verifyOTPHash } = require('../utils/otp');
const { sendOTPEmail, sendChangePasswordLink, sendNewDeviceAlert } = require('../utils/email');
const { log, ACTIONS } = require('../utils/logger');
const { parseDevice } = require('../utils/deviceParser');
const {
validateEmail,
validatePassword,
getPasswordErrors,
isLeakedPassword,
sanitize,
} = require('../utils/validator');
const isDev = process.env.NODE_ENV !== 'production';
// Max OTP verification attempts before OTP is invalidated
const MAX_OTP_ATTEMPTS = 3;
// Minimum seconds between OTP resend requests per user
const OTP_RESEND_COOLDOWN_SEC = 60;
// Password expires after 90 days — user must change it
const PASSWORD_MAX_AGE_DAYS = 90;
// Helper: get client IP
function getIP(req) {
return req.headers['x-forwarded-for']?.split(',')[0]?.trim() || req.socket?.remoteAddress || 'unknown';
}
// ============================================================
// HELPER: Verify Cloudflare Turnstile CAPTCHA token
// ============================================================
async function verifyTurnstile(token) {
try {
const response = await axios.post(
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
new URLSearchParams({
secret: process.env.TURNSTILE_SECRET_KEY,
response: token,
}),
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
);
return response.data.success === true;
} catch (err) {
console.error('Turnstile verification error:', err.message);
return false;
}
}
// Helper: password validation error message
function passwordErrorMessage(password) {
const errors = getPasswordErrors(password);
if (errors.length === 0) return null;
return `Password must contain ${errors.join(', ')}.`;
}
// ============================================================
// POST /api/auth/login
// ============================================================
async function login(req, res, next) {
try {
let { email, password, turnstileToken } = req.body;
email = sanitize(email || '').toLowerCase().trim();
// Verify CAPTCHA
const captchaOk = await verifyTurnstile(turnstileToken);
if (!captchaOk) {
await log(null, ACTIONS.CAPTCHA_FAILED, 'failed', `CAPTCHA failed on login for: "${email}"`, req);
return res.status(400).json({ message: 'CAPTCHA verification failed. Please try again.' });
}
// Find user by email
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
if (result.rows.length === 0) {
await log(null, ACTIONS.LOGIN_FAILED, 'failed', `Login attempt for unknown email: "${email}"`, req);
return res.status(401).json({ message: 'Invalid email or password.' });
}
const user = result.rows[0];
// Block login if email is not verified
if (user.email_verified === false) {
await log(user.id, ACTIONS.LOGIN_FAILED, 'failed', `Login blocked — email not verified for "${email}"`, req);
return res.status(403).json({
message: 'Email not verified. Please verify your email with the OTP sent during registration.',
requireEmailVerification: true,
userId: user.id,
});
}
// Check account lock
if (user.locked_until && new Date() < new Date(user.locked_until)) {
const minsLeft = Math.ceil((new Date(user.locked_until) - new Date()) / 60000);
await log(user.id, ACTIONS.ACCOUNT_LOCKED, 'warning', `Login blocked — account locked for ${minsLeft} more min(s)`, req);
return res.status(423).json({ message: `Account is locked. Try again in ${minsLeft} minute(s).` });
}
// Verify password
const passwordOk = verifyPassword(password, user.password_hash);
if (!passwordOk) {
const newAttempts = user.failed_attempts + 1;
let lockUntil = null;
if (newAttempts >= 5) {
lockUntil = new Date(Date.now() + 15 * 60 * 1000);
}
await pool.query(
'UPDATE users SET failed_attempts = $1, locked_until = $2 WHERE id = $3',
[newAttempts, lockUntil, user.id]
);
if (lockUntil) {
await log(user.id, ACTIONS.ACCOUNT_LOCKED, 'warning', `Account locked after 5 failed attempts`, req);
return res.status(423).json({ message: 'Account locked for 15 minutes after 5 failed attempts.' });
}
const remaining = 5 - newAttempts;
await log(user.id, ACTIONS.LOGIN_FAILED, 'failed', `Wrong password — attempt ${newAttempts}/5 (${remaining} left)`, req);
return res.status(401).json({ message: `Invalid password. ${remaining} attempt(s) remaining before lockout.` });
}
// Password correct — reset failed attempts
await pool.query(
'UPDATE users SET failed_attempts = 0, locked_until = NULL WHERE id = $1',
[user.id]
);
// Check password expiry (90 days)
if (user.password_changed_at) {
const daysSinceChange = (Date.now() - new Date(user.password_changed_at).getTime()) / (1000 * 60 * 60 * 24);
if (daysSinceChange >= PASSWORD_MAX_AGE_DAYS) {
await log(user.id, ACTIONS.PASSWORD_EXPIRED, 'warning',
`Password expired (${Math.floor(daysSinceChange)} days old) for "${user.email}"`, req);
return res.status(403).json({
message: `Your password has expired (last changed ${Math.floor(daysSinceChange)} days ago). Please reset your password.`,
passwordExpired: true,
userId: user.id,
});
}
}
// Generate OTP, hash it, and store the hash in DB
const otp = generateOTP();
const otpExpiry = getOTPExpiry();
const otpHash = hashOTP(otp);
await pool.query(
'UPDATE users SET otp_code = $1, otp_expires_at = $2, otp_attempts = 0 WHERE id = $3',
[otpHash, otpExpiry, user.id]
);
// Send OTP via email
try {
await sendOTPEmail(user.email, user.username, otp);
if (isDev) console.log(`[OTP] Sent to ${user.email} — Code: ${otp}`);
} catch (emailErr) {
console.error('[OTP] Email failed:', emailErr.message);
if (isDev) console.log(`[OTP] Fallback — User: ${user.username} | Code: ${otp}`);
}
await log(user.id, ACTIONS.OTP_SENT, 'success', `OTP sent to ${user.email} after password verified`, req);
return res.json({
message: `OTP sent to your email (${user.email}).`,
userId: user.id,
requireOTP: true,
});
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/request-otp (resend)
// ============================================================
async function requestOTP(req, res, next) {
try {
const { userId } = req.body;
const result = await pool.query(
'SELECT id, username, email, otp_expires_at FROM users WHERE id = $1',
[userId]
);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'User not found.' });
}
const user = result.rows[0];
// Rate-limit: enforce cooldown between OTP resends
// OTP expiry is 5 min from issue. If last OTP was issued less than
// OTP_RESEND_COOLDOWN_SEC ago, reject the request.
if (user.otp_expires_at) {
const issuedAt = new Date(user.otp_expires_at).getTime() - 5 * 60 * 1000; // when OTP was issued
const elapsed = (Date.now() - issuedAt) / 1000;
if (elapsed < OTP_RESEND_COOLDOWN_SEC) {
const wait = Math.ceil(OTP_RESEND_COOLDOWN_SEC - elapsed);
return res.status(429).json({
message: `Please wait ${wait} second(s) before requesting a new OTP.`,
});
}
}
// Generate new OTP, hash it, reset attempts
const otp = generateOTP();
const otpExpiry = getOTPExpiry();
const otpHash = hashOTP(otp);
await pool.query(
'UPDATE users SET otp_code = $1, otp_expires_at = $2, otp_attempts = 0 WHERE id = $3',
[otpHash, otpExpiry, userId]
);
try {
await sendOTPEmail(user.email, user.username, otp);
if (isDev) console.log(`[OTP] Resent to ${user.email} — Code: ${otp}`);
} catch (emailErr) {
console.error('[OTP] Email failed:', emailErr.message);
if (isDev) console.log(`[OTP] Fallback — User: ${user.username} | Code: ${otp}`);
}
await log(user.id, ACTIONS.OTP_RESENT, 'success', `OTP resent to ${user.email}`, req);
return res.json({ message: `New OTP sent to ${user.email}.` });
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/verify-otp
// ============================================================
async function verifyOTP(req, res, next) {
try {
const { userId, otp } = req.body;
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'User not found.' });
}
const user = result.rows[0];
// Check OTP expiry first
if (!user.otp_expires_at || new Date() > new Date(user.otp_expires_at)) {
await log(user.id, ACTIONS.OTP_EXPIRED, 'failed', `OTP expired`, req);
return res.status(401).json({ message: 'OTP has expired. Please request a new one.' });
}
// Brute-force protection: check attempt count
const attempts = user.otp_attempts || 0;
if (attempts >= MAX_OTP_ATTEMPTS) {
// Invalidate the OTP
await pool.query(
'UPDATE users SET otp_code = NULL, otp_expires_at = NULL, otp_attempts = 0 WHERE id = $1',
[user.id]
);
await log(user.id, ACTIONS.OTP_FAILED, 'failed', `OTP invalidated after ${MAX_OTP_ATTEMPTS} failed attempts`, req);
return res.status(401).json({
message: `Too many wrong attempts. OTP has been invalidated. Please request a new one.`,
});
}
// Verify OTP hash
let otpValid = false;
try {
otpValid = user.otp_code && verifyOTPHash(otp, user.otp_code);
} catch {
otpValid = false;
}
if (!otpValid) {
// Increment attempt counter
await pool.query(
'UPDATE users SET otp_attempts = otp_attempts + 1 WHERE id = $1',
[user.id]
);
const remaining = MAX_OTP_ATTEMPTS - (attempts + 1);
await log(user.id, ACTIONS.OTP_FAILED, 'failed', `Wrong OTP entered (${remaining} attempt(s) remaining)`, req);
return res.status(401).json({
message: `Invalid OTP. ${remaining} attempt(s) remaining.`,
});
}
// Clear OTP
await pool.query(
'UPDATE users SET otp_code = NULL, otp_expires_at = NULL, otp_attempts = 0 WHERE id = $1',
[user.id]
);
// Generate a unique session ID (jti = JWT ID)
const jti = crypto.randomBytes(16).toString('hex');
// Issue JWT — includes jti so we can match it to a session row
const token = jwt.sign(
{ id: user.id, username: user.username, role: user.role, jti },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
// Issue refresh token (longer lived)
const refreshJti = crypto.randomBytes(16).toString('hex');
const refreshToken = jwt.sign(
{ id: user.id, jti: refreshJti, type: 'refresh' },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
);
// Save session to DB with device + IP info, including refresh token jti
const deviceInfo = parseDevice(req.headers['user-agent']);
const clientIP = getIP(req);
// Check if this device + IP combo has been seen before for this user
const knownDevice = await pool.query(
`SELECT id FROM sessions
WHERE user_id = $1 AND device_info = $2 AND ip_address = $3
LIMIT 1`,
[user.id, deviceInfo, clientIP]
);
const isNewDevice = knownDevice.rows.length === 0;
await pool.query(
`INSERT INTO sessions (user_id, jti, refresh_jti, ip_address, device_info)
VALUES ($1, $2, $3, $4, $5)`,
[user.id, jti, refreshJti, clientIP, deviceInfo]
);
// Send new device alert email (non-blocking — don't fail login if email fails)
if (isNewDevice) {
sendNewDeviceAlert(user.email, user.username, deviceInfo, clientIP, new Date())
.then(() => {
if (isDev) console.log(`[NEW DEVICE] Alert sent to ${user.email} for "${deviceInfo}"`);
})
.catch((err) => {
console.error('[NEW DEVICE] Alert email failed:', err.message);
});
await log(user.id, ACTIONS.NEW_DEVICE_LOGIN, 'warning',
`New device login: ${deviceInfo} from ${clientIP}`, req);
}
const isProduction = process.env.NODE_ENV === 'production';
res.cookie('token', token, {
httpOnly: true,
secure: isProduction,
maxAge: 60 * 60 * 1000, // 1 hour
sameSite: isProduction ? 'strict' : 'lax',
});
res.cookie('refreshToken', refreshToken, {
httpOnly: true,
secure: isProduction,
maxAge: 7 * 24 * 60 * 60 * 1000, // 7 days
sameSite: isProduction ? 'strict' : 'lax',
path: '/api/auth/refresh-token', // only sent to refresh endpoint
});
await log(user.id, ACTIONS.LOGIN_SUCCESS, 'success',
`Login completed — role: ${user.role} — device: ${deviceInfo}`, req);
return res.json({
message: 'Login successful! Welcome.',
user: { id: user.id, username: user.username, role: user.role },
});
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/refresh-token (public, requires refresh cookie)
// ============================================================
async function refreshToken(req, res, next) {
try {
const token = req.cookies.refreshToken;
if (!token) {
return res.status(401).json({ message: 'No refresh token.' });
}
let decoded;
try {
decoded = jwt.verify(token, process.env.JWT_SECRET);
} catch {
return res.status(401).json({ message: 'Invalid or expired refresh token. Please login again.' });
}
if (decoded.type !== 'refresh') {
return res.status(401).json({ message: 'Invalid token type.' });
}
// Check session still exists by refresh_jti
const session = await pool.query(
'SELECT s.*, u.username, u.role FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.refresh_jti = $1',
[decoded.jti]
);
if (session.rows.length === 0) {
return res.status(401).json({ message: 'Session revoked. Please login again.' });
}
const sess = session.rows[0];
// Issue a new access token
const newJti = crypto.randomBytes(16).toString('hex');
const newToken = jwt.sign(
{ id: sess.user_id, username: sess.username, role: sess.role, jti: newJti },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
// Update session jti
await pool.query(
'UPDATE sessions SET jti = $1, last_used_at = NOW() WHERE id = $2',
[newJti, sess.id]
);
const isProduction = process.env.NODE_ENV === 'production';
res.cookie('token', newToken, {
httpOnly: true,
secure: isProduction,
maxAge: 60 * 60 * 1000,
sameSite: isProduction ? 'strict' : 'lax',
});
return res.json({ message: 'Token refreshed.', user: { id: sess.user_id, username: sess.username, role: sess.role } });
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/change-password (protected)
// ============================================================
async function changePassword(req, res, next) {
try {
const { oldPassword, newPassword } = req.body;
const userId = req.user.id;
if (!validatePassword(newPassword)) {
const msg = passwordErrorMessage(newPassword) || 'Password does not meet requirements.';
return res.status(400).json({ message: msg });
}
if (isLeakedPassword(newPassword)) {
await log(userId, ACTIONS.CHANGE_PASSWORD_FAILED, 'failed', `Leaked password used for change password`, req);
return res.status(400).json({ message: 'This password is commonly used and easy to crack. Please choose a stronger password.' });
}
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'User not found.' });
}
const user = result.rows[0];
// Verify old password
const oldPasswordOk = verifyPassword(oldPassword, user.password_hash);
if (!oldPasswordOk) {
await log(userId, ACTIONS.CHANGE_PASSWORD_FAILED, 'failed', `Wrong current password provided`, req);
return res.status(401).json({ message: 'Current password is incorrect.' });
}
// Check password history (last 5)
const history = await pool.query(
`SELECT password_hash FROM password_history
WHERE user_id = $1 ORDER BY created_at DESC LIMIT 5`,
[userId]
);
for (const record of history.rows) {
if (verifyPassword(newPassword, record.password_hash)) {
await log(userId, ACTIONS.CHANGE_PASSWORD_FAILED, 'failed', `Attempted to reuse a recent password`, req);
return res.status(400).json({ message: 'Cannot reuse a recent password. Please choose a different one.' });
}
}
// Hash and save new password + update password_changed_at
const newSalt = generateSalt();
const newPasswordHash = hashPassword(newPassword, newSalt);
await pool.query(
'UPDATE users SET password_hash = $1, password_changed_at = NOW() WHERE id = $2',
[newPasswordHash, userId]
);
await pool.query(
'INSERT INTO password_history (user_id, password_hash) VALUES ($1, $2)',
[userId, newPasswordHash]
);
// Invalidate ALL sessions (forces re-login on all devices)
const deleted = await pool.query(
'DELETE FROM sessions WHERE user_id = $1 RETURNING id',
[userId]
);
await log(userId, ACTIONS.CHANGE_PASSWORD, 'success',
`Password changed — ${deleted.rowCount} session(s) invalidated`, req);
res.clearCookie('token');
res.clearCookie('refreshToken', { path: '/api/auth/refresh-token' });
return res.json({
message: 'Password changed successfully! You have been logged out of all devices for security.',
loggedOut: true,
});
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/forgot-password (public)
// ============================================================
async function forgotPassword(req, res, next) {
try {
let { email } = req.body;
email = sanitize(email || '').toLowerCase().trim();
if (!validateEmail(email)) {
return res.status(400).json({ message: 'Please enter a valid email address.' });
}
const result = await pool.query('SELECT * FROM users WHERE email = $1', [email]);
if (result.rows.length === 0) {
await log(null, ACTIONS.FORGOT_PASSWORD_FAILED, 'failed',
`Reset requested for unknown email: "${email}"`, req);
return res.json({ message: 'If that email is registered, an OTP has been sent.' });
}
const user = result.rows[0];
// Rate-limit: enforce cooldown between OTP resends
if (user.otp_expires_at) {
const issuedAt = new Date(user.otp_expires_at).getTime() - 5 * 60 * 1000;
const elapsed = (Date.now() - issuedAt) / 1000;
if (elapsed < OTP_RESEND_COOLDOWN_SEC) {
return res.json({ message: 'If that email is registered, an OTP has been sent.' });
}
}
// Generate OTP, hash it, and store
const otp = generateOTP();
const otpExpiry = getOTPExpiry();
const otpHash = hashOTP(otp);
await pool.query(
'UPDATE users SET otp_code = $1, otp_expires_at = $2, otp_attempts = 0 WHERE id = $3',
[otpHash, otpExpiry, user.id]
);
try {
await sendOTPEmail(user.email, user.username, otp);
if (isDev) console.log(`[RESET OTP] Sent to ${user.email} — Code: ${otp}`);
} catch (emailErr) {
console.error('[RESET OTP] Email failed:', emailErr.message);
if (isDev) console.log(`[RESET OTP] Fallback — User: ${user.username} | Code: ${otp}`);
}
await log(user.id, ACTIONS.FORGOT_PASSWORD, 'success',
`Password reset OTP sent to ${user.email}`, req);
return res.json({
message: 'OTP sent to your email. Enter it below to reset your password.',
userId: user.id,
});
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/reset-password (public)
// ============================================================
async function resetPassword(req, res, next) {
try {
const { userId, otp, newPassword } = req.body;
if (!validatePassword(newPassword)) {
const msg = passwordErrorMessage(newPassword) || 'Password does not meet requirements.';
return res.status(400).json({ message: msg });
}
if (isLeakedPassword(newPassword)) {
await log(userId, ACTIONS.RESET_PASSWORD_FAILED, 'failed', `Leaked password used for reset password`, req);
return res.status(400).json({ message: 'This password is commonly used and easy to crack. Please choose a stronger password.' });
}
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'User not found.' });
}
const user = result.rows[0];
// Check OTP expiry
if (!user.otp_expires_at || new Date() > new Date(user.otp_expires_at)) {
await log(user.id, ACTIONS.RESET_PASSWORD_FAILED, 'failed', `Expired OTP on password reset`, req);
return res.status(401).json({ message: 'OTP has expired. Please request a new one.' });
}
// Brute-force protection
const attempts = user.otp_attempts || 0;
if (attempts >= MAX_OTP_ATTEMPTS) {
await pool.query(
'UPDATE users SET otp_code = NULL, otp_expires_at = NULL, otp_attempts = 0 WHERE id = $1',
[user.id]
);
await log(user.id, ACTIONS.RESET_PASSWORD_FAILED, 'failed', `OTP invalidated after ${MAX_OTP_ATTEMPTS} failed attempts`, req);
return res.status(401).json({
message: `Too many wrong attempts. OTP has been invalidated. Please request a new one.`,
});
}
// Verify OTP hash
let otpValid = false;
try {
otpValid = user.otp_code && verifyOTPHash(otp, user.otp_code);
} catch {
otpValid = false;
}
if (!otpValid) {
await pool.query(
'UPDATE users SET otp_attempts = otp_attempts + 1 WHERE id = $1',
[user.id]
);
const remaining = MAX_OTP_ATTEMPTS - (attempts + 1);
await log(user.id, ACTIONS.RESET_PASSWORD_FAILED, 'failed', `Wrong OTP on password reset (${remaining} attempt(s) remaining)`, req);
return res.status(401).json({ message: `Invalid OTP. ${remaining} attempt(s) remaining.` });
}
// Check password history
const history = await pool.query(
`SELECT password_hash FROM password_history
WHERE user_id = $1 ORDER BY created_at DESC LIMIT 5`,
[userId]
);
for (const record of history.rows) {
if (verifyPassword(newPassword, record.password_hash)) {
await log(user.id, ACTIONS.RESET_PASSWORD_FAILED, 'failed',
`Attempted to reuse a recent password during reset`, req);
return res.status(400).json({
message: 'Cannot reuse a recent password. Please choose a different one.',
});
}
}
// Hash and save the new password
const newSalt = generateSalt();
const newPasswordHash = hashPassword(newPassword, newSalt);
await pool.query('UPDATE users SET password_hash = $1, otp_code = NULL, otp_expires_at = NULL, otp_attempts = 0, password_changed_at = NOW() WHERE id = $2',
[newPasswordHash, userId]);
await pool.query(
'INSERT INTO password_history (user_id, password_hash) VALUES ($1, $2)',
[userId, newPasswordHash]
);
await log(user.id, ACTIONS.RESET_PASSWORD, 'success',
`Password reset successfully via OTP for "${user.username}"`, req);
return res.json({ message: 'Password reset successful! You can now login with your new password.' });
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/logout (protected)
// ============================================================
async function logout(req, res, next) {
try {
await pool.query('DELETE FROM sessions WHERE jti = $1', [req.userJti]);
await log(req.user.id, ACTIONS.LOGOUT, 'success', `User logged out from one device`, req);
res.clearCookie('token');
res.clearCookie('refreshToken', { path: '/api/auth/refresh-token' });
return res.json({ message: 'Logged out successfully.' });
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/logout-all (protected)
// ============================================================
async function logoutAll(req, res, next) {
try {
const result = await pool.query(
'DELETE FROM sessions WHERE user_id = $1 RETURNING id',
[req.user.id]
);
const count = result.rowCount;
await log(req.user.id, ACTIONS.LOGOUT_ALL, 'success',
`Logged out from all ${count} device(s)`, req);
res.clearCookie('token');
res.clearCookie('refreshToken', { path: '/api/auth/refresh-token' });
return res.json({ message: `Logged out from all ${count} device(s).` });
} catch (err) {
next(err);
}
}
// ============================================================
// GET /api/auth/sessions (protected)
// ============================================================
async function getSessions(req, res, next) {
try {
const result = await pool.query(
`SELECT id, jti, ip_address, device_info, created_at, last_used_at
FROM sessions
WHERE user_id = $1
ORDER BY last_used_at DESC`,
[req.user.id]
);
const sessions = result.rows.map(s => ({
...s,
isCurrent: s.jti === req.userJti,
}));
return res.json({ sessions });
} catch (err) {
next(err);
}
}
// ============================================================
// GET /api/auth/me (protected)
// ============================================================
async function getMe(req, res) {
return res.json({ user: req.user });
}
// ============================================================
// POST /api/auth/request-change-password-link (protected)
// ============================================================
async function requestChangePasswordLink(req, res, next) {
try {
const userId = req.user.id;
const result = await pool.query('SELECT username, email, password_hash FROM users WHERE id = $1', [userId]);
if (result.rows.length === 0) return res.status(404).json({ message: 'User not found.' });
const user = result.rows[0];
const secret = process.env.JWT_SECRET + user.password_hash;
const token = jwt.sign({ id: userId, type: 'change-password-link' }, secret, { expiresIn: '15m' });
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:5002';
const link = `${frontendUrl}/set-new-password?token=${token}&id=${userId}`;
try {
await sendChangePasswordLink(user.email, user.username, link);
if (isDev) console.log(`[CHANGE PWD LINK] Sent to ${user.email} — Link: ${link}`);
} catch (emailErr) {
console.error('[CHANGE PWD LINK] Email failed:', emailErr.message);
if (isDev) console.log(`[CHANGE PWD LINK] Fallback — User: ${user.username} | Link: ${link}`);
}
await log(userId, ACTIONS.CHANGE_PASSWORD, 'success', `Change password link sent to ${user.email}`, req);
return res.json({ message: 'A secure password change link has been sent to your email. Please check your inbox.' });
} catch (err) {
next(err);
}
}
// ============================================================
// POST /api/auth/verify-change-password-link (public, but requires token)
// ============================================================
async function verifyChangePasswordLink(req, res, next) {
try {
const { id, token, newPassword } = req.body;
if (!validatePassword(newPassword)) {
const msg = passwordErrorMessage(newPassword) || 'Password does not meet requirements.';
return res.status(400).json({ message: msg });
}
if (isLeakedPassword(newPassword)) {
await log(id, ACTIONS.CHANGE_PASSWORD_FAILED, 'failed', `Leaked password used for email link reset`, req);
return res.status(400).json({ message: 'This password is commonly used and easy to crack. Please choose a stronger password.' });
}
const result = await pool.query('SELECT * FROM users WHERE id = $1', [id]);
if (result.rows.length === 0) return res.status(404).json({ message: 'User not found.' });
const user = result.rows[0];
const secret = process.env.JWT_SECRET + user.password_hash;
try {
const decoded = jwt.verify(token, secret);
if (decoded.id !== parseInt(id) || decoded.type !== 'change-password-link') {
throw new Error('Invalid token payload');
}
} catch (tokenErr) {
await log(id, ACTIONS.CHANGE_PASSWORD_FAILED, 'failed', `Invalid or expired password change link`, req);
return res.status(400).json({ message: 'The secure link is invalid or has expired. Please request a new one.' });
}
// Check password history (last 5)
const history = await pool.query(
`SELECT password_hash FROM password_history
WHERE user_id = $1 ORDER BY created_at DESC LIMIT 5`,
[id]
);
for (const record of history.rows) {
if (verifyPassword(newPassword, record.password_hash)) {
await log(user.id, ACTIONS.CHANGE_PASSWORD_FAILED, 'failed', `Attempted to reuse a recent password during link reset`, req);
return res.status(400).json({ message: 'Cannot reuse a recent password. Please choose a different one.' });
}
}
// Hash and save new password
const newSalt = generateSalt();
const newPasswordHash = hashPassword(newPassword, newSalt);
await pool.query('UPDATE users SET password_hash = $1, password_changed_at = NOW() WHERE id = $2', [newPasswordHash, id]);
await pool.query(
'INSERT INTO password_history (user_id, password_hash) VALUES ($1, $2)',
[id, newPasswordHash]
);
// Logout all active sessions for security
await pool.query('DELETE FROM sessions WHERE user_id = $1', [id]);
await log(id, ACTIONS.CHANGE_PASSWORD, 'success', `Password changed successfully via email link`, req);
return res.json({ message: 'Password changed successfully! You will now be logged out of all devices.' });
} catch (err) {
next(err);
}
}
module.exports = {
login, requestOTP, verifyOTP, refreshToken,
changePassword, forgotPassword, resetPassword,
requestChangePasswordLink, verifyChangePasswordLink,
logout, logoutAll, getSessions, getMe,
};
+120
View File
@@ -0,0 +1,120 @@
// ============================================================
// chatController.js — AI assistant proxy (Google Gemini)
// ============================================================
// The browser NEVER calls Gemini directly and never sees the API
// key. The widget posts a message here; this controller forwards
// it to the Gemini free-tier API using the server-side
// GEMINI_API_KEY and returns the assistant's reply.
//
// Escalation: the model is instructed to append the marker
// [[ESCALATE]] when a human representative should take over
// (pricing negotiation, complaints, account/legal issues, or
// anything it cannot confidently answer). We strip the marker and
// surface an `escalate` flag so the UI can offer the Contact page.
// ============================================================
const axios = require('axios');
const GEMINI_MODEL = process.env.GEMINI_MODEL || 'gemini-2.5-flash';
const GEMINI_URL =
`https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent`;
// Persona / knowledge for the assistant.
const SYSTEM_PROMPT = `You are "Ava", the AI virtual assistant for AI-Solutions, a Sunderland-based
start-up that uses artificial intelligence to improve the digital employee experience. AI-Solutions
offers AI-powered virtual assistants, rapid affordable prototyping, and bespoke software solutions
that speed up design, engineering and innovation for industry clients.
Your job: answer visitor questions about the company, its services, past projects, events and how to
get in touch. Be concise (2-4 sentences), warm, and professional. Never invent specific prices,
contracts, or personal data.
Escalate to a human by ending your reply with the exact marker [[ESCALATE]] when: the visitor asks
for pricing/quotes, wants to book or schedule a demo, raises a complaint, asks something you cannot
answer confidently, or explicitly asks to speak to a person. When you escalate, briefly tell them a
representative will help and suggest the Contact Us form.`;
// Keyword fallback so escalation still works if the model forgets the marker.
const ESCALATION_HINTS = [
'human', 'representative', 'agent', 'real person', 'speak to someone',
'price', 'pricing', 'quote', 'cost', 'complaint', 'refund', 'book a demo',
'schedule a demo', 'sales',
];
function looksLikeEscalation(text) {
const t = (text || '').toLowerCase();
return ESCALATION_HINTS.some(k => t.includes(k));
}
// POST /api/chat body: { message, history?: [{role, text}] }
async function chat(req, res, next) {
try {
const message = (req.body.message || '').toString().trim();
if (!message) {
return res.status(400).json({ message: 'Please enter a message.' });
}
if (message.length > 1000) {
return res.status(400).json({ message: 'Message is too long (max 1000 characters).' });
}
// Graceful degradation when the key isn't configured.
if (!process.env.GEMINI_API_KEY) {
return res.json({
reply:
"I'm not fully online right now, but our team would love to help. " +
'Please use the Contact Us page and someone will get back to you shortly.',
escalate: true,
});
}
// Build conversation history (last 8 turns) in Gemini's format.
const history = Array.isArray(req.body.history) ? req.body.history.slice(-8) : [];
const contents = history
.filter(h => h && h.text)
.map(h => ({
role: h.role === 'assistant' || h.role === 'model' ? 'model' : 'user',
parts: [{ text: String(h.text).slice(0, 1000) }],
}));
contents.push({ role: 'user', parts: [{ text: message }] });
const { data } = await axios.post(
`${GEMINI_URL}?key=${process.env.GEMINI_API_KEY}`,
{
system_instruction: { parts: [{ text: SYSTEM_PROMPT }] },
contents,
generationConfig: { temperature: 0.6, maxOutputTokens: 400, topP: 0.9 },
},
{ headers: { 'Content-Type': 'application/json' }, timeout: 20000 }
);
let reply =
data?.candidates?.[0]?.content?.parts?.map(p => p.text).join(' ').trim() || '';
let escalate = false;
if (reply.includes('[[ESCALATE]]')) {
escalate = true;
reply = reply.replace(/\[\[ESCALATE\]\]/g, '').trim();
}
// Fallback signal from the user's own words.
if (!escalate && looksLikeEscalation(message)) escalate = true;
if (!reply) {
reply =
"I'm sorry, I didn't quite catch that. Could you rephrase, or reach our team via the Contact Us page?";
escalate = true;
}
return res.json({ reply, escalate });
} catch (err) {
// Don't leak provider errors to the client — degrade gracefully.
console.error('[Chat] Gemini error:', err.response?.data?.error?.message || err.message);
return res.json({
reply:
"I'm having trouble reaching my AI service right now. Our team can help directly — " +
'please use the Contact Us page and we will be in touch.',
escalate: true,
});
}
}
module.exports = { chat };
+56
View File
@@ -0,0 +1,56 @@
// ============================================================
// contactController.js — Public "Contact Us" inquiry submission
// ============================================================
// Customers do NOT need an account or password to submit an
// inquiry. The 7 CSE fields are validated (see validate.js),
// sanitised, stored in the `inquiries` table, and logged.
// ============================================================
const pool = require('../db');
const { log } = require('../utils/logger');
const { sanitize } = require('../utils/validator');
const { verifyTurnstile } = require('../utils/turnstile');
// POST /api/contact
async function submitInquiry(req, res, next) {
try {
// Protect the public form with the existing Cloudflare Turnstile.
const captchaOk = await verifyTurnstile(req.body.turnstileToken);
if (!captchaOk) {
await log(null, 'CAPTCHA_FAILED', 'failed', 'Turnstile failed on Contact Us submission', req);
return res.status(400).json({ message: 'CAPTCHA verification failed. Please try again.' });
}
const full_name = sanitize(req.body.full_name || '');
const email = sanitize(req.body.email || '').toLowerCase().trim();
const phone = sanitize(req.body.phone || '');
const company = sanitize(req.body.company || '');
const country = sanitize(req.body.country || '');
const job_title = sanitize(req.body.job_title || '');
const job_details = sanitize(req.body.job_details || '');
const result = await pool.query(
`INSERT INTO inquiries (full_name, email, phone, company, country, job_title, job_details)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id, created_at`,
[full_name, email, phone || null, company || null, country || null, job_title || null, job_details]
);
await log(
null,
'INQUIRY_RECEIVED',
'success',
`New customer inquiry from "${full_name}" (${email})${company ? ` @ ${company}` : ''}`,
req
);
return res.status(201).json({
message: 'Thank you! Your inquiry has been received. Our team will be in touch shortly.',
inquiryId: result.rows[0].id,
});
} catch (err) {
next(err);
}
}
module.exports = { submitInquiry };
@@ -0,0 +1,136 @@
// ============================================================
// publicContentController.js — Public, read-only website content
// ============================================================
// These endpoints power the public marketing pages. They expose
// only ACTIVE / PUBLISHED rows. No authentication is required.
// ============================================================
const pool = require('../db');
// GET /api/content/solutions
async function getSolutions(req, res, next) {
try {
const result = await pool.query(
`SELECT id, title, summary, description, icon
FROM solutions
WHERE is_active = true
ORDER BY sort_order ASC, id ASC`
);
return res.json({ solutions: result.rows });
} catch (err) {
next(err);
}
}
// GET /api/content/case-studies
async function getCaseStudies(req, res, next) {
try {
const result = await pool.query(
`SELECT id, title, client, industry, summary, outcome, image_url, created_at
FROM case_studies
ORDER BY created_at DESC, id DESC`
);
return res.json({ caseStudies: result.rows });
} catch (err) {
next(err);
}
}
// GET /api/content/feedback
async function getFeedback(req, res, next) {
try {
const result = await pool.query(
`SELECT id, customer_name, company, rating, comment, created_at
FROM feedback
WHERE is_published = true
ORDER BY created_at DESC, id DESC`
);
// Average rating for a quick "social proof" headline figure
const avg = result.rows.length
? result.rows.reduce((sum, r) => sum + r.rating, 0) / result.rows.length
: 0;
return res.json({
feedback: result.rows,
averageRating: Math.round(avg * 10) / 10,
count: result.rows.length,
});
} catch (err) {
next(err);
}
}
// GET /api/content/articles
async function getArticles(req, res, next) {
try {
const result = await pool.query(
`SELECT id, slug, title, excerpt, cover_image, author, published_at
FROM articles
WHERE is_published = true
ORDER BY published_at DESC, id DESC`
);
return res.json({ articles: result.rows });
} catch (err) {
next(err);
}
}
// GET /api/content/articles/:slug
async function getArticleBySlug(req, res, next) {
try {
const { slug } = req.params;
const result = await pool.query(
`SELECT id, slug, title, excerpt, body, cover_image, author, published_at
FROM articles
WHERE slug = $1 AND is_published = true`,
[slug]
);
if (result.rows.length === 0) {
return res.status(404).json({ message: 'Article not found.' });
}
return res.json({ article: result.rows[0] });
} catch (err) {
next(err);
}
}
// GET /api/content/events
async function getEvents(req, res, next) {
try {
const result = await pool.query(
`SELECT id, title, description, location, event_date, is_upcoming, cover_image
FROM events
ORDER BY event_date DESC NULLS LAST, id DESC`
);
return res.json({
upcoming: result.rows.filter(e => e.is_upcoming),
past: result.rows.filter(e => !e.is_upcoming),
});
} catch (err) {
next(err);
}
}
// GET /api/content/gallery
async function getGallery(req, res, next) {
try {
const result = await pool.query(
`SELECT g.id, g.image_url, g.caption, g.created_at, e.title AS event_title
FROM gallery_images g
LEFT JOIN events e ON e.id = g.event_id
ORDER BY g.created_at DESC, g.id DESC`
);
return res.json({ gallery: result.rows });
} catch (err) {
next(err);
}
}
module.exports = {
getSolutions,
getCaseStudies,
getFeedback,
getArticles,
getArticleBySlug,
getEvents,
getGallery,
};
+29
View File
@@ -0,0 +1,29 @@
// ============================================================
// db.js — PostgreSQL database connection
// ============================================================
// We use the 'pg' package to talk to PostgreSQL.
// A "Pool" keeps multiple connections open so requests don't
// have to wait for a single connection to free up.
// ============================================================
const { Pool } = require('pg');
// Read database settings from .env file
const pool = new Pool({
host: process.env.DB_HOST, // e.g. 'localhost'
port: process.env.DB_PORT, // e.g. 5432
database: process.env.DB_NAME, // e.g. 'auth_db'
user: process.env.DB_USER, // e.g. 'postgres'
password: process.env.DB_PASSWORD, // your postgres password
});
// Test the connection when the server starts
pool.connect((err) => {
if (err) {
console.error('Database connection error:', err.message);
} else {
console.log('Connected to PostgreSQL database!');
}
});
module.exports = pool;
+15
View File
@@ -0,0 +1,15 @@
123456
password
123456789
qwerty
12345678
abc123
password123
111111
123123
admin
letmein
welcome
iloveyou
000000
1234
+62
View File
@@ -0,0 +1,62 @@
// ============================================================
// authMiddleware.js — JWT + session validation
// ============================================================
// Every protected route runs this middleware first.
// It checks two things:
// 1. Is the JWT signature valid and not expired?
// 2. Does this session (jti) still exist in the sessions table?
// → If "logout all devices" was called, all sessions are
// deleted, so even a valid JWT gets rejected here.
// ============================================================
const jwt = require('jsonwebtoken');
const pool = require('../db');
async function authenticate(req, res, next) {
const token = req.cookies.token;
if (!token) {
return res.status(401).json({ message: 'Not authenticated. Please login.' });
}
try {
// Step 1: Verify JWT signature and expiry
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Step 2: Check this session still exists in the DB
// This is what makes "logout all devices" work —
// deleting sessions from DB invalidates all existing tokens
const session = await pool.query(
'SELECT id FROM sessions WHERE jti = $1',
[decoded.jti]
);
if (session.rows.length === 0) {
return res.status(401).json({ message: 'Session expired or signed out. Please login again.' });
}
// Step 3: Update last_used_at to track device activity
await pool.query(
'UPDATE sessions SET last_used_at = NOW() WHERE jti = $1',
[decoded.jti]
);
req.user = decoded; // { id, username, role, jti }
req.userJti = decoded.jti; // shortcut for logout
next();
} catch (err) {
return res.status(401).json({ message: 'Session expired. Please login again.' });
}
}
// Middleware: Check if the user has admin role
// Must be used AFTER 'authenticate'
function requireAdmin(req, res, next) {
if (req.user.role !== 'admin') {
return res.status(403).json({ message: 'Admin access required.' });
}
next();
}
module.exports = { authenticate, requireAdmin };
+155
View File
@@ -0,0 +1,155 @@
// ============================================================
// validate.js — Express-validator validation rules + middleware
// ============================================================
// Centralizes request validation so controllers stay clean.
// Each route can pick the validation chain it needs.
// ============================================================
const { body, query, validationResult } = require('express-validator');
// Middleware: run after validation chains — returns 400 if any field is invalid
function handleValidationErrors(req, res, next) {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const messages = errors.array().map(e => e.msg);
return res.status(400).json({ message: messages[0], errors: messages });
}
next();
}
// ---- Auth validation chains --------------------------------
const loginRules = [
body('email')
.trim()
.notEmpty().withMessage('Email is required.')
.isEmail().withMessage('Invalid email address.'),
body('password')
.notEmpty().withMessage('Password is required.'),
body('turnstileToken')
.notEmpty().withMessage('CAPTCHA token is required.'),
];
const verifyOtpRules = [
body('userId')
.notEmpty().withMessage('User ID is required.')
.isInt({ min: 1 }).withMessage('Invalid user ID.'),
body('otp')
.notEmpty().withMessage('OTP is required.')
.isLength({ min: 6, max: 6 }).withMessage('OTP must be 6 digits.')
.isNumeric().withMessage('OTP must be numeric.'),
];
const requestOtpRules = [
body('userId')
.notEmpty().withMessage('User ID is required.')
.isInt({ min: 1 }).withMessage('Invalid user ID.'),
];
const changePasswordRules = [
body('oldPassword')
.notEmpty().withMessage('Current password is required.'),
body('newPassword')
.notEmpty().withMessage('New password is required.')
.isLength({ min: 8 }).withMessage('New password must be at least 8 characters.')
.matches(/[A-Z]/).withMessage('New password must contain an uppercase letter.')
.matches(/[a-z]/).withMessage('New password must contain a lowercase letter.')
.matches(/[0-9]/).withMessage('New password must contain a number.')
.matches(/[^a-zA-Z0-9]/).withMessage('New password must contain a special character.'),
];
const forgotPasswordRules = [
body('email')
.trim()
.notEmpty().withMessage('Email is required.')
.isEmail().withMessage('Invalid email address.'),
];
const resetPasswordRules = [
body('userId')
.notEmpty().withMessage('User ID is required.')
.isInt({ min: 1 }).withMessage('Invalid user ID.'),
body('otp')
.notEmpty().withMessage('OTP is required.')
.isLength({ min: 6, max: 6 }).withMessage('OTP must be 6 digits.')
.isNumeric().withMessage('OTP must be numeric.'),
body('newPassword')
.notEmpty().withMessage('New password is required.')
.isLength({ min: 8 }).withMessage('New password must be at least 8 characters.')
.matches(/[A-Z]/).withMessage('New password must contain an uppercase letter.')
.matches(/[a-z]/).withMessage('New password must contain a lowercase letter.')
.matches(/[0-9]/).withMessage('New password must contain a number.')
.matches(/[^a-zA-Z0-9]/).withMessage('New password must contain a special character.'),
];
const verifyChangePwdLinkRules = [
body('id')
.notEmpty().withMessage('User ID is required.'),
body('token')
.notEmpty().withMessage('Token is required.'),
body('newPassword')
.notEmpty().withMessage('New password is required.')
.isLength({ min: 8 }).withMessage('New password must be at least 8 characters.')
.matches(/[A-Z]/).withMessage('New password must contain an uppercase letter.')
.matches(/[a-z]/).withMessage('New password must contain a lowercase letter.')
.matches(/[0-9]/).withMessage('New password must contain a number.')
.matches(/[^a-zA-Z0-9]/).withMessage('New password must contain a special character.'),
];
// ---- Public "Contact Us" validation chain ------------------
const contactRules = [
body('full_name')
.trim()
.notEmpty().withMessage('Full name is required.')
.isLength({ max: 120 }).withMessage('Full name is too long.'),
body('email')
.trim()
.notEmpty().withMessage('Email is required.')
.isEmail().withMessage('Please enter a valid email address.'),
body('phone')
.optional({ checkFalsy: true })
.trim()
.isLength({ max: 40 }).withMessage('Phone number is too long.'),
body('company')
.optional({ checkFalsy: true })
.trim()
.isLength({ max: 160 }).withMessage('Company name is too long.'),
body('country')
.optional({ checkFalsy: true })
.trim()
.isLength({ max: 80 }).withMessage('Country is too long.'),
body('job_title')
.optional({ checkFalsy: true })
.trim()
.isLength({ max: 120 }).withMessage('Job title is too long.'),
body('job_details')
.trim()
.notEmpty().withMessage('Please tell us about your requirements.')
.isLength({ min: 5, max: 5000 }).withMessage('Job details must be 5-5000 characters.'),
body('turnstileToken')
.notEmpty().withMessage('Please complete the CAPTCHA challenge.'),
];
// ---- Admin validation chains --------------------------------
const adminLogsRules = [
query('page').optional().isInt({ min: 1 }).withMessage('Page must be a positive integer.'),
query('limit').optional().isInt({ min: 1, max: 100 }).withMessage('Limit must be 1-100.'),
query('action').optional().isString().trim(),
query('status').optional().isIn(['success', 'failed', 'warning']).withMessage('Status must be success, failed, or warning.'),
query('search').optional().isString().trim(),
];
module.exports = {
handleValidationErrors,
loginRules,
verifyOtpRules,
requestOtpRules,
changePasswordRules,
forgotPasswordRules,
resetPasswordRules,
verifyChangePwdLinkRules,
contactRules,
adminLogsRules,
};
+1697
View File
File diff suppressed because it is too large. Load diff
+27
View File
@@ -0,0 +1,27 @@
{
"name": "auth-backend",
"version": "1.0.0",
"description": "Secure authentication backend using Node.js, Express, and PostgreSQL",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"dependencies": {
"axios": "^1.6.0",
"bcryptjs": "^3.0.3",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"express-rate-limit": "^7.1.5",
"express-validator": "^7.3.2",
"helmet": "^7.1.0",
"jsonwebtoken": "^9.0.2",
"nodemailer": "^8.0.3",
"pg": "^8.11.3"
},
"devDependencies": {
"nodemon": "^3.0.2"
}
}
+27
View File
@@ -0,0 +1,27 @@
// ============================================================
// adminRoutes.js — Admin-only API routes
// Every route requires: logged in (JWT + active session) + admin.
// Sole purpose: review Contact Us inquiries.
// ============================================================
const express = require('express');
const router = express.Router();
const { authenticate, requireAdmin } = require('../middleware/authMiddleware');
const {
getStats,
getInquiries,
getInquiry,
setInquiryRead,
deleteInquiry,
} = require('../controllers/adminController');
// Apply auth + admin guard to every route in this file.
router.use(authenticate, requireAdmin);
router.get('/stats', getStats);
router.get('/inquiries', getInquiries);
router.get('/inquiries/:id', getInquiry);
router.patch('/inquiries/:id/read', setInquiryRead);
router.delete('/inquiries/:id', deleteInquiry);
module.exports = router;
+76
View File
@@ -0,0 +1,76 @@
// ============================================================
// authRoutes.js — All authentication API routes
// ============================================================
const express = require('express');
const router = express.Router();
const {
login,
requestOTP,
verifyOTP,
refreshToken,
changePassword,
forgotPassword,
resetPassword,
requestChangePasswordLink,
verifyChangePasswordLink,
logout,
logoutAll,
getSessions,
getMe,
} = require('../controllers/authController');
const { authenticate } = require('../middleware/authMiddleware');
const {
handleValidationErrors,
loginRules,
verifyOtpRules,
requestOtpRules,
changePasswordRules,
forgotPasswordRules,
resetPasswordRules,
verifyChangePwdLinkRules,
} = require('../middleware/validate');
// POST /api/auth/login — Check email + password, send OTP
router.post('/login', loginRules, handleValidationErrors, login);
// POST /api/auth/request-otp — Resend OTP to user (for "resend" button)
router.post('/request-otp', requestOtpRules, handleValidationErrors, requestOTP);
// POST /api/auth/verify-otp — Submit OTP to complete login
router.post('/verify-otp', verifyOtpRules, handleValidationErrors, verifyOTP);
// POST /api/auth/refresh-token — Get a new access token using refresh token
router.post('/refresh-token', refreshToken);
// POST /api/auth/change-password — Change password (must be logged in)
router.post('/change-password', authenticate, changePasswordRules, handleValidationErrors, changePassword);
// POST /api/auth/request-change-password-link — Send email link
router.post('/request-change-password-link', authenticate, requestChangePasswordLink);
// POST /api/auth/verify-change-password-link — Set new password from link
router.post('/verify-change-password-link', verifyChangePwdLinkRules, handleValidationErrors, verifyChangePasswordLink);
// POST /api/auth/forgot-password — Send OTP to email for password reset
router.post('/forgot-password', forgotPasswordRules, handleValidationErrors, forgotPassword);
// POST /api/auth/reset-password — Verify OTP and set new password
router.post('/reset-password', resetPasswordRules, handleValidationErrors, resetPassword);
// GET /api/auth/sessions — List all active sessions for this user
router.get('/sessions', authenticate, getSessions);
// POST /api/auth/logout — Logout this device only
router.post('/logout', authenticate, logout);
// POST /api/auth/logout-all — Logout ALL devices
router.post('/logout-all', authenticate, logoutAll);
// GET /api/auth/me — Get current user info (must be logged in)
router.get('/me', authenticate, getMe);
module.exports = router;
+39
View File
@@ -0,0 +1,39 @@
// ============================================================
// publicRoutes.js — Public website API (no authentication)
// ============================================================
const express = require('express');
const router = express.Router();
const { submitInquiry } = require('../controllers/contactController');
const { chat } = require('../controllers/chatController');
const {
getSolutions,
getCaseStudies,
getFeedback,
getArticles,
getArticleBySlug,
getEvents,
getGallery,
} = require('../controllers/publicContentController');
const { handleValidationErrors, contactRules } = require('../middleware/validate');
// ---- Contact Us form -------------------------------------
// POST /api/contact — submit a customer inquiry (7 CSE fields, Turnstile-protected)
router.post('/contact', contactRules, handleValidationErrors, submitInquiry);
// ---- AI assistant chat proxy (Google Gemini) -------------
// POST /api/chat — forwards to Gemini server-side; key never leaves the backend
router.post('/chat', chat);
// ---- Public content (read-only) --------------------------
router.get('/content/solutions', getSolutions);
router.get('/content/case-studies', getCaseStudies);
router.get('/content/feedback', getFeedback);
router.get('/content/articles', getArticles);
router.get('/content/articles/:slug', getArticleBySlug);
router.get('/content/events', getEvents);
router.get('/content/gallery', getGallery);
module.exports = router;
+210
View File
@@ -0,0 +1,210 @@
// ============================================================
// seed.js — Seed the AI-Solutions database
// ============================================================
// Creates the single admin account (there is no public sign-up)
// and loads sample public website content so every page renders.
//
// Run from the backend folder: node seed.js
// Idempotent: re-running resets sample content and upserts admin.
// ============================================================
require('dotenv').config({ path: require('path').resolve(__dirname, '../.env') });
const pool = require('./db');
const { generateSalt, hashPassword } = require('./utils/hash');
// ---- Default admin credentials (change after first login) ----
const ADMIN = {
username: 'admin',
email: process.env.SEED_ADMIN_EMAIL || 'admin@ai-solutions.com',
password: process.env.SEED_ADMIN_PASSWORD || 'Admin@2026!',
};
const solutions = [
{ title: 'AI Virtual Assistants & Chatbots', icon: 'robot', sort_order: 1,
summary: 'Conversational AI that handles routine customer and employee queries 24/7 and escalates to a human when needed.',
description: 'We design and deploy AI assistants — built on large language models with retrieval-augmented generation — that answer questions from your own knowledge base, automate common requests such as order tracking or IT password resets, and hand over to a human agent with full context when a query is complex or sensitive.' },
{ title: 'Intelligent Document Processing', icon: 'code', sort_order: 2,
summary: 'Extract, classify and validate data from invoices, forms and contracts automatically using OCR and NLP.',
description: 'Manual data entry is slow and error-prone. Our document-processing pipelines combine optical character recognition with natural-language models to read structured and unstructured documents, extract the fields that matter, and push clean data straight into your finance or back-office systems.' },
{ title: 'Predictive Analytics & Forecasting', icon: 'chart', sort_order: 3,
summary: 'Machine-learning models for demand forecasting, churn prediction and predictive maintenance.',
description: 'We build and validate models on your historical data to forecast demand, anticipate equipment failures before they happen, and flag customers at risk of churning — turning the data you already collect into decisions you can act on.' },
{ title: 'Process Automation (RPA + AI)', icon: 'bolt', sort_order: 4,
summary: 'Automate repetitive, rules-based workflows and augment them with AI judgement.',
description: 'By combining robotic process automation with AI decisioning, we remove the repetitive digital tasks that slow teams down — from onboarding and approvals to reconciliation — freeing people to focus on work that needs human judgement.' },
{ title: 'Computer Vision & Quality Inspection', icon: 'spark', sort_order: 5,
summary: 'Automated visual inspection and image recognition for manufacturing and operations.',
description: 'Our computer-vision solutions detect defects on production lines, read labels and serial numbers, and monitor sites in real time, delivering consistent quality checks at a speed and scale that manual inspection cannot match.' },
];
const caseStudies = [
{ title: 'AI service-desk assistant deflecting routine IT tickets', client: 'A national logistics operator', industry: 'Logistics',
summary: 'An AI virtual assistant was integrated into the internal IT service desk to handle password resets, system access requests, status updates and "how-to" questions for depot and driver staff.',
outcome: 'A large share of tier-1 requests were resolved automatically without an agent, with anything complex escalated to the support team with full context — reducing wait times for staff and freeing agents for higher-value work.',
image_url: 'https://picsum.photos/seed/logistics/800/500' },
{ title: 'Predictive maintenance reducing unplanned downtime', client: 'A precision manufacturer', industry: 'Manufacturing',
summary: 'Machine-learning models were trained on sensor and maintenance data to predict equipment failures on a production line before they occurred.',
outcome: 'Early-warning alerts allowed maintenance to be scheduled proactively rather than reactively, cutting unplanned downtime and extending the working life of critical machinery.',
image_url: 'https://picsum.photos/seed/factory/800/500' },
{ title: 'Automated claims intake with intelligent document processing', client: 'A regional insurer', industry: 'Insurance',
summary: 'OCR and natural-language models were used to read incoming claim forms and supporting documents and extract the data needed to open and triage a case.',
outcome: 'Claims that previously required manual keying were processed in minutes, improving turnaround times while handlers focused on assessment rather than data entry.',
image_url: 'https://picsum.photos/seed/insurance/800/500' },
{ title: 'Demand forecasting to improve stock availability', client: 'A multi-site retailer', industry: 'Retail',
summary: 'A forecasting model combined sales history, seasonality and promotional calendars to predict demand at store and product level.',
outcome: 'More accurate forecasts reduced both stockouts and overstock, improving on-shelf availability while lowering the working capital tied up in inventory.',
image_url: 'https://picsum.photos/seed/retail/800/500' },
];
const feedback = [
{ customer_name: 'Sarah Whitfield', company: 'National logistics operator', rating: 5,
comment: 'Their AI service-desk assistant handles the routine questions our team used to drown in, and the hand-off to a human is genuinely seamless. Delivered faster than we expected.' },
{ customer_name: 'David Olsen', company: 'Precision manufacturer', rating: 5,
comment: 'The predictive-maintenance models have already flagged issues before they became failures. Pragmatic, expert and easy to work with.' },
{ customer_name: 'Priya Nair', company: 'Regional insurer', rating: 4,
comment: 'Automating our claims intake removed a huge amount of manual data entry. A few tweaks were needed but support was excellent throughout.' },
{ customer_name: 'Marcus Lee', company: 'Multi-site retailer', rating: 5,
comment: 'Demand forecasting finally gave us a real handle on stock. On-shelf availability is up and we are holding far less dead inventory.' },
{ customer_name: 'Elena Costa', company: 'Customer services team', rating: 4,
comment: 'Professional, responsive and genuinely invested in our success. The chatbot has noticeably cut our call volume.' },
];
const articles = [
{ slug: 'ai-assistants-it-service-desks', title: 'How AI Virtual Assistants Are Transforming IT Service Desks',
excerpt: 'A look at how conversational AI is deflecting routine tickets and improving employee support in real organisations.',
cover_image: 'https://picsum.photos/seed/servicedesk/800/450',
body: 'The IT service desk is one of the most common — and most successful — places organisations deploy AI today. A large proportion of the requests that reach a service desk are repetitive: password resets, software access, "how do I…" questions and status updates.\n\nModern AI assistants, built on large language models connected to a company\'s own knowledge base, can resolve many of these requests instantly and around the clock. Crucially, a well-designed assistant recognises the limits of what it can safely answer and escalates to a human agent — with the full conversation history attached — whenever a request is complex, sensitive or unusual.\n\nThe result is not the removal of human agents but the redirection of their time: routine volume is absorbed by the assistant, while skilled staff focus on the incidents that genuinely need them. This is the model AI-Solutions builds towards for every assistant we deliver.' },
{ slug: 'predictive-maintenance-machine-learning', title: 'Predictive Maintenance: Using Machine Learning to Cut Downtime',
excerpt: 'How manufacturers use sensor data and machine learning to fix equipment before it breaks.',
cover_image: 'https://picsum.photos/seed/maintenance/800/450',
body: 'Unplanned downtime is one of the largest hidden costs in manufacturing. Traditional maintenance is either reactive — fixing machines after they fail — or calendar-based, replacing parts on a fixed schedule whether they need it or not.\n\nPredictive maintenance takes a different approach. By training machine-learning models on the data that equipment already produces — vibration, temperature, current draw and error logs — it becomes possible to detect the subtle patterns that precede a failure and to act before the breakdown happens.\n\nIn practice this means maintenance can be scheduled at the right moment: late enough to get full value from a component, early enough to avoid an unplanned stoppage. For the manufacturers we work with, that balance translates directly into higher output and lower cost.' },
{ slug: 'intelligent-document-processing-finance', title: 'Intelligent Document Processing in Financial Services',
excerpt: 'Turning invoices, forms and contracts into clean data with OCR and natural-language AI.',
cover_image: 'https://picsum.photos/seed/documents/800/450',
body: 'Financial services run on documents — invoices, claims, statements, contracts and forms — and historically much of that information has been moved into systems by hand. Manual keying is slow, expensive and prone to error.\n\nIntelligent document processing combines optical character recognition, which converts images of text into machine-readable characters, with natural-language models that understand context. Together they can locate and extract the specific fields a process needs, validate them against business rules, and route anything uncertain to a person for review.\n\nThe pattern is widely applicable: accounts-payable automation, claims intake, customer onboarding and compliance checks all benefit. The goal is straightforward — let software handle the predictable extraction work, and let people handle the judgement.' },
{ slug: 'rag-enterprise-knowledge', title: 'Retrieval-Augmented Generation: Grounding AI in Your Own Data',
excerpt: 'Why RAG is the practical way to make AI assistants accurate and trustworthy for business use.',
cover_image: 'https://picsum.photos/seed/rag/800/450',
body: 'Large language models are powerful, but on their own they can answer confidently from general knowledge that may be out of date or simply wrong for your business. Retrieval-augmented generation, or RAG, is the technique that addresses this.\n\nInstead of relying only on the model\'s memory, a RAG system first retrieves the most relevant passages from a trusted source — your documentation, policies or product data — and gives them to the model as context when it answers. The response is therefore grounded in your own, current information, and can cite where it came from.\n\nFor organisations, this is the difference between an interesting demo and a system they can rely on. It is the foundation of the AI assistants AI-Solutions deploys, because accuracy and trust matter more than novelty.' },
];
// event_date stored as YYYY-MM-DD; is_upcoming controls the page it appears on.
const events = [
{ title: 'AI for the Workplace — Sunderland Summit', location: 'Sunderland Software Centre',
event_date: '2026-09-18', is_upcoming: true,
description: 'A half-day summit exploring practical AI adoption for regional employers, featuring live demos of our virtual assistant.',
cover_image: 'https://picsum.photos/seed/summit/800/500' },
{ title: 'Hands-on Prototyping Workshop', location: 'Online (Webinar)',
event_date: '2026-07-30', is_upcoming: true,
description: 'A free interactive workshop showing how to take an idea to a working prototype using AI-assisted tooling.',
cover_image: 'https://picsum.photos/seed/workshop/800/500' },
{ title: 'North East Tech Expo 2026', location: 'Newcastle Exhibition Centre',
event_date: '2026-03-12', is_upcoming: false,
description: 'We showcased our latest digital employee experience tooling to over 400 visitors at the region’s flagship technology expo.',
cover_image: 'https://picsum.photos/seed/expo/800/500' },
{ title: 'Innovation Showcase Evening', location: 'Sunderland City Hall',
event_date: '2025-11-20', is_upcoming: false,
description: 'An evening demonstrating real industry solutions delivered by AI-Solutions, with talks from our client partners.',
cover_image: 'https://picsum.photos/seed/showcase/800/500' },
];
// Gallery images keyed to the past events by index after insert.
const galleryFor = (pastEventIds) => ([
{ event_idx: 0, image_url: 'https://picsum.photos/seed/g1/600/400', caption: 'Our stand at the North East Tech Expo' },
{ event_idx: 0, image_url: 'https://picsum.photos/seed/g2/600/400', caption: 'Live virtual assistant demo' },
{ event_idx: 1, image_url: 'https://picsum.photos/seed/g3/600/400', caption: 'Client partner talk at the Innovation Showcase' },
{ event_idx: 1, image_url: 'https://picsum.photos/seed/g4/600/400', caption: 'Networking at Sunderland City Hall' },
{ event_idx: 0, image_url: 'https://picsum.photos/seed/g5/600/400', caption: 'The AI-Solutions team' },
{ event_idx: 1, image_url: 'https://picsum.photos/seed/g6/600/400', caption: 'Prototyping in action' },
].map(g => ({ ...g, event_id: pastEventIds[g.event_idx] || null })));
async function seed() {
const client = await pool.connect();
try {
await client.query('BEGIN');
// ---- Admin (upsert) ----
const hash = hashPassword(ADMIN.password, generateSalt());
await client.query(
`INSERT INTO users (username, email, password_hash, role, email_verified, password_changed_at)
VALUES ($1, $2, $3, 'admin', true, NOW())
ON CONFLICT (email) DO UPDATE
SET password_hash = EXCLUDED.password_hash,
role = 'admin',
email_verified = true,
failed_attempts = 0,
locked_until = NULL`,
[ADMIN.username, ADMIN.email, hash]
);
// ---- Reset + load sample content ----
await client.query('TRUNCATE solutions, case_studies, feedback, articles, gallery_images, events RESTART IDENTITY CASCADE');
for (const s of solutions) {
await client.query(
`INSERT INTO solutions (title, summary, description, icon, sort_order, is_active)
VALUES ($1,$2,$3,$4,$5,true)`,
[s.title, s.summary, s.description, s.icon, s.sort_order]
);
}
for (const c of caseStudies) {
await client.query(
`INSERT INTO case_studies (title, client, industry, summary, outcome, image_url)
VALUES ($1,$2,$3,$4,$5,$6)`,
[c.title, c.client, c.industry, c.summary, c.outcome, c.image_url]
);
}
for (const f of feedback) {
await client.query(
`INSERT INTO feedback (customer_name, company, rating, comment, is_published)
VALUES ($1,$2,$3,$4,true)`,
[f.customer_name, f.company, f.rating, f.comment]
);
}
for (const a of articles) {
await client.query(
`INSERT INTO articles (slug, title, excerpt, body, cover_image, is_published, published_at)
VALUES ($1,$2,$3,$4,$5,true,NOW())`,
[a.slug, a.title, a.excerpt, a.body, a.cover_image]
);
}
const pastEventIds = [];
for (const e of events) {
const r = await client.query(
`INSERT INTO events (title, description, location, event_date, is_upcoming, cover_image)
VALUES ($1,$2,$3,$4,$5,$6) RETURNING id, is_upcoming`,
[e.title, e.description, e.location, e.event_date, e.is_upcoming, e.cover_image]
);
if (!r.rows[0].is_upcoming) pastEventIds.push(r.rows[0].id);
}
for (const g of galleryFor(pastEventIds)) {
await client.query(
`INSERT INTO gallery_images (event_id, image_url, caption) VALUES ($1,$2,$3)`,
[g.event_id, g.image_url, g.caption]
);
}
await client.query('COMMIT');
console.log('\n AI-Solutions database seeded successfully.');
console.log(' --------------------------------------------');
console.log(` Admin login: ${ADMIN.email}`);
console.log(` Password: ${ADMIN.password}`);
console.log(' (Change this after your first login.)\n');
} catch (err) {
await client.query('ROLLBACK');
console.error('\n Seed failed:', err.message, '\n');
process.exitCode = 1;
} finally {
client.release();
await pool.end();
}
}
seed();
+152
View File
@@ -0,0 +1,152 @@
// ============================================================
// server.js — Main Express server entry point
// ============================================================
// Load environment variables from the single root .env file
require('dotenv').config({ path: require('path').resolve(__dirname, '../.env') });
// ---- Validate required environment variables at startup -----
const REQUIRED_ENV = ['DB_HOST', 'DB_PORT', 'DB_NAME', 'DB_USER', 'DB_PASSWORD', 'JWT_SECRET', 'TURNSTILE_SECRET_KEY'];
const missing = REQUIRED_ENV.filter(key => !process.env[key]);
if (missing.length > 0) {
console.error(`FATAL: Missing required environment variables: ${missing.join(', ')}`);
console.error('Please check your .env file.');
process.exit(1);
}
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const rateLimit = require('express-rate-limit');
const crypto = require('crypto');
const pool = require('./db');
const authRoutes = require('./routes/authRoutes');
const adminRoutes = require('./routes/adminRoutes');
const publicRoutes = require('./routes/publicRoutes');
const app = express();
// ---- Security: HTTP headers --------------------------------
app.use(helmet());
// ---- CORS: Only allow requests from our React frontend -----
// FRONTEND_URL may be a comma-separated list of allowed origins.
// In development we also allow any localhost / 127.0.0.1 port so the
// dev server can run on 3000, 5001, etc. without breaking fetches.
const allowedOrigins = (process.env.FRONTEND_URL || 'http://localhost:3000')
.split(',')
.map(s => s.trim())
.filter(Boolean);
app.use(cors({
origin(origin, callback) {
// Allow non-browser clients (curl, server-to-server) with no Origin header.
if (!origin) return callback(null, true);
if (allowedOrigins.includes(origin)) return callback(null, true);
if (process.env.NODE_ENV !== 'production' &&
/^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin)) {
return callback(null, true);
}
return callback(new Error('Not allowed by CORS'));
},
credentials: true,
}));
// ---- Body Parser: Read JSON from request body --------------
app.use(express.json());
// ---- Cookie Parser: Read cookies from requests -------------
app.use(cookieParser());
// ---- CSRF Protection (Double Submit Cookie) ----------------
// Generate a CSRF token and set it as a readable cookie.
// The frontend must send it back in the X-CSRF-Token header.
// This protects state-changing endpoints from cross-site attacks.
app.use((req, res, next) => {
// Only enforce CSRF on state-changing methods
const safeMethods = ['GET', 'HEAD', 'OPTIONS'];
if (safeMethods.includes(req.method)) {
// For safe methods, issue/refresh the CSRF cookie if missing
if (!req.cookies.csrfToken) {
const csrfToken = crypto.randomBytes(32).toString('hex');
const isProduction = process.env.NODE_ENV === 'production';
res.cookie('csrfToken', csrfToken, {
httpOnly: false, // frontend JS needs to read this
secure: isProduction,
sameSite: isProduction ? 'strict' : 'lax',
maxAge: 24 * 60 * 60 * 1000, // 24 hours
});
}
return next();
}
// For POST/PUT/PATCH/DELETE: validate the CSRF token
const cookieToken = req.cookies.csrfToken;
const headerToken = req.headers['x-csrf-token'];
if (!cookieToken || !headerToken || cookieToken !== headerToken) {
return res.status(403).json({ message: 'CSRF token validation failed.' });
}
next();
});
// ---- Rate Limiting: Max 100 requests per 15 minutes --------
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
message: { message: 'Too many requests. Please wait and try again.' },
});
app.use(limiter);
// ---- Routes -----------------------------------------------
app.use('/api/auth', authRoutes);
app.use('/api/admin', adminRoutes);
app.use('/api', publicRoutes); // /api/contact, /api/chat, /api/content/*
// ---- Health check route ------------------------------------
app.get('/', (req, res) => {
res.json({ message: 'AI-Solutions API is running!' });
});
// ---- Centralized Error Handler -----------------------------
// All controllers call next(err) instead of handling errors inline.
// This middleware catches them all in one place.
app.use((err, req, res, _next) => {
console.error(`[${new Date().toISOString()}] ${req.method} ${req.originalUrl} — Error:`, err.message);
// Don't leak internal details in production
const isProduction = process.env.NODE_ENV === 'production';
res.status(err.status || 500).json({
message: isProduction ? 'Server error. Please try again.' : err.message || 'Server error.',
});
});
// ---- Session Cleanup: Remove expired sessions --------------
// Runs every hour. Deletes sessions older than 1 hour (matching JWT expiry)
// and sessions whose refresh tokens have expired (7 days).
function cleanupExpiredSessions() {
pool.query(
`DELETE FROM sessions WHERE created_at < NOW() - INTERVAL '7 days'`
).then(result => {
if (result.rowCount > 0) {
console.log(`[Session Cleanup] Removed ${result.rowCount} expired session(s).`);
}
}).catch(err => {
console.error('[Session Cleanup] Error:', err.message);
});
}
// Run cleanup on startup and then every hour
cleanupExpiredSessions();
const CLEANUP_INTERVAL = 60 * 60 * 1000; // 1 hour
setInterval(cleanupExpiredSessions, CLEANUP_INTERVAL);
// ---- Start Server ------------------------------------------
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Backend server is running at http://localhost:${PORT}`);
});
+29
View File
@@ -0,0 +1,29 @@
// ============================================================
// deviceParser.js — Parse User-Agent into readable device info
// ============================================================
function parseDevice(userAgent) {
if (!userAgent) return 'Unknown Device';
// Detect OS
let os = 'Unknown OS';
if (/windows nt 10/i.test(userAgent)) os = 'Windows 10/11';
else if (/windows nt/i.test(userAgent)) os = 'Windows';
else if (/android/i.test(userAgent)) os = 'Android';
else if (/iphone/i.test(userAgent)) os = 'iPhone';
else if (/ipad/i.test(userAgent)) os = 'iPad';
else if (/mac os/i.test(userAgent)) os = 'macOS';
else if (/linux/i.test(userAgent)) os = 'Linux';
// Detect browser
let browser = 'Unknown Browser';
if (/edg\//i.test(userAgent)) browser = 'Edge';
else if (/opr\//i.test(userAgent)) browser = 'Opera';
else if (/chrome/i.test(userAgent)) browser = 'Chrome';
else if (/firefox/i.test(userAgent)) browser = 'Firefox';
else if (/safari/i.test(userAgent)) browser = 'Safari';
return `${browser} on ${os}`;
}
module.exports = { parseDevice };
+114
View File
@@ -0,0 +1,114 @@
// ============================================================
// email.js — Send emails via Gmail using Nodemailer
// ============================================================
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS,
},
});
// Send the OTP email to the user
async function sendOTPEmail(toEmail, username, otp) {
const mailOptions = {
from: `"Auth System" <${process.env.EMAIL_USER}>`,
to: toEmail,
subject: 'Your OTP Code',
html: `
<div style="font-family: Arial, sans-serif; max-width: 400px; margin: auto;
border: 1px solid #e5e7eb; border-radius: 8px; padding: 24px;">
<h2 style="color: #16a34a; margin-top: 0;">One-Time Password</h2>
<p>Hello <strong>${username}</strong>,</p>
<p>Your login OTP code is:</p>
<div style="font-size: 2rem; font-weight: bold; letter-spacing: 8px;
color: #16a34a; text-align: center; padding: 16px 0;">
${otp}
</div>
<p style="color: #6b7280; font-size: 0.9rem;">
This code expires in <strong>5 minutes</strong>.<br/>
If you did not request this, please ignore this email.
</p>
</div>
`,
};
await transporter.sendMail(mailOptions);
}
// Send the Change Password Link email
async function sendChangePasswordLink(toEmail, username, link) {
const mailOptions = {
from: `"Auth System" <${process.env.EMAIL_USER}>`,
to: toEmail,
subject: 'Password Change Request',
html: `
<div style="font-family: Arial, sans-serif; max-width: 400px; margin: auto;
border: 1px solid #e5e7eb; border-radius: 8px; padding: 24px;">
<h2 style="color: #1d4ed8; margin-top: 0;">Change Your Password</h2>
<p>Hello <strong>${username}</strong>,</p>
<p>You requested to change your password. Click the secure link below to set a new password:</p>
<div style="text-align: center; margin: 24px 0;">
<a href="${link}" style="background-color: #1d4ed8; color: white; padding: 12px 24px;
text-decoration: none; border-radius: 6px; font-weight: bold;">
Set New Password
</a>
</div>
<p style="color: #6b7280; font-size: 0.9rem;">
This link expires in <strong>15 minutes</strong>.<br/>
If you did not request this, please ignore this email and your password will remain unchanged.
</p>
</div>
`,
};
await transporter.sendMail(mailOptions);
}
// Send a new device login alert email
async function sendNewDeviceAlert(toEmail, username, deviceInfo, ipAddress, loginTime) {
const timeStr = new Date(loginTime).toLocaleString('en-US', {
weekday: 'short', year: 'numeric', month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit', timeZoneName: 'short',
});
const mailOptions = {
from: `"Auth System" <${process.env.EMAIL_USER}>`,
to: toEmail,
subject: 'New Device Login Detected',
html: `
<div style="font-family: Arial, sans-serif; max-width: 440px; margin: auto;
border: 1px solid #e5e7eb; border-radius: 8px; padding: 24px;">
<h2 style="color: #ea580c; margin-top: 0;">New Device Login</h2>
<p>Hello <strong>${username}</strong>,</p>
<p>We detected a new login to your account from a device we haven't seen before:</p>
<table style="width: 100%; border-collapse: collapse; margin: 16px 0; font-size: 0.9rem;">
<tr>
<td style="padding: 8px 12px; background: #f9fafb; border: 1px solid #e5e7eb; font-weight: 600; width: 100px;">Device</td>
<td style="padding: 8px 12px; border: 1px solid #e5e7eb;">${deviceInfo}</td>
</tr>
<tr>
<td style="padding: 8px 12px; background: #f9fafb; border: 1px solid #e5e7eb; font-weight: 600;">IP Address</td>
<td style="padding: 8px 12px; border: 1px solid #e5e7eb; font-family: monospace;">${ipAddress}</td>
</tr>
<tr>
<td style="padding: 8px 12px; background: #f9fafb; border: 1px solid #e5e7eb; font-weight: 600;">Time</td>
<td style="padding: 8px 12px; border: 1px solid #e5e7eb;">${timeStr}</td>
</tr>
</table>
<p style="color: #6b7280; font-size: 0.9rem;">
If this was you, no action is needed.<br/>
If you don't recognize this login, please <strong>change your password immediately</strong>
and log out of all devices from your dashboard.
</p>
</div>
`,
};
await transporter.sendMail(mailOptions);
}
module.exports = { sendOTPEmail, sendChangePasswordLink, sendNewDeviceAlert };
+19
View File
@@ -0,0 +1,19 @@
// ============================================================
// hash.js — Password hashing using bcrypt
// ============================================================
const bcrypt = require('bcryptjs');
function generateSalt() {
return bcrypt.genSaltSync(10);
}
function hashPassword(password, salt) {
return bcrypt.hashSync(password, salt);
}
function verifyPassword(inputPassword, storedHash) {
return bcrypt.compareSync(inputPassword, storedHash);
}
module.exports = { generateSalt, hashPassword, verifyPassword };
+66
View File
@@ -0,0 +1,66 @@
// ============================================================
// logger.js — Save activity logs to the database
// ============================================================
// Every important action (login, register, OTP, etc.) calls
// this function to leave a record in the logs table.
// ============================================================
const pool = require('../db');
// Actions — use these constants everywhere so spelling is consistent
const ACTIONS = {
REGISTER_SUCCESS: 'REGISTER_SUCCESS',
REGISTER_FAILED: 'REGISTER_FAILED',
LOGIN_SUCCESS: 'LOGIN_SUCCESS',
LOGIN_FAILED: 'LOGIN_FAILED',
ACCOUNT_LOCKED: 'ACCOUNT_LOCKED',
OTP_SENT: 'OTP_SENT',
OTP_RESENT: 'OTP_RESENT',
OTP_VERIFIED: 'OTP_VERIFIED',
OTP_FAILED: 'OTP_FAILED',
OTP_EXPIRED: 'OTP_EXPIRED',
LOGOUT: 'LOGOUT',
CHANGE_PASSWORD: 'CHANGE_PASSWORD',
CHANGE_PASSWORD_FAILED:'CHANGE_PASSWORD_FAILED',
ADMIN_UNLOCK_USER: 'ADMIN_UNLOCK_USER',
ADMIN_DELETE_USER: 'ADMIN_DELETE_USER',
ADMIN_CHANGE_ROLE: 'ADMIN_CHANGE_ROLE',
CAPTCHA_FAILED: 'CAPTCHA_FAILED',
LOGOUT_ALL: 'LOGOUT_ALL',
FORGOT_PASSWORD: 'FORGOT_PASSWORD',
FORGOT_PASSWORD_FAILED:'FORGOT_PASSWORD_FAILED',
RESET_PASSWORD: 'RESET_PASSWORD',
RESET_PASSWORD_FAILED: 'RESET_PASSWORD_FAILED',
PASSWORD_EXPIRED: 'PASSWORD_EXPIRED',
NEW_DEVICE_LOGIN: 'NEW_DEVICE_LOGIN',
};
// Get IP address from the request object
function getIP(req) {
return (
req.headers['x-forwarded-for']?.split(',')[0]?.trim() ||
req.socket?.remoteAddress ||
'unknown'
);
}
// Write a log entry to the database
// userId — can be null (e.g. failed login where user doesn't exist)
// action — use ACTIONS constants above
// status — 'success' | 'failed' | 'warning'
// details — any extra human-readable info
async function log(userId, action, status, details, req) {
try {
const ip = req ? getIP(req) : 'system';
await pool.query(
`INSERT INTO logs (user_id, action, status, details, ip_address)
VALUES ($1, $2, $3, $4, $5)`,
[userId || null, action, status, details || null, ip]
);
} catch (err) {
// Never crash the app because logging failed
console.error('[Logger] Failed to write log:', err.message);
}
}
module.exports = { log, ACTIONS };
+30
View File
@@ -0,0 +1,30 @@
// ============================================================
// otp.js — One-Time Password (OTP) generator
// ============================================================
const crypto = require('crypto');
const bcrypt = require('bcryptjs');
// Generate a random 6-digit OTP using crypto.randomInt()
function generateOTP() {
return crypto.randomInt(100000, 1000000).toString();
}
// Get the expiry time: 5 minutes from now
function getOTPExpiry() {
const expiry = new Date();
expiry.setMinutes(expiry.getMinutes() + 5);
return expiry;
}
// Hash an OTP with bcrypt before storing in DB
function hashOTP(otp) {
return bcrypt.hashSync(String(otp), 10);
}
// Verify an OTP against a stored bcrypt hash
function verifyOTPHash(inputOTP, storedHash) {
return bcrypt.compareSync(String(inputOTP), storedHash);
}
module.exports = { generateOTP, getOTPExpiry, hashOTP, verifyOTPHash };
+30
View File
@@ -0,0 +1,30 @@
// ============================================================
// turnstile.js — Cloudflare Turnstile CAPTCHA verification
// ============================================================
// Shared helper so both the auth flow and the public Contact Us
// form can validate Turnstile tokens server-side against the
// existing TURNSTILE_SECRET_KEY. The browser never bypasses this.
// ============================================================
const axios = require('axios');
async function verifyTurnstile(token) {
// If no token supplied, fail closed.
if (!token) return false;
try {
const response = await axios.post(
'https://challenges.cloudflare.com/turnstile/v0/siteverify',
new URLSearchParams({
secret: process.env.TURNSTILE_SECRET_KEY,
response: token,
}),
{ headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
);
return response.data.success === true;
} catch (err) {
console.error('Turnstile verification error:', err.message);
return false;
}
}
module.exports = { verifyTurnstile };
+102
View File
@@ -0,0 +1,102 @@
// ============================================================
// validator.js — Input validation and sanitization
// ============================================================
// Always validate user input before storing it in the database.
// This protects against bad data and injection attacks.
// ============================================================
const fs = require('fs');
const path = require('path');
// Load simple leaked passwords dictionary into memory
let leakedPasswords = new Set();
try {
const filePath = path.join(__dirname, '..', 'leaked_passwords.txt');
const data = fs.readFileSync(filePath, 'utf8');
data.split(/\r?\n/).forEach(line => {
const pwd = line.trim();
if (pwd) leakedPasswords.add(pwd);
});
} catch (err) {
console.warn('Could not load leaked_passwords.txt. Leaked password checking is disabled.');
}
// Check if email format is valid (e.g. user@example.com)
function validateEmail(email) {
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return regex.test(email);
}
// Username: only letters, numbers, underscores. Length 3-30.
function validateUsername(username) {
const regex = /^[a-zA-Z0-9_]{3,30}$/;
return regex.test(username);
}
// Check if password exists in our leaked passwords file
function isLeakedPassword(password) {
return leakedPasswords.has(password);
}
// Password must be at least 8 characters and contain:
// - at least 1 uppercase letter
// - at least 1 lowercase letter
// - at least 1 number
// - at least 1 special character
function validatePassword(password) {
if (typeof password !== 'string' || password.length < 8) return false;
if (!/[A-Z]/.test(password)) return false; // uppercase
if (!/[a-z]/.test(password)) return false; // lowercase
if (!/[0-9]/.test(password)) return false; // digit
if (!/[^a-zA-Z0-9]/.test(password)) return false; // special char
return true;
}
// Returns a user-friendly message about what's missing from the password
function getPasswordErrors(password) {
const errors = [];
if (typeof password !== 'string') return ['Password is required.'];
if (password.length < 8) errors.push('at least 8 characters');
if (!/[A-Z]/.test(password)) errors.push('an uppercase letter');
if (!/[a-z]/.test(password)) errors.push('a lowercase letter');
if (!/[0-9]/.test(password)) errors.push('a number');
if (!/[^a-zA-Z0-9]/.test(password)) errors.push('a special character');
return errors;
}
// Sanitize input to prevent XSS (cross-site scripting)
// This escapes HTML special characters like < > & " '
function sanitize(input) {
if (typeof input !== 'string') return input;
return input
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#x27;');
}
// Password strength checker — returns 'weak', 'medium', or 'strong'
// Used on the frontend to show a live strength indicator
function checkPasswordStrength(password) {
let score = 0;
if (password.length >= 8) score++; // basic length
if (password.length >= 12) score++; // longer = better
if (/[A-Z]/.test(password)) score++; // has uppercase
if (/[0-9]/.test(password)) score++; // has number
if (/[^a-zA-Z0-9]/.test(password)) score++; // has special char
if (score <= 2) return 'weak';
if (score <= 3) return 'medium';
return 'strong';
}
module.exports = {
validateEmail,
validateUsername,
validatePassword,
getPasswordErrors,
isLeakedPassword,
sanitize,
checkPasswordStrength,
};