- Inscription, suivi de l'inscription (lien de confirmation), seconde étape de connexion (code à 6 chiffres ou code de secours), mot de passe oublié et réinitialisation, page « Mon compte » (mot de passe, 2FA avec QR code et codes de secours), d'après les maquettes Penpot. - Les jetons reçus par e-mail sont retirés de l'URL dès l'arrivée. - Favicon de la SSMG (ssmg.be) ; retour en haut de page à chaque navigation. - 93 tests Vitest ; README et CLAUDE.md mis à jour. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
93 lines
3.6 KiB
TypeScript
93 lines
3.6 KiB
TypeScript
/**
|
|
* Client HTTP de l'API Django (sessions + CSRF).
|
|
*
|
|
* Le cookie CSRF est déposé par GET /auth/me/ ; il est renvoyé dans l'en-tête X-CSRFToken
|
|
* pour toutes les requêtes qui modifient l'état.
|
|
*/
|
|
|
|
import type { Assessment, LoginResult, RegisterPayload, TotpSetup, User } from './types'
|
|
|
|
const BASE = '/api/v1'
|
|
|
|
export class ApiError extends Error {
|
|
readonly status: number
|
|
readonly body: Record<string, unknown>
|
|
|
|
constructor(status: number, body: Record<string, unknown>) {
|
|
super(typeof body.detail === 'string' ? body.detail : `HTTP ${status}`)
|
|
this.status = status
|
|
this.body = body
|
|
}
|
|
|
|
get code(): string | undefined {
|
|
return typeof this.body.code === 'string' ? this.body.code : undefined
|
|
}
|
|
|
|
/** Messages de validation par champ (réponse 400 de DRF). */
|
|
fieldErrors(): Record<string, string> {
|
|
const errors: Record<string, string> = {}
|
|
for (const [field, value] of Object.entries(this.body)) {
|
|
if (Array.isArray(value) && typeof value[0] === 'string') errors[field] = value.join(' ')
|
|
}
|
|
return errors
|
|
}
|
|
}
|
|
|
|
export function csrfToken(): string {
|
|
const match = document.cookie.match(/(?:^|;\s*)csrftoken=([^;]+)/)
|
|
return match?.[1] ? decodeURIComponent(match[1]) : ''
|
|
}
|
|
|
|
async function request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
const headers: Record<string, string> = { Accept: 'application/json' }
|
|
if (method !== 'GET') {
|
|
headers['X-CSRFToken'] = csrfToken()
|
|
}
|
|
if (body !== undefined) {
|
|
headers['Content-Type'] = 'application/json'
|
|
}
|
|
const response = await fetch(`${BASE}${path}`, {
|
|
method,
|
|
headers,
|
|
credentials: 'same-origin',
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
})
|
|
if (response.status === 204) {
|
|
return undefined as T
|
|
}
|
|
const data = await response.json().catch(() => ({}))
|
|
if (!response.ok) {
|
|
throw new ApiError(response.status, data)
|
|
}
|
|
return data as T
|
|
}
|
|
|
|
export const api = {
|
|
me: () => request<User>('GET', '/auth/me/'),
|
|
login: (email: string, password: string) =>
|
|
request<LoginResult>('POST', '/auth/login/', { email, password }),
|
|
verifyMfa: (code: string) => request<LoginResult>('POST', '/auth/2fa/verify/', { code }),
|
|
logout: () => request<void>('POST', '/auth/logout/'),
|
|
register: (payload: RegisterPayload) => request<void>('POST', '/auth/register/', payload),
|
|
verifyEmail: (token: string) =>
|
|
request<{ status: string }>('POST', '/auth/verify-email/', { token }),
|
|
resendVerification: (target: { email?: string; token?: string }) =>
|
|
request<void>('POST', '/auth/verify-email/resend/', target),
|
|
changePassword: (current_password: string, new_password: string) =>
|
|
request<void>('POST', '/auth/password/change/', { current_password, new_password }),
|
|
requestPasswordReset: (email: string) =>
|
|
request<void>('POST', '/auth/password-reset/', { email }),
|
|
validateResetToken: (token: string) =>
|
|
request<void>('POST', '/auth/password-reset/validate/', { token }),
|
|
resetPassword: (token: string, new_password: string) =>
|
|
request<void>('POST', '/auth/password-reset/confirm/', { token, new_password }),
|
|
setupTotp: () => request<TotpSetup>('POST', '/auth/2fa/setup/'),
|
|
enableTotp: (code: string) =>
|
|
request<{ recovery_codes: string[] }>('POST', '/auth/2fa/enable/', { code }),
|
|
disableTotp: (password: string, code: string) =>
|
|
request<void>('POST', '/auth/2fa/disable/', { password, code }),
|
|
regenerateRecoveryCodes: (code: string) =>
|
|
request<{ recovery_codes: string[] }>('POST', '/auth/2fa/recovery-codes/', { code }),
|
|
assess: (address: string) => request<Assessment>('POST', '/assessments/', { address }),
|
|
}
|