const express = require('express'); const rateLimit = require('express-rate-limit'); const bcrypt = require('bcryptjs'); const QRCode = require('qrcode'); const prisma = require('../config/db'); const { encrypt, decrypt } = require('../utils/crypto'); const totp = require('../utils/totp'); const { audit } = require('../utils/audit'); const { protect, sessionToken, stepToken, adminFromToken } = require('../middleware/auth'); const router = express.Router(); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 20, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many attempts — wait a few minutes.' } }); const publicAdmin = a => ({ id: a.id, email: a.email, name: a.name, totpEnabled: a.totpEnabled, lastLoginAt: a.lastLoginAt }); async function finishLogin(req, res, admin) { const updated = await prisma.adminUser.update({ where: { id: admin.id }, data: { lastLoginAt: new Date() } }); req.admin = updated; await audit(req, 'login'); res.json({ token: sessionToken(updated), admin: publicAdmin(updated) }); } // Step 1: email + password → a two-factor step (or two-factor set-up on first login). router.post('/login', limiter, async (req, res) => { const { email, password } = req.body || {}; const admin = await prisma.adminUser.findUnique({ where: { email: String(email || '').trim().toLowerCase() } }); if (!admin || !(await bcrypt.compare(String(password || ''), admin.password))) { return res.status(401).json({ message: 'Wrong email or password.' }); } if (!admin.totpEnabled) return res.json({ setupRequired: true, setupToken: stepToken(admin, 'setup') }); res.json({ twoFactorRequired: true, challengeToken: stepToken(admin, 'totp') }); }); // Step 2: the authenticator code. router.post('/2fa', limiter, async (req, res) => { const admin = await adminFromToken(req.body?.challengeToken, 'totp'); if (!admin) return res.status(401).json({ message: 'That took too long — log in again.' }); if (!admin.totpSecret || !totp.verifyCode(decrypt(admin.totpSecret), req.body?.code)) { return res.status(401).json({ message: 'That code is not right. Check your authenticator app and try again.' }); } await finishLogin(req, res, admin); }); // First login: make a secret and show it as a QR code to scan. router.post('/2fa/setup', limiter, async (req, res) => { const admin = await adminFromToken(req.body?.setupToken, 'setup'); // Only while two-factor is still off: a set-up token can't replace a working secret. if (!admin || admin.totpEnabled) return res.status(401).json({ message: 'That took too long — log in again.' }); const secret = totp.generateSecret(); await prisma.adminUser.update({ where: { id: admin.id }, data: { totpSecret: encrypt(secret), totpEnabled: false } }); const url = totp.otpauthUrl(secret, admin.email); res.json({ secret, otpauthUrl: url, qrDataUrl: await QRCode.toDataURL(url) }); }); // ...then confirm with a code from the app, which turns two-factor on and logs in. router.post('/2fa/confirm', limiter, async (req, res) => { const admin = await adminFromToken(req.body?.setupToken, 'setup'); if (!admin || admin.totpEnabled || !admin.totpSecret) return res.status(401).json({ message: 'That took too long — log in again.' }); if (!totp.verifyCode(decrypt(admin.totpSecret), req.body?.code)) { return res.status(400).json({ message: 'That code is not right. Check the time on your phone and try again.' }); } const enabled = await prisma.adminUser.update({ where: { id: admin.id }, data: { totpEnabled: true } }); req.admin = enabled; await audit(req, 'two_factor_enabled'); await finishLogin(req, res, enabled); }); router.get('/me', protect, (req, res) => res.json(publicAdmin(req.admin))); // Sign out on every device (e.g. a lost laptop). router.post('/logout-everywhere', protect, async (req, res) => { await prisma.adminUser.update({ where: { id: req.admin.id }, data: { tokenVersion: { increment: 1 } } }); await audit(req, 'logout_everywhere'); res.json({ message: 'Signed out everywhere.' }); }); router.post('/password', protect, limiter, async (req, res) => { const { currentPassword, newPassword } = req.body || {}; if (!(await bcrypt.compare(String(currentPassword || ''), req.admin.password))) return res.status(400).json({ message: 'Your current password is not right.' }); if (String(newPassword || '').length < 12) return res.status(400).json({ message: 'Use at least 12 characters.' }); const updated = await prisma.adminUser.update({ where: { id: req.admin.id }, data: { password: await bcrypt.hash(newPassword, 12), tokenVersion: { increment: 1 } } }); await audit({ ...req, admin: updated }, 'password_changed'); res.json({ token: sessionToken(updated) }); }); module.exports = router;