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:
2026-10-29 09:31:00 +02:00
co-authored by Claude Opus 5.5
parent 440c43e530
commit 6816e8bc67
28 changed files with 3006 additions and 781 deletions
@@ -12,6 +12,7 @@ import { User, Lock, ShieldAlert, ShieldCheck, ShieldOff, Trash2, Clock, LogIn,
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { useCampuses } from "@/hooks/useCampuses";
import { apiV2 } from "@/lib/apiV2";
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string };
@@ -61,19 +62,18 @@ export default function UserProfilePage() {
setSavingProfile(true);
setProfileMsg(null);
try {
const res = await apiFetch<{ token?: string }>("/api/users/profile", {
method: "PUT",
const res = await apiV2("patch", "/me", {
authToken: token,
body: {
name,
email,
phoneNumber: phone || null,
phone: phone || null,
notificationPreference: hasValidPhone ? notifPref : "email",
...(campusInfo.enabled ? { homeCampusId: homeCampusId || null } : {}),
},
});
// Backend returns a refreshed token — save it so the session stays valid
if (res?.token) updateToken(res.token);
// A refreshed token comes back — save it so the session stays valid
updateToken(res.token);
setProfileMsg({ type: "ok", text: "Profile updated." });
} catch (e) {
setProfileMsg({ type: "err", text: errorMessage(e) || "Failed to update profile." });
@@ -103,12 +103,8 @@ export default function UserProfilePage() {
setSavingPw(true);
setPwMsg(null);
try {
const res = await apiFetch<{ token?: string }>("/api/users/profile", {
method: "PUT",
authToken: token,
body: { currentPassword, password: newPassword },
});
if (res?.token) updateToken(res.token);
const res = await apiV2("patch", "/me", { authToken: token, body: { currentPassword, password: newPassword } });
updateToken(res.token);
setCurrentPassword("");
setNewPassword("");
setConfirmPassword("");
@@ -1,12 +1,12 @@
"use client";
import React, { useMemo, useState } from "react";
import { useAuth } from "@/hooks/useAuth";
import { apiFetch } from "@/lib/api";
import { useDismissingState } from "@/hooks/useDismissingState";
import { useRouter } from "next/navigation";
import { KeyRound } from "lucide-react";
import { errorMessage } from "@/lib/utils";
import { BackLink } from "@/components/shared/BackLink";
import { apiV2 } from "@/lib/apiV2";
export default function ResetPasswordPage() {
const { token } = useAuth();
@@ -31,7 +31,7 @@ export default function ResetPasswordPage() {
if (!canSubmit) return;
try {
setLoading(true);
await apiFetch("/api/users/profile", { method: "PUT", authToken: token, body: { password, currentPassword: current } });
await apiV2("patch", "/me", { authToken: token, body: { password, currentPassword: current } });
setStatus("Your password has been updated successfully.");
setCurrent("");
setPassword("");
@@ -2,7 +2,15 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { apiFetch, ApiError } from "@/lib/api";
import { AuthResponse, AuthUser, TwoFactorChallenge, clearToken, getDeviceToken, getToken, isTwoFactorChallenge, saveDeviceToken, saveToken } from "@/lib/auth";
import { AuthResponse, AuthUser, TwoFactorChallenge, clearToken, getDeviceToken, getToken, saveDeviceToken, saveToken } from "@/lib/auth";
import { apiV2, type V2Result } from "@/lib/apiV2";
// A v2 "signed_in" answer as the session the app keeps (the user's fields plus the token).
type V2Session = Extract<V2Result<"/auth/login", "post">["data"], { status: "signed_in" }>;
const toAuthResponse = (s: V2Session): AuthResponse => ({
...s.user, token: s.token, newsPromptPending: s.newsPromptPending, noticePromptPending: s.noticePromptPending,
...(s.deviceToken ? { deviceToken: s.deviceToken } : {}),
});
export type AuthContextValue = {
user: AuthUser | null;
@@ -91,22 +99,21 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}, []);
const login = useCallback(async (email: string, password: string) => {
const res = await apiFetch<AuthResponse | TwoFactorChallenge>("/api/users/login", {
method: "POST",
body: { email, password, deviceToken: getDeviceToken() || undefined },
const { data } = await apiV2("post", "/auth/login", {
body: { identifier: email, password, deviceToken: getDeviceToken() || undefined },
});
// 2FA accounts get a challenge back instead of a token — nothing is saved
// until verifyTwoFactor exchanges the emailed/WhatsApp code for one.
if (isTwoFactorChallenge(res)) return res;
return startSession(res as AuthResponse);
if (data.status === "code_required") {
const challenge: TwoFactorChallenge = { twoFactorRequired: true, challengeId: data.challengeId, method: data.method, destination: data.destination || "", ...(data.enrolling ? { enrolling: true } : {}) };
return challenge;
}
return startSession(toAuthResponse(data));
}, [startSession]);
const verifyTwoFactor = useCallback(async (challengeId: string, code: string, rememberDevice: boolean) => {
const res = await apiFetch<AuthResponse>("/api/users/login/2fa", {
method: "POST",
body: { challengeId, code, rememberDevice },
});
return startSession(res);
const { data } = await apiV2("post", "/auth/login/code", { body: { challengeId, code, rememberDevice } });
return startSession(toAuthResponse(data));
}, [startSession]);
const resendTwoFactor = useCallback((challengeId: string) => {
@@ -117,11 +124,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}, []);
const register = useCallback(async (data: { name: string; email: string; password: string; phoneNumber?: string; notificationPreference?: "email" | "whatsapp" | "both"; newsOptIn?: boolean }) => {
const res = await apiFetch<AuthResponse>("/api/users", {
method: "POST",
body: data,
// The sign-up form only submits once "I agree to the Terms of Use and Privacy Policy" is ticked.
const { data: made } = await apiV2("post", "/auth/signup", {
body: {
name: data.name, email: data.email, password: data.password, acceptTerms: true,
...(data.phoneNumber ? { phone: data.phoneNumber } : {}),
...(data.notificationPreference ? { notificationPreference: data.notificationPreference } : {}),
...(data.newsOptIn !== undefined ? { newsOptIn: data.newsOptIn } : {}),
},
});
const { token, ...registeredUser } = res;
const { token, ...registeredUser } = toAuthResponse(made);
saveToken(token);
setToken(token);
setUser(registeredUser);
File diff suppressed because it is too large Load Diff
+562 -1
View File
@@ -157,7 +157,13 @@ export interface paths {
delete?: never;
options?: never;
head?: never;
patch?: never;
/**
* Change my details
* @description Only what is sent changes. A new `password` needs `currentPassword`; it sends a security notice and stops other devices skipping the 2FA code. The answer has a fresh `token` (the old one keeps working).
*
* **Who:** Any signed-in person.
*/
patch: operations["patchMe"];
trace?: never;
};
"/me/registrations": {
@@ -182,6 +188,104 @@ export interface paths {
patch?: never;
trace?: never;
};
"/checkin/{qrCode}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* Look a ticket up before checking it in
* @description Who it is for, how many are left to check in (for today's session on multi-day events, or `sessionId`), and parental consent. Nothing is changed.
*
* **Who:** Staff, supervisors and admins.
*/
get: operations["getCheckinQrCode"];
put?: never;
/**
* Check a ticket in
* @description Checks in everyone left on the ticket, or `people`. Every normal result is a 200 with an `outcome`:
*
* `checked_in`, `already_used`, `consent_required` (a supervisor can resend with `overrideConsent`, which is logged), `wrong_event`, `wrong_section`, `section_not_found`, `no_session` (multi-day: nothing open now), `locked` (offline-locked to another device) or `transferred` (handed on; `message` says to whom).
*
* An unknown code is `NOT_FOUND`.
*
* **Who:** Staff, supervisors and admins.
*/
post: operations["postCheckinQrCode"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/auth/signup": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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.
*
* **Who:** Anyone.
*/
post: operations["postAuthSignup"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/auth/login": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* 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`.
*
* **Who:** Anyone.
*/
post: operations["postAuthLogin"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/auth/login/code": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Finish logging in with the code
* @description **Who:** Anyone.
*/
post: operations["postAuthLoginCode"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
}
export type webhooks = Record<string, never>;
export interface components {
@@ -737,6 +841,9 @@ export interface operations {
/** @enum {string} */
role: "admin" | "supervisor" | "staff" | "user";
twoFactorEnabled: boolean;
/** @enum {string} */
notificationPreference: "email" | "whatsapp" | "both";
homeCampusId: string | null;
/** Format: date-time */
createdAt: string;
};
@@ -754,6 +861,76 @@ export interface operations {
};
};
};
patchMe: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
name?: string;
/** Format: email */
email?: string;
/** @description null or empty removes it */
phone?: string | null;
/** @enum {string} */
notificationPreference?: "email" | "whatsapp" | "both";
/** @description While campuses are on */
homeCampusId?: string | null;
password?: string;
currentPassword?: string;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
id: string;
name: string;
email: string;
phone: string | null;
/** @enum {string} */
role: "admin" | "supervisor" | "staff" | "user";
twoFactorEnabled: boolean;
/** @enum {string} */
notificationPreference: "email" | "whatsapp" | "both";
homeCampusId: string | null;
/** Format: date-time */
createdAt: string;
};
token: string;
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
getMeRegistrations: {
parameters: {
query?: {
@@ -835,4 +1012,388 @@ export interface operations {
};
};
};
getCheckinQrCode: {
parameters: {
query?: {
/** @description Multi-day events: the session (default: today's) */
sessionId?: string;
};
header?: never;
path: {
/** @description The code in the ticket's QR */
qrCode: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @enum {string} */
outcome: "found" | "transferred";
/** @description For a transferred ticket: who has it now */
message: string | null;
ticket: {
id: string;
eventId: string;
eventTitle: string | null;
ticketName: string | null;
variant: string | null;
/** @description The attendee named on it, or the person who registered */
holder: string | null;
quantity: number;
/** @description Still to check in (this session, on multi-day events) */
remaining: number;
session: {
id: string;
label: string;
} | null;
/** @description Why no session is open for check-in now */
sessionError: string | null;
/** @description not_required, given, pending, declined or missing */
consentStatus: string;
} | null;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postCheckinQrCode: {
parameters: {
query?: never;
header?: never;
path: {
/** @description The code in the ticket's QR */
qrCode: string;
};
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description Refuse tickets for any other event */
eventId?: string;
/** @description Only tickets valid for this section */
sectionId?: string;
/** @description Multi-day events: the session (default: today's) */
sessionId?: string;
/** @description How many to check in (default: everyone left) */
people?: number;
overrideConsent?: boolean;
/** @description This scanner, so its own offline lock doesn't block it */
deviceId?: string;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @enum {string} */
outcome: "checked_in" | "already_used" | "consent_required" | "wrong_event" | "wrong_section" | "section_not_found" | "no_session" | "locked" | "transferred";
message: string;
ticket: {
id: string;
eventId: string;
eventTitle: string | null;
/** @description The ticket option, e.g. "Adult" */
ticketName: string | null;
/** @description People on this ticket */
quantity: number;
} | null;
/** @description People checked in by this request (0 unless checked_in) */
checkedIn: number;
/** @description Still to check in afterwards */
remaining: number | null;
session: {
id: string;
label: string;
} | null;
consentStatus: string | null;
/** @description consent_required: whether you may override */
canOverride: boolean;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not signed in (UNAUTHENTICATED) */
401: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not allowed for this role (FORBIDDEN) */
403: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
/** @description Not found (NOT_FOUND) */
404: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postAuthSignup: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
name: string;
/** Format: email */
email: string;
password: string;
phone?: string;
/**
* @description WhatsApp needs a valid South African number; otherwise email is used
* @enum {string}
*/
notificationPreference?: "email" | "whatsapp" | "both";
newsOptIn?: boolean;
/** @constant */
acceptTerms: true;
};
};
};
responses: {
/** @description OK */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
status: "signed_in";
/** @description Send as `Authorization: Bearer <token>` */
token: string;
user: {
id: string;
name: string;
email: string;
/** @enum {string} */
role: "admin" | "supervisor" | "staff" | "user";
};
/** @description Ask once whether they want News & announcements */
newsPromptPending: boolean;
/** @description A privacy notice they must accept: never accepted (first) or a newer version (updated) */
noticePromptPending: false | ("first" | "updated");
/** @description With rememberDevice: send it with the next login to skip the code on this device */
deviceToken?: string;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postAuthLogin: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
/** @description Email address or phone number */
identifier: string;
password: string;
/** @description From an earlier login with rememberDevice */
deviceToken?: string;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
status: "signed_in";
/** @description Send as `Authorization: Bearer <token>` */
token: string;
user: {
id: string;
name: string;
email: string;
/** @enum {string} */
role: "admin" | "supervisor" | "staff" | "user";
};
/** @description Ask once whether they want News & announcements */
newsPromptPending: boolean;
/** @description A privacy notice they must accept: never accepted (first) or a newer version (updated) */
noticePromptPending: false | ("first" | "updated");
/** @description With rememberDevice: send it with the next login to skip the code on this device */
deviceToken?: string;
} | {
/** @constant */
status: "code_required";
challengeId: string;
/** @enum {string} */
method: "email" | "whatsapp";
/** @description Where the code went, partly hidden */
destination: string | null;
/** @description true = this turns two-factor on (required for the role) */
enrolling: boolean;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
postAuthLoginCode: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
challengeId: string;
code: string;
/** @description Skip the code on this device next time (30 days) */
rememberDevice?: boolean;
};
};
};
responses: {
/** @description OK */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
data: {
/** @constant */
status: "signed_in";
/** @description Send as `Authorization: Bearer <token>` */
token: string;
user: {
id: string;
name: string;
email: string;
/** @enum {string} */
role: "admin" | "supervisor" | "staff" | "user";
};
/** @description Ask once whether they want News & announcements */
newsPromptPending: boolean;
/** @description A privacy notice they must accept: never accepted (first) or a newer version (updated) */
noticePromptPending: false | ("first" | "updated");
/** @description With rememberDevice: send it with the next login to skip the code on this device */
deviceToken?: string;
};
};
};
};
/** @description Validation failed (VALIDATION_FAILED) */
400: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
};
};
}