API v2 accounts and check-in (1.51.2)
- v2: auth/signup, auth/login (+ code step, rate limited), PATCH /me; check-in look-up and scan returning an outcome for every normal result. Campus rule as v1. - Sign up/login/2FA/profile moved to src/services/auth.ts; scan preview and scan to src/services/checkin.ts. v1 answers unchanged (ServiceError v1Status). - Login, 2FA step, sign up and profile/password pages use v2. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Ls1vMdg2GYqbnKZmPaX1ot
This commit is contained in:
@@ -24,7 +24,9 @@ jest.mock('../src/middleware/authMiddleware', () => {
|
||||
protect: (req: { user?: unknown }, res: { status(n: number): void }, next: (e?: Error) => void) => (signedIn ? ((req.user = signedIn), next()) : deny(401, 'Not authorized, no token')(req, res, next as (e: Error) => void)),
|
||||
optionalAuth: (req: { user?: unknown }, _res: unknown, next: () => void) => { if (signedIn) req.user = signedIn; next(); },
|
||||
admin: (req: { user?: { role: string } }, res: { status(n: number): void }, next: (e?: Error) => void) => (req.user?.role === 'admin' ? next() : deny(403, 'Not authorized as an admin')(req, res, next as (e: Error) => void)),
|
||||
staff: jest.fn(), supervisor: jest.fn(),
|
||||
staff: (req: { user?: { role: string } }, res: { status(n: number): void }, next: (e?: Error) => void) => (['admin', 'supervisor', 'staff'].includes(req.user?.role || '') ? next() : deny(403, 'Not authorized as staff')(req, res, next as (e: Error) => void)),
|
||||
supervisor: jest.fn(),
|
||||
loginLimiter: (_req: unknown, _res: unknown, next: () => void) => next(),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -32,6 +34,19 @@ jest.mock('../src/middleware/authMiddleware', () => {
|
||||
const mockServices = { createRegistration: jest.fn(), cancelRegistration: jest.fn(), startRegistrationCheckout: jest.fn() };
|
||||
jest.mock('../src/services/registrations', () => ({ createRegistration: (...a: unknown[]) => mockServices.createRegistration(...a), cancelRegistration: (...a: unknown[]) => mockServices.cancelRegistration(...a) }));
|
||||
jest.mock('../src/services/payments', () => ({ startRegistrationCheckout: (...a: unknown[]) => mockServices.startRegistrationCheckout(...a) }));
|
||||
const mockAuth = { signUp: jest.fn(), logIn: jest.fn(), verifyLoginCode: jest.fn(), updateProfile: jest.fn() };
|
||||
jest.mock('../src/services/auth', () => ({
|
||||
signUp: (...a: unknown[]) => mockAuth.signUp(...a), logIn: (...a: unknown[]) => mockAuth.logIn(...a),
|
||||
verifyLoginCode: (...a: unknown[]) => mockAuth.verifyLoginCode(...a), updateProfile: (...a: unknown[]) => mockAuth.updateProfile(...a),
|
||||
}));
|
||||
const mockCheckin = { previewScan: jest.fn(), scanTicket: jest.fn() };
|
||||
jest.mock('../src/services/checkin', () => ({ previewScan: (...a: unknown[]) => mockCheckin.previewScan(...a), scanTicket: (...a: unknown[]) => mockCheckin.scanTicket(...a) }));
|
||||
const mockScope = { scope: null as object | null, campusId: 'north' as string | null };
|
||||
jest.mock('../src/utils/campusScope', () => ({
|
||||
scopeFor: async () => mockScope.scope,
|
||||
eventOf: async () => ({ campusId: mockScope.campusId, campusName: 'North' }),
|
||||
canView: (scope: { campusIds: string[] }, campusId: string | null) => !campusId || scope.campusIds.includes(campusId),
|
||||
}));
|
||||
|
||||
import { v2Router } from '../src/v2';
|
||||
import { ServiceError } from '../src/services/errors';
|
||||
@@ -237,3 +252,87 @@ describe('the frontend types', () => {
|
||||
expect(saved).toBe(currentDocument());
|
||||
});
|
||||
});
|
||||
|
||||
describe('accounts', () => {
|
||||
const sess = { id: 'u1', name: 'Thandi', email: 't@x.co', role: 'user', token: 'jwt', newsPromptPending: true, noticePromptPending: false };
|
||||
|
||||
test('log in: a token, or a code to finish with', async () => {
|
||||
mockAuth.logIn.mockResolvedValueOnce({ status: 'signed_in', session: sess });
|
||||
const ok = await request(app).post('/api/v2/auth/login').send({ identifier: 't@x.co', password: 'secret' });
|
||||
expect(ok.body.data).toEqual({ status: 'signed_in', token: 'jwt', user: { id: 'u1', name: 'Thandi', email: 't@x.co', role: 'user' }, newsPromptPending: true, noticePromptPending: false });
|
||||
|
||||
mockAuth.logIn.mockResolvedValueOnce({ status: 'code_required', challenge: { challengeId: 'c1', method: 'email', destination: 't***@x.co' }, enrolling: true });
|
||||
const code = await request(app).post('/api/v2/auth/login').send({ identifier: 't@x.co', password: 'secret' });
|
||||
expect(code.body.data).toEqual({ status: 'code_required', challengeId: 'c1', method: 'email', destination: 't***@x.co', enrolling: true });
|
||||
// The token never comes with a code challenge.
|
||||
expect(code.body.data.token).toBeUndefined();
|
||||
});
|
||||
|
||||
test('a wrong password is UNAUTHENTICATED and a locked account RATE_LIMITED', async () => {
|
||||
mockAuth.logIn.mockRejectedValueOnce(new ServiceError(401, 'Invalid email or password', undefined, { v1Status: 400 }));
|
||||
expect((await request(app).post('/api/v2/auth/login').send({ identifier: 'a', password: 'b' })).body.error.code).toBe('UNAUTHENTICATED');
|
||||
mockAuth.logIn.mockRejectedValueOnce(new ServiceError(429, 'Too many attempts. Try again in 5 minute(s).'));
|
||||
const locked = await request(app).post('/api/v2/auth/login').send({ identifier: 'a', password: 'b' });
|
||||
expect([locked.status, locked.body.error.code]).toEqual([429, 'RATE_LIMITED']);
|
||||
});
|
||||
|
||||
test('sign up needs the terms accepted and a password of 8+', async () => {
|
||||
const bad = await request(app).post('/api/v2/auth/signup').send({ name: 'T', email: 't@x.co', password: 'short' });
|
||||
expect(Object.keys(bad.body.error.fields).sort()).toEqual(['acceptTerms', 'password']);
|
||||
mockAuth.signUp.mockResolvedValue({ id: 'u9', name: 'T', email: 't@x.co', role: 'user', token: 'jwt9' });
|
||||
const ok = await request(app).post('/api/v2/auth/signup').send({ name: 'T', email: 't@x.co', password: 'long-enough', acceptTerms: true, newsOptIn: true });
|
||||
expect(ok.status).toBe(201);
|
||||
expect(ok.body.data).toMatchObject({ status: 'signed_in', token: 'jwt9' });
|
||||
expect(mockAuth.signUp).toHaveBeenCalledWith(expect.objectContaining({ newsOptIn: true }), expect.any(Object));
|
||||
});
|
||||
|
||||
test('PATCH /me changes only what is sent and hands back a fresh token', async () => {
|
||||
signedIn = { id: 'u1', role: 'user' };
|
||||
mockAuth.updateProfile.mockResolvedValue({ user: { id: 'u1', name: 'New', email: 't@x.co', phoneNumber: null, role: 'user', twoFactorEnabled: false, notificationPreference: 'email', homeCampusId: null, createdAt: new Date('2026-01-01T00:00:00Z'), tokenVersion: 0 }, token: 'jwt2' });
|
||||
const res = await request(app).patch('/api/v2/me').send({ name: 'New' });
|
||||
expect(res.body).toMatchObject({ data: { name: 'New', phone: null }, token: 'jwt2' });
|
||||
expect(res.body.data.tokenVersion).toBeUndefined();
|
||||
expect(mockAuth.updateProfile).toHaveBeenCalledWith('u1', { name: 'New', phoneNumber: undefined }, expect.any(Object));
|
||||
});
|
||||
});
|
||||
|
||||
describe('check-in', () => {
|
||||
const ticket = { id: 't1', quantity: 2, isUsed: false, eventId: 'e1', event: { title: 'Youth Camp' }, registrationOption: { eventOption: { id: 'o1', name: 'Camper', isMainTicket: true } }, usages: [] };
|
||||
afterEach(() => { mockScope.scope = null; });
|
||||
|
||||
test('staff only', async () => {
|
||||
signedIn = { id: 'u1', role: 'user' };
|
||||
expect((await request(app).post('/api/v2/checkin/QR1').send({})).body.error.code).toBe('FORBIDDEN');
|
||||
});
|
||||
|
||||
test('every normal result is a 200 with an outcome', async () => {
|
||||
signedIn = { id: 's1', role: 'staff' };
|
||||
mockCheckin.scanTicket.mockResolvedValueOnce({ outcome: 'checked_in', message: 'Ticket scanned successfully (1 of 2 redeemed, 1 remaining)', session: null, ticketUsage: {}, ticket, qtyRedeemed: 1, totalRedeemed: 1, remaining: 1 });
|
||||
const ok = await request(app).post('/api/v2/checkin/QR1').send({ people: 1, eventId: 'e1' });
|
||||
expect(ok.body.data).toEqual({ outcome: 'checked_in', message: expect.any(String), ticket: { id: 't1', eventId: 'e1', eventTitle: 'Youth Camp', ticketName: 'Camper', quantity: 2 }, checkedIn: 1, remaining: 1, session: null, consentStatus: null, canOverride: false });
|
||||
expect(mockCheckin.scanTicket).toHaveBeenCalledWith('QR1', signedIn, expect.objectContaining({ qty: 1, eventId: 'e1' }), expect.anything());
|
||||
|
||||
mockCheckin.scanTicket.mockResolvedValueOnce({ outcome: 'consent_required', message: 'Parental consent is missing', consentStatus: 'missing', canOverride: false, ticket });
|
||||
const consent = await request(app).post('/api/v2/checkin/QR1').send({});
|
||||
expect(consent.status).toBe(200);
|
||||
expect(consent.body.data).toMatchObject({ outcome: 'consent_required', checkedIn: 0, consentStatus: 'missing' });
|
||||
|
||||
mockCheckin.scanTicket.mockResolvedValueOnce({ outcome: 'transferred', message: 'Given to Sipho' });
|
||||
expect((await request(app).post('/api/v2/checkin/QR1').send({})).body.data).toMatchObject({ outcome: 'transferred', ticket: null });
|
||||
});
|
||||
|
||||
test("campus-scoped staff can't check in another campus's ticket", async () => {
|
||||
signedIn = { id: 's1', role: 'staff' };
|
||||
mockScope.scope = { campusIds: ['south'] };
|
||||
const res = await request(app).post('/api/v2/checkin/QR1').send({});
|
||||
expect(res.body.error).toEqual({ code: 'FORBIDDEN', message: 'This ticket is for an event at North.' });
|
||||
expect(mockCheckin.scanTicket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('the preview names the holder and what is left', async () => {
|
||||
signedIn = { id: 's1', role: 'staff' };
|
||||
mockCheckin.previewScan.mockResolvedValue({ outcome: 'found', ticket: { ...ticket, consentStatus: 'not_required', remaining: 2, session: null, sessionError: null, registrationOption: { id: 'ro1', eventOption: { id: 'o1', name: 'Camper' }, variant: null }, event: { id: 'e1', title: 'Youth Camp' }, user: { id: 'u1', name: 'Thandi' }, attendee: { name: 'Lulu' } } });
|
||||
const res = await request(app).get('/api/v2/checkin/QR1');
|
||||
expect(res.body.data.ticket).toMatchObject({ holder: 'Lulu', remaining: 2, consentStatus: 'not_required' });
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user