// Admin account route registration and profile helpers. module.exports = function registerAccountRoutes(app, deps) { const pool = deps.pool; const common = deps.common; const pages = deps.pages; const formatDashboardDate = deps.formatDashboardDate; const getAuditUserId = deps.getAuditUserId; const verifyPassword = deps.verifyPassword; const hashPassword = deps.hashPassword; const validatePasswordStrength = deps.validatePasswordStrength; const createUserSession = deps.createUserSession; const setSessionCookie = deps.setSessionCookie; app.get('/account', function (req, res) { res.send(pages.renderAccountPage(req.currentUser, req.query.message ? String(req.query.message) : '', '/dashboard')); }); app.post('/account/name', async function (req, res, next) { try { const name = String(req.body.name || '').trim(); if (!name) { return res.status(400).send('Name is required.'); } if (await common.fetchDuplicateName(pool, 'a_users', name, req.currentUser.id)) { return res.redirect('/account?message=' + encodeURIComponent('That name already exists.')); } const actorId = getAuditUserId(req); const [result] = await pool.query('UPDATE a_users SET name = ?, modified_by = ? WHERE id = ?', [name, actorId, req.currentUser.id]); if (!result.affectedRows) { return res.status(404).send('User not found.'); } res.redirect('/dashboard?message=' + encodeURIComponent('Name updated.')); } catch (error) { next(error); } }); app.post('/account/password', async function (req, res, next) { try { const currentPassword = String(req.body.current_password || ''); const newPassword = String(req.body.new_password || ''); const confirmPassword = String(req.body.confirm_password || ''); const [rows] = await pool.query('SELECT id, name, username, password_hash, password_salt, password_iterations FROM a_users WHERE id = ? LIMIT 1', [req.currentUser.id]); const user = rows[0] || null; if (!user) { return res.status(404).send('User not found.'); } if (!verifyPassword(currentPassword, user)) { return res.status(400).send('Current password is incorrect.'); } const passwordStrengthMessage = validatePasswordStrength(newPassword); if (passwordStrengthMessage) { return res.status(400).send(passwordStrengthMessage); } if (newPassword !== confirmPassword) { return res.status(400).send('New passwords do not match.'); } const passwordRecord = hashPassword(newPassword); await pool.query( 'UPDATE a_users SET password_hash = ?, password_salt = ?, password_iterations = ?, modified_by = ? WHERE id = ?', [passwordRecord.hash, passwordRecord.salt, passwordRecord.iterations, getAuditUserId(req), user.id] ); await pool.query('DELETE FROM a_sessions WHERE user_id = ?', [user.id]); const token = await createUserSession(pool, user.id); setSessionCookie(res, token); res.redirect('/account?message=' + encodeURIComponent('Password updated.')); } catch (error) { next(error); } }); };