/** * Cross Events' own sign-in, once sign-in goes through Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md ยง6). * Mounted after express.json, before the API: * * - Signing in, signing up, passwords, activation and 2FA here answer 409 `SIGN_IN_MOVED` with * where to go instead (the frontend forwards there). * - While a move runs, Events' own sign-in waits (503 `SIGN_IN_MOVING`). * - Changing my name, email or phone is done in Accounts (`PATCH /me` keeps the rest). * - An admin changing someone's name, email or phone (`PATCH /users/:id`) changes their account in * Accounts first (`people.update`), then Events' copy; a password or 2FA change is refused. */ import type { NextFunction, Request, Response } from 'express'; import { accounts, AccountsUnavailable } from './client'; import { getSetting, viaAccounts } from './mode'; import { RUNNING_KEY } from './move'; /* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */ const prisma = require('../config/db'); /* eslint-enable @typescript-eslint/no-require-imports */ const MOVED = [ 'POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/login/code/resend', 'POST /api/v2/auth/signup', 'POST /api/v2/auth/password/forgot', 'POST /api/v2/auth/password/reset', 'POST /api/v2/auth/activate', 'POST /api/v2/me/verify-password', 'POST /api/v2/me/close', ]; const MOVED_PREFIXES = ['POST /api/v2/me/two-factor/']; const LOCAL_SIGN_IN = ['POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/signup', 'POST /api/v2/auth/activate']; const movedAnswer = (res: Response) => res.status(409).json({ error: { code: 'SIGN_IN_MOVED', message: 'Signing in, passwords and two-step sign-in are now on your church account. Use "Sign in" to continue.', signInUrl: '/api/auth/signin', }, }); export async function signInGuard(req: Request, res: Response, next: NextFunction) { const key = `${req.method} ${req.path.replace(/\/+$/, '')}`; const isMoved = MOVED.includes(key) || MOVED_PREFIXES.some((p) => key.startsWith(p)); const isMe = key === 'PATCH /api/v2/me'; const isAdminEdit = /^PATCH \/api\/v2\/users\/[^/]+$/.test(key); if (!isMoved && !isMe && !isAdminEdit) return next(); try { if (!(await viaAccounts())) { if (LOCAL_SIGN_IN.includes(key)) { const running = await getSetting(RUNNING_KEY); if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) { return res.status(503).json({ error: { code: 'SIGN_IN_MOVING', message: 'One moment, we\'re updating the sign-in. Please try again in a minute.' } }); } } return next(); } if (isMoved) return movedAnswer(res); const body = (req.body ?? {}) as Record; if (isMe) { if (body.password !== undefined || body.currentPassword !== undefined) return movedAnswer(res); delete body.name; delete body.email; delete body.phone; return next(); } // An admin's change to someone (the route itself checks they're an admin). if (body.password !== undefined || body.twoFactorEnabled !== undefined) return movedAnswer(res); const changes: { name?: string; email?: string; phone?: string | null } = {}; if (typeof body.name === 'string') changes.name = body.name.trim(); if (typeof body.email === 'string') changes.email = body.email.trim().toLowerCase(); if (body.phoneNumber !== undefined) changes.phone = body.phoneNumber ? String(body.phoneNumber) : null; if (!Object.keys(changes).length) return next(); const target = await prisma.user.findUnique({ where: { id: String(req.params?.id ?? req.path.split('/').pop()) }, select: { id: true, accountId: true, name: true, email: true, phoneNumber: true } }); if (!target?.accountId) return next(); const differs = (changes.name !== undefined && changes.name !== target.name) || (changes.email !== undefined && changes.email !== target.email) || (changes.phone !== undefined && changes.phone !== target.phoneNumber); if (!differs) return next(); // Only for a signed-in admin: anyone else is refused by the route itself, untouched here. const admin = await signedInAdmin(req); if (!admin) return next(); await (await accounts()).request({ type: 'people.update', actor: admin.accountId, sub: target.accountId, ...changes }); return next(); } catch (e) { if (e instanceof AccountsUnavailable) return res.status(503).json({ error: { code: 'UNAVAILABLE', message: e.message } }); const err = e as { code?: string; message: string }; if (err.code === 'EMAIL_TAKEN') return res.status(409).json({ error: { code: 'CONFLICT', message: 'Another account has that email address.' } }); if (err.code) return res.status(502).json({ error: { code: 'UNAVAILABLE', message: `Accounts didn't accept the change: ${err.message}` } }); return next(e); } } /** * The request's user when it's a valid, current admin token (as `protect` + `admin` would accept, * not viewing as someone else), or null. Their `accountId` goes to Accounts' audit log. */ async function signedInAdmin(req: Request): Promise<{ id: string; accountId: string | null } | null> { try { const header = String(req.headers.authorization || ''); if (!header.startsWith('Bearer ')) return null; // eslint-disable-next-line @typescript-eslint/no-require-imports const jwt = require('jsonwebtoken'); const decoded = jwt.verify(header.slice(7), process.env.JWT_SECRET, { algorithms: ['HS256'] }) as { id?: string; tokenVersion?: number; imp?: string; asi?: string; mfa?: boolean }; // Viewing as someone, or an Accounts sign-in without the second step admins need. if (!decoded.id || decoded.imp || (decoded.asi && decoded.mfa !== true)) return null; const u = await prisma.user.findUnique({ where: { id: decoded.id }, select: { id: true, accountId: true, role: true, isActive: true, tokenVersion: true } }); if (!u || !u.isActive || u.role !== 'admin' || (decoded.tokenVersion ?? 0) !== u.tokenVersion) return null; return { id: u.id, accountId: u.accountId }; } catch { return null; } }