const prisma = require('../config/db'); const { generateToken, hashPassword, comparePassword } = require('../config/auth'); const { v4: uuidv4 } = require('uuid'); const { safeErrorMessage } = require('../utils/errorUtils'); const { logSecurityEvent, getRecentSecurityEvents } = require('../utils/securityEvents'); const { METHODS: TWO_FACTOR_METHODS, availableMethods, createChallenge, verifyChallenge, resendChallenge, clearTrustedDevices, requiresTwoFactor, replaceRecoveryCodes, recoveryCodesLeft, clearTwoFactor, } = require('../utils/twoFactor'); // ─── Helpers ──────────────────────────────────────────────────────────────── // Sign up, log in and profile changes are shared with /api/v2 (TypeScript, 1.51.2). const accounts = require('../services/auth'); const { getOrgName, sendActivationLink, sendWelcomeEmail } = accounts; const { v1StatusOf } = require('../services/errors'); // Resolve a client IP from the request (works behind proxies) function getClientIp(req) { const forwarded = req.headers['x-forwarded-for']; if (forwarded) return forwarded.split(',')[0].trim(); return req.socket?.remoteAddress || 'unknown'; } // Errors from utils/twoFactor and the services carry their own HTTP status; everything else // follows the controller convention of res.status(...) before throwing. function errorStatus(error, res) { return v1StatusOf(error, res.statusCode === 200 ? 400 : res.statusCode); } // @desc Register a new user // @route POST /api/users // @access Public const registerUser = async (req, res) => { try { res.status(201).json(await accounts.signUp(req.body || {}, { ip: getClientIp(req), userAgent: req.headers['user-agent'] })); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc Auth user & get token // @route POST /api/users/login // @access Public const loginUser = async (req, res) => { try { const { email, password, deviceToken } = req.body || {}; const result = await accounts.logIn({ identifier: email, password, deviceToken }, { ip: getClientIp(req), userAgent: req.headers['user-agent'] }); if (result.status === 'code_required') { return res.json({ twoFactorRequired: true, ...(result.enrolling ? { enrolling: true } : {}), ...result.challenge }); } res.json(result.session); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc Second login step — exchange an emailed/WhatsApp code for a token // @route POST /api/users/login/2fa // @access Public const verifyLoginTwoFactor = async (req, res) => { try { const { challengeId, code, rememberDevice } = req.body || {}; res.json(await accounts.verifyLoginCode({ challengeId, code, rememberDevice }, { ip: getClientIp(req), userAgent: req.headers['user-agent'] })); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc Send a new code for a pending login challenge // @route POST /api/users/login/2fa/resend // @access Public const resendLoginTwoFactor = async (req, res) => { try { const { challengeId } = req.body || {}; res.json(await resendChallenge(challengeId, 'login')); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc Start turning on 2FA — sends a code to the chosen channel to prove it works // @route POST /api/users/2fa/enable // @access Private const startEnableTwoFactor = async (req, res) => { try { const { method, password } = req.body || {}; const user = await prisma.user.findUnique({ where: { id: req.user.id } }); if (!user) { res.status(404); throw new Error('User not found'); } if (typeof password !== 'string' || !(await comparePassword(password, user.password))) { res.status(400); throw new Error('Incorrect password'); } if (!TWO_FACTOR_METHODS.includes(method)) { res.status(400); throw new Error('Choose email, WhatsApp or an authenticator app for your verification codes'); } if (!(await availableMethods(user)).includes(method)) { res.status(400); throw new Error(method === 'whatsapp' ? 'WhatsApp codes aren\'t available for your account. Add a valid phone number or choose email.' : 'Add a valid email address to your profile before turning on two-factor authentication.'); } // Unlike login, don't fall back to email here — the point of this step is to // prove the channel the user picked actually reaches them. For an authenticator app the // answer carries the secret and its otpauth:// link (shown as a QR code) until confirmed. res.json(await createChallenge(user, 'enable', method, { allowFallback: false })); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc Finish turning on 2FA with the code that was sent // @route POST /api/users/2fa/confirm // @access Private const confirmEnableTwoFactor = async (req, res) => { try { const { challengeId, code } = req.body || {}; const challenge = await verifyChallenge(challengeId, code, 'enable', req.user.id); // An authenticator app: the confirmed secret is kept (encrypted). Another method: any app is // forgotten. Either way a fresh set of recovery codes, shown once (2.3.0). await prisma.user.update({ where: { id: req.user.id }, data: { twoFactorEnabled: true, twoFactorMethod: challenge.method, updatedAt: new Date(), ...(challenge.method === 'authenticator' ? { totpSecret: challenge.pendingSecret } : { totpSecret: null, totpLastStep: null }), }, }); await prisma.twoFactorChallenge.update({ where: { id: challenge.id }, data: { pendingSecret: null } }).catch(() => {}); const recoveryCodes = await replaceRecoveryCodes(req.user.id); logSecurityEvent({ userId: req.user.id, type: 'two_factor_enabled', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {}); res.json({ twoFactorEnabled: true, twoFactorMethod: challenge.method, recoveryCodes }); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc Turn off 2FA // @route POST /api/users/2fa/disable // @access Private const disableTwoFactor = async (req, res) => { try { const { password } = req.body || {}; const user = await prisma.user.findUnique({ where: { id: req.user.id } }); if (!user) { res.status(404); throw new Error('User not found'); } if (requiresTwoFactor(user)) { res.status(403); throw new Error("Two-factor authentication is required for your role and can't be turned off."); } if (typeof password !== 'string' || !(await comparePassword(password, user.password))) { res.status(400); throw new Error('Incorrect password'); } await prisma.user.update({ where: { id: user.id }, data: { ...(await clearTwoFactor(user.id)), updatedAt: new Date() }, }); await clearTrustedDevices(user.id); if (user.twoFactorEnabled) { logSecurityEvent({ userId: user.id, type: 'two_factor_disabled', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {}); } res.json({ twoFactorEnabled: false, twoFactorMethod: null }); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc A new set of recovery codes (the old ones stop working), shown once (2.3.0) // @route POST /api/v2/me/two-factor/recovery-codes // @access Private const replaceMyRecoveryCodes = async (req, res) => { try { const { password } = req.body || {}; const user = await prisma.user.findUnique({ where: { id: req.user.id } }); if (!user) { res.status(404); throw new Error('User not found'); } if (!user.twoFactorEnabled) { res.status(400); throw new Error('Turn on two-factor authentication first.'); } if (typeof password !== 'string' || !(await comparePassword(password, user.password))) { res.status(400); throw new Error('Incorrect password'); } const recoveryCodes = await replaceRecoveryCodes(user.id); logSecurityEvent({ userId: user.id, type: 'recovery_codes_replaced', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {}); res.json({ recoveryCodes }); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc Re-confirm the logged-in user's password without starting a new session // (the self-service kiosk uses this before letting the event be changed) // @route POST /api/users/verify-password // @access Private const verifyPassword = async (req, res) => { try { const { password } = req.body || {}; const user = await prisma.user.findUnique({ where: { id: req.user.id }, select: { password: true } }); if (!user || typeof password !== 'string' || !(await comparePassword(password, user.password))) { res.status(401); throw new Error('Incorrect password'); } res.json({ ok: true }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Get user profile // @route GET /api/users/profile // @access Private const getUserProfile = async (req, res) => { try { const user = await prisma.user.findUnique({ where: { id: req.user.id }, select: { id: true, name: true, email: true, role: true, phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, twoFactorMethod: true, createdAt: true, updatedAt: true, isActive: true, homeCampusId: true, newsAskedAt: true, noticeVersionAccepted: true } }); if (user) { const { newsAskedAt, noticeVersionAccepted, ...rest } = user; // newsPromptPending: they haven't answered the news opt-in question yet (asked once). // noticePromptPending: a privacy notice version they must accept has been published. const noticePromptPending = !req.impersonation && await require('../utils/privacyNotice').noticePromptPending({ noticeVersionAccepted }); // Campus-scoped staff: the campuses they're limited to (null = every campus). const campusScope = (await require('../utils/campusScope').scopeFor(req))?.campusIds || null; res.json({ ...rest, twoFactorRequired: requiresTwoFactor(user), recoveryCodesLeft: user.twoFactorEnabled ? await recoveryCodesLeft(user.id) : 0, newsPromptPending: !newsAskedAt && !req.impersonation, noticePromptPending, campusScope }); } else { res.status(404); throw new Error('User not found'); } } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Update user profile // @route PUT /api/users/profile // @access Private const updateUserProfile = async (req, res) => { try { const { user, twoFactorRequired, token } = await accounts.updateProfile(req.user.id, req.body || {}, { ip: getClientIp(req), userAgent: req.headers['user-agent'] }); res.json({ ...user, twoFactorRequired, token }); } catch (error) { res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) }); } }; // @desc Get all users // @route GET /api/users // @access Private/Admin const getUsers = async (req, res) => { try { const page = Math.max(1, parseInt(req.query.page) || 1); const limit = Math.min(200, Math.max(1, parseInt(req.query.limit) || 100)); const skip = (page - 1) * limit; const select = { id: true, name: true, email: true, role: true, phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, twoFactorMethod: true, createdAt: true, updatedAt: true, isActive: true }; // Build filters const where = {}; if (req.query.isActive !== undefined) { where.isActive = req.query.isActive === 'true'; } if (req.query.role) { where.role = req.query.role; } if (req.query.search) { const s = req.query.search.trim(); where.OR = [ { name: { contains: s, mode: 'insensitive' } }, { email: { contains: s, mode: 'insensitive' } }, { phoneNumber: { contains: s, mode: 'insensitive' } }, ]; } const [users, total] = await prisma.$transaction([ prisma.user.findMany({ where, select, orderBy: { name: 'asc' }, skip, take: limit }), prisma.user.count({ where }) ]); res.json({ data: users, total, page, limit, pages: Math.ceil(total / limit) }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Check whether an account already exists for a given email and/or phone // @route GET /api/users/check-exists // @access Private/Supervisor const checkUserExists = async (req, res) => { try { const email = typeof req.query.email === 'string' ? req.query.email.trim() : ''; const rawPhone = typeof req.query.phone === 'string' ? req.query.phone.trim() : ''; const { normalizeZAPhone } = require('../utils/whatsapp'); const phone = normalizeZAPhone(rawPhone) || (rawPhone ? rawPhone.replace(/\D/g, '') : ''); const phoneAlt = phone && phone.startsWith('27') ? '0' + phone.slice(2) : (phone && phone.length === 9 ? '27' + phone : null); const searchClauses = [ ...(email ? [{ email }] : []), ...(phone ? [{ phoneNumber: phone }] : []), ...(phoneAlt ? [{ phoneNumber: phoneAlt }] : []), ]; if (searchClauses.length === 0) { return res.json({ exists: false }); } const existingUser = await prisma.user.findFirst({ where: { OR: searchClauses }, select: { id: true, name: true, email: true, phoneNumber: true, notificationPreference: true }, }); const hasEmail = !!existingUser?.email && !existingUser.email.endsWith('@guest.local'); const hasPhone = !!existingUser?.phoneNumber; res.json({ exists: !!existingUser, hasEmail, hasPhone, // Safe-to-display fields only, for autofilling a lookup form — never the password. // Guest placeholder emails are withheld the same way hasEmail already treats them. // `id` lets the kiosk tell two different matched accounts apart (e.g. when the // typed email and phone number resolve to different people) — it's never shown, // only compared client-side, and this endpoint is already Private/Supervisor. user: existingUser ? { id: existingUser.id, name: existingUser.name, email: hasEmail ? existingUser.email : null, phoneNumber: hasPhone ? existingUser.phoneNumber : null, notificationPreference: existingUser.notificationPreference, } : null, }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Get user by ID // @route GET /api/users/:id // @access Private/Admin const getUserById = async (req, res) => { try { const user = await prisma.user.findUnique({ where: { id: req.params.id }, select: { id: true, name: true, email: true, role: true, phoneNumber: true, createdAt: true, updatedAt: true, isActive: true, scopedCampuses: { select: { id: true, name: true } } } }); if (user) { res.json(user); } else { res.status(404); throw new Error('User not found'); } } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Update user // @route PUT /api/users/:id // @access Private/Admin const updateUser = async (req, res) => { try { const user = await prisma.user.findUnique({ where: { id: req.params.id } }); if (!user) { res.status(404); throw new Error('User not found'); } const { name, email, role, isActive, phoneNumber, password, notificationPreference, twoFactorEnabled, scopedCampusIds } = req.body; const newPhone = phoneNumber !== undefined ? (phoneNumber || null) : user.phoneNumber; const { resolveNotificationPreference } = require('../utils/notificationPreference'); const newPref = resolveNotificationPreference(notificationPreference, newPhone, user.notificationPreference); // Prepare data update, allow admin to set a new password const data = { name: name || user.name, email: email || user.email, role: role || user.role, isActive: isActive !== undefined ? isActive : user.isActive, phoneNumber: newPhone, notificationPreference: newPref, updatedAt: new Date() }; if (password && typeof password === 'string' && password.trim().length > 0) { data.password = await hashPassword(password.trim()); } // Admins can switch 2FA off for someone who has lost access to their codes, // but never on — enabling requires the user to prove the channel themselves. const resetTwoFactor = twoFactorEnabled === false && user.twoFactorEnabled; if (resetTwoFactor) { // The app's secret and the recovery codes go too (2.3.0). Object.assign(data, await clearTwoFactor(user.id)); } // Promoted to a role that requires 2FA without having it: end their sessions // so the next login enrols them. const willHaveTwoFactor = resetTwoFactor ? false : user.twoFactorEnabled; if (!willHaveTwoFactor && data.role !== user.role && requiresTwoFactor({ role: data.role })) { data.tokenVersion = { increment: 1 }; } // Campus-scoped staff (utils/campusScope.js): "Limit to campuses" for supervisors and staff. // Admins and users are never limited, so a role change away from staff clears the limit. const before = await prisma.user.findUnique({ where: { id: user.id }, select: { scopedCampuses: { select: { id: true } } } }); const beforeIds = before.scopedCampuses.map(c => c.id).sort(); let afterIds = beforeIds; if (!['supervisor', 'staff'].includes(data.role)) afterIds = []; else if (Array.isArray(scopedCampusIds)) { const wanted = [...new Set(scopedCampusIds.filter(x => typeof x === 'string' && x))]; const found = await prisma.campus.findMany({ where: { id: { in: wanted } }, select: { id: true } }); if (found.length !== wanted.length) { res.status(400); throw new Error('One of those campuses doesn\'t exist.'); } afterIds = wanted.sort(); } const scopeChanged = afterIds.join(',') !== beforeIds.join(','); if (scopeChanged) data.scopedCampuses = { set: afterIds.map(id => ({ id })) }; const updatedUser = await prisma.user.update({ where: { id: req.params.id }, data, select: { id: true, name: true, email: true, role: true, phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, twoFactorMethod: true, createdAt: true, updatedAt: true, isActive: true, scopedCampuses: { select: { id: true, name: true } } } }); if (scopeChanged) { require('../utils/adminAudit').logAdminAction({ actorId: req.user.id, actorRole: req.user.role, action: 'user_campus_scope_changed', targetType: 'User', targetId: updatedUser.id, metadata: { from: beforeIds, to: afterIds }, ip: getClientIp(req) }); } if (resetTwoFactor || data.password) { await clearTrustedDevices(updatedUser.id); } if (resetTwoFactor) { logSecurityEvent({ userId: updatedUser.id, type: 'two_factor_disabled', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {}); } res.json(updatedUser); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Delete user // @route DELETE /api/users/:id // @access Private/Admin const deleteUser = async (req, res) => { try { const user = await prisma.user.findUnique({ where: { id: req.params.id } }); if (!user) { res.status(404); throw new Error('User not found'); } // Instead of deleting, we deactivate the user await prisma.user.update({ where: { id: req.params.id }, data: { isActive: false, updatedAt: new Date() } }); res.json({ message: 'User deactivated' }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Anonymize user data (GDPR / "right to be forgotten") // @route POST /api/users/:id/anonymize // @access Private/Admin const anonymizeUser = async (req, res) => { try { const user = await prisma.user.findUnique({ where: { id: req.params.id } }); if (!user) { res.status(404); throw new Error('User not found'); } const { deletionBlockers, anonymiseUser } = require('../utils/privacy'); const blockers = await deletionBlockers(user.id); if (blockers.length) { res.status(409); throw new Error(`Cancel (and refund where needed) these registrations first: ${blockers.map(b => b.eventTitle).join(', ')}.`); } const counts = await anonymiseUser(user.id); // An open deletion request from this person is now done. await prisma.dataRequest.updateMany({ where: { userId: user.id, type: 'deletion', status: 'open' }, data: { status: 'completed', closedAt: new Date(), handledById: req.user.id }, }); require('../utils/adminAudit').logAdminAction({ actorId: req.user.id, actorRole: req.user.role, action: 'user_anonymised', targetType: 'user', targetId: user.id, metadata: counts, ip: getClientIp(req), }); res.json({ message: 'User data deleted' }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Request password reset // @route POST /api/users/forgot // @access Public const requestPasswordReset = async (req, res) => { try { const { email } = req.body; if (!email || typeof email !== 'string') { res.status(400); throw new Error('Email is required'); } const user = await prisma.user.findUnique({ where: { email } }); // Security (1.51.17): the same answer, with the same status, whether or not an account has // this email — and it's sent before any work that only happens for real accounts, so the // response time doesn't tell either. The link is made and sent afterwards. res.json({ message: GENERIC_RESET_MESSAGE }); if (user) sendPasswordResetLink(user).catch(e => console.warn('[password reset] Failed:', e?.message || e)); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; const GENERIC_RESET_MESSAGE = 'If an account uses that email, we\'ve sent it a link to reset the password.'; /** A one-hour reset link for this account, by email (and WhatsApp when they prefer it). */ async function sendPasswordResetLink(user) { const token = uuidv4(); const expiresAt = new Date(Date.now() + 60 * 60 * 1000); // Invalidate previous tokens (optional) await prisma.passwordReset.updateMany({ where: { userId: user.id, used: false, expiresAt: { gt: new Date() } }, data: { used: true } }); await prisma.passwordReset.create({ data: { id: uuidv4(), userId: user.id, token, expiresAt, used: false } }); const baseUrl = process.env.FRONTEND_URL || process.env.APP_BASE_URL || 'http://localhost:3001'; const resetUrl = `${baseUrl.replace(/\/$/, '')}/reset-password?token=${encodeURIComponent(token)}`; const { sendMail, buildPasswordResetEmail } = require('../utils/email'); const emailContent = buildPasswordResetEmail({ name: user.name, resetUrl }); // Security: always email sendMail({ to: user.email, subject: 'Reset your password', ...emailContent }) .catch(e => console.warn('[password reset email] Failed:', e?.message || e)); // Also WhatsApp if preferred (security message — sent in addition to email) const { waText } = require('../utils/notify'); waText(user, emailContent.text).catch(() => {}); } // @desc Reset password using token // @route POST /api/users/reset // @access Public const resetPassword = async (req, res) => { try { const { token, password } = req.body; if (!token || !password) { res.status(400); throw new Error('Token and new password are required'); } // If PasswordReset model isn't available, avoid crashing and return a generic error if (!prisma.passwordReset || typeof prisma.passwordReset.findUnique !== 'function' || typeof prisma.passwordReset.update !== 'function') { res.status(400); throw new Error('Invalid or expired token'); } const reset = await prisma.passwordReset.findUnique({ where: { token } }); if (!reset || reset.used || reset.expiresAt < new Date()) { res.status(400); throw new Error('Invalid or expired token'); } const user = await prisma.user.findUnique({ where: { id: reset.userId } }); if (!user || !user.isActive) { res.status(400); throw new Error('User not found or inactive'); } const newHashed = await hashPassword(password); await prisma.$transaction([ prisma.user.update({ where: { id: user.id }, data: { password: newHashed, updatedAt: new Date() } }), prisma.passwordReset.update({ where: { token }, data: { used: true } }) ]); await clearTrustedDevices(user.id); logSecurityEvent({ userId: user.id, type: 'password_reset', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {}); res.json({ message: 'Password has been reset successfully' }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Activate account using token (for inactive/guest accounts) // @route POST /api/users/activate // @access Public const activateAccount = async (req, res) => { try { const { token, password } = req.body; if (!token || !password) { res.status(400); throw new Error('Token and password are required'); } if (typeof password !== 'string' || password.trim().length < 8) { res.status(400); throw new Error('Password must be at least 8 characters'); } if (!prisma.passwordReset || typeof prisma.passwordReset.findUnique !== 'function') { res.status(400); throw new Error('Invalid or expired token'); } const reset = await prisma.passwordReset.findUnique({ where: { token } }); if (!reset || reset.used || reset.expiresAt < new Date()) { res.status(400); throw new Error('Invalid or expired activation link'); } const user = await prisma.user.findUnique({ where: { id: reset.userId } }); if (!user) { res.status(400); throw new Error('User not found'); } const newHashed = await hashPassword(password.trim()); await prisma.$transaction([ prisma.user.update({ where: { id: user.id }, data: { password: newHashed, isActive: true, updatedAt: new Date() } }), prisma.passwordReset.update({ where: { token }, data: { used: true } }) ]); const updated = await prisma.user.findUnique({ where: { id: user.id }, select: { id: true, name: true, email: true, role: true, tokenVersion: true } }); // The activation form asks them to agree to the terms and privacy notice, as sign-up does. // Without it (an older page) they're asked once after login instead. if (req.body.acceptTerms === true) { await require('../utils/privacyNotice').acceptNotice(user.id, { source: 'activation', ip: getClientIp(req) }) .catch(e => console.warn('[activate] notice acceptance not saved:', e?.message || e)); } // Send welcome email (skip guest/placeholder accounts) if (updated.email && !updated.email.endsWith('@guest.local')) { sendWelcomeEmail(updated).catch(() => {}); } res.json({ message: 'Account activated successfully.', id: updated.id, name: updated.name, email: updated.email, role: updated.role, token: generateToken(updated.id, updated.role, updated.tokenVersion) }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Revoke all active sessions for the logged-in user (increments tokenVersion) // @route POST /api/users/revoke-sessions // @access Private const revokeMySession = async (req, res) => { try { const updated = await prisma.user.update({ where: { id: req.user.id }, data: { tokenVersion: { increment: 1 } }, select: { id: true, role: true, tokenVersion: true }, }); await clearTrustedDevices(updated.id); // Bumping tokenVersion invalidates every existing token, including the one // this request just used. Issue a fresh token for the current device so it // isn't logged out too. res.json({ message: 'All other sessions have been signed out.', token: generateToken(updated.id, updated.role, updated.tokenVersion), }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Admin: revoke all sessions for a specific user // @route POST /api/users/:id/revoke-sessions // @access Private/Admin const adminRevokeUserSessions = async (req, res) => { try { const target = await prisma.user.findUnique({ where: { id: req.params.id } }); if (!target) { res.status(404); throw new Error('User not found'); } await prisma.user.update({ where: { id: req.params.id }, data: { tokenVersion: { increment: 1 } }, }); await clearTrustedDevices(req.params.id); res.json({ message: `Sessions revoked for ${target.name}.` }); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Close (and optionally anonymise) the logged-in user's own account // @route POST /api/users/close-account // @access Private const closeAccount = async (req, res) => { try { const { deleteData = false, password } = req.body || {}; // Re-verify password before allowing account closure const user = await prisma.user.findUnique({ where: { id: req.user.id } }); if (!user) { res.status(404); throw new Error('User not found'); } const passwordOk = await comparePassword(password, user.password); if (!passwordOk) { res.status(400); throw new Error('Incorrect password'); } // Capture real details before any anonymisation so the email goes to the right address const realEmail = user.email; const realName = user.name; if (deleteData) { // POPIA: deleting personal data is a request an admin approves (see privacyController); // the account is closed straight away. const open = await prisma.dataRequest.findFirst({ where: { userId: user.id, type: 'deletion', status: 'open' } }); if (!open) await require('./privacyController').requestAccountDeletion(user); return res.json({ message: 'Your account is closed. Your personal information will be deleted once your request has been processed — we will email you.' }); } else { // Soft-deactivate only await prisma.user.update({ where: { id: req.user.id }, data: { isActive: false, tokenVersion: { increment: 1 }, updatedAt: new Date(), }, }); await clearTrustedDevices(req.user.id); // Send closure confirmation if (realEmail && !realEmail.endsWith('@deleted.invalid') && !realEmail.endsWith('@guest.local')) { const { sendMail, buildAccountClosedEmail } = require('../utils/email'); const { waText } = require('../utils/notify'); const { buildWAAccountClosed } = require('../utils/waMessages'); const content = buildAccountClosedEmail({ name: realName, dataDeleted: false }); sendMail({ to: realEmail, subject: `Your ${getOrgName()} account has been closed`, ...content }).catch(() => {}); waText(user, buildWAAccountClosed({ name: realName, dataDeleted: false })).catch(() => {}); } return res.json({ message: 'Your account has been deactivated.' }); } } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; // @desc Recent account activity (logins, password changes) for the current user // @route GET /api/users/activity // @access Private const getMyActivity = async (req, res) => { try { const events = await getRecentSecurityEvents(req.user.id, 10); res.json(events); } catch (error) { res.status(res.statusCode === 200 ? 400 : res.statusCode).json({ message: safeErrorMessage(error) }); } }; module.exports = { registerUser, loginUser, verifyLoginTwoFactor, resendLoginTwoFactor, startEnableTwoFactor, confirmEnableTwoFactor, disableTwoFactor, replaceMyRecoveryCodes, verifyPassword, getUserProfile, updateUserProfile, getUsers, checkUserExists, getUserById, updateUser, deleteUser, anonymizeUser, requestPasswordReset, resetPassword, activateAccount, revokeMySession, adminRevokeUserSessions, closeAccount, getMyActivity, sendActivationLink, };