chnages
chnages
This commit is contained in:
1 parent
3e22355510
commit
e22a8dc248
71 files changed
+24775
-1
No files matched your search
@@ -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,
|
||||
};
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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 };
|
||||
@@ -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,
|
||||
};
|
||||
Reference in new issue
Block a user