import { z } from 'zod'; import type { Request } from 'express'; import { defineRoute } from '../route'; import { single } from '../paging'; import { id } from '../schemas'; import auth from '../../middleware/authMiddleware'; import { signUp, logIn, verifyLoginCode, type Session } from '../../services/auth'; const requestInfo = (req: Request) => { const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string }; return { ip: getClientIp(req), userAgent: req.headers['user-agent'] }; }; const session = z.object({ status: z.literal('signed_in'), token: z.string().describe('Send as `Authorization: Bearer `'), user: z.object({ id, name: z.string(), email: z.string(), role: z.enum(['admin', 'supervisor', 'staff', 'user']) }), newsPromptPending: z.boolean().describe('Ask once whether they want News & announcements'), noticePromptPending: z.union([z.literal(false), z.enum(['first', 'updated'])]).describe('A privacy notice they must accept: never accepted (first) or a newer version (updated)'), deviceToken: z.string().optional().describe('With rememberDevice: send it with the next login to skip the code on this device'), }); const toSession = (s: Session): z.input => ({ status: 'signed_in', token: s.token, user: { id: s.id, name: s.name, email: s.email, role: s.role as 'admin' | 'supervisor' | 'staff' | 'user' }, newsPromptPending: s.newsPromptPending, noticePromptPending: s.noticePromptPending, ...(s.deviceToken ? { deviceToken: s.deviceToken } : {}), }); export const signup = defineRoute({ method: 'post', path: '/auth/signup', tag: 'Accounts', summary: 'Create an account', description: 'Signs the new account in straight away. `acceptTerms` must be true (the Terms of Use and Privacy Policy); `newsOptIn` is the unticked "News & announcements" box.', access: 'public', status: 201, body: z.object({ name: z.string().trim().min(1).max(200), email: z.email().max(200), password: z.string().min(8).max(200), phone: z.string().trim().max(40).optional(), notificationPreference: z.enum(['email', 'whatsapp', 'both']).optional().describe('WhatsApp needs a valid South African number; otherwise email is used'), newsOptIn: z.boolean().optional(), acceptTerms: z.literal(true), }), response: single(session), async handler({ body, req }) { const made = await signUp({ name: body.name, email: body.email, password: body.password, phoneNumber: body.phone, notificationPreference: body.notificationPreference, newsOptIn: body.newsOptIn }, requestInfo(req)); return { data: { status: 'signed_in' as const, token: made.token, user: { id: made.id, name: made.name, email: made.email, role: made.role }, newsPromptPending: false, noticePromptPending: false as const } }; }, }); export const login = defineRoute({ method: 'post', path: '/auth/login', tag: 'Accounts', summary: 'Log in', description: [ 'With an email address or phone number. Five wrong passwords lock the account for five minutes (`RATE_LIMITED`).', 'With two-factor authentication (always for supervisors and admins), the answer is `code_required`: a code was sent by email or WhatsApp — finish with `POST /auth/login/code`.', ].join('\n\n'), access: 'public', middleware: [auth.loginLimiter], body: z.object({ identifier: z.string().trim().min(1).max(200).describe('Email address or phone number'), password: z.string().min(1).max(200), deviceToken: z.string().max(500).optional().describe('From an earlier login with rememberDevice'), }), response: single(z.discriminatedUnion('status', [ session, z.object({ status: z.literal('code_required'), challengeId: z.string(), method: z.enum(['email', 'whatsapp']), destination: z.string().nullable().describe('Where the code went, partly hidden'), enrolling: z.boolean().describe('true = this turns two-factor on (required for the role)'), }), ])), async handler({ body, req }) { const result = await logIn(body, requestInfo(req)); if (result.status === 'signed_in') return { data: toSession(result.session) }; return { data: { status: 'code_required' as const, challengeId: result.challenge.challengeId, method: result.challenge.method as 'email' | 'whatsapp', destination: result.challenge.destination ?? null, enrolling: result.enrolling } }; }, }); export const loginCode = defineRoute({ method: 'post', path: '/auth/login/code', tag: 'Accounts', summary: 'Finish logging in with the code', access: 'public', middleware: [auth.loginLimiter], body: z.object({ challengeId: z.string().min(1).max(100), code: z.string().trim().min(4).max(12), rememberDevice: z.boolean().optional().describe('Skip the code on this device next time (30 days)'), }), response: single(session), async handler({ body, req }) { return { data: toSession(await verifyLoginCode(body, requestInfo(req))) }; }, });