- Login-Seite, Auth-Store und Router-Guard mit Weiterleitung nach dem Login - API-Client sendet X-CSRF-Token und reagiert auf 401 - Konto: Passwort ändern, angemeldete Geräte anzeigen und widerrufen - Benutzerverwaltung für Admins: anlegen, Rolle, aktiv, Passwort-Reset, löschen Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
67 lines
2.1 KiB
TypeScript
67 lines
2.1 KiB
TypeScript
export class ApiError extends Error {
|
|
constructor(
|
|
public readonly status: number,
|
|
message: string,
|
|
) {
|
|
super(message)
|
|
}
|
|
}
|
|
|
|
type UnauthorizedHandler = () => void
|
|
|
|
let onUnauthorized: UnauthorizedHandler | null = null
|
|
|
|
/** Called on 401 responses (except for the login request itself). */
|
|
export function setUnauthorizedHandler(handler: UnauthorizedHandler): void {
|
|
onUnauthorized = handler
|
|
}
|
|
|
|
function readCookie(name: string): string | null {
|
|
const match = document.cookie.split('; ').find((c) => c.startsWith(`${name}=`))
|
|
return match ? decodeURIComponent(match.slice(name.length + 1)) : null
|
|
}
|
|
|
|
async function errorMessage(response: Response): Promise<string> {
|
|
try {
|
|
const data: unknown = await response.json()
|
|
if (data && typeof data === 'object' && 'detail' in data) {
|
|
const detail = (data as { detail: unknown }).detail
|
|
if (typeof detail === 'string') return detail
|
|
if (Array.isArray(detail)) return 'Ungültige Eingabe.'
|
|
}
|
|
} catch {
|
|
// body is not JSON
|
|
}
|
|
return `${response.status} ${response.statusText}`
|
|
}
|
|
|
|
export async function apiRequest<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
const headers: Record<string, string> = { Accept: 'application/json' }
|
|
if (body !== undefined) headers['Content-Type'] = 'application/json'
|
|
if (method !== 'GET') {
|
|
const csrf = readCookie('lc_csrf')
|
|
if (csrf) headers['X-CSRF-Token'] = csrf
|
|
}
|
|
|
|
const response = await fetch(`/api${path}`, {
|
|
method,
|
|
headers,
|
|
credentials: 'same-origin',
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
})
|
|
|
|
if (!response.ok) {
|
|
if (response.status === 401 && path !== '/auth/login') onUnauthorized?.()
|
|
throw new ApiError(response.status, await errorMessage(response))
|
|
}
|
|
if (response.status === 204) return undefined as T
|
|
return (await response.json()) as T
|
|
}
|
|
|
|
export const api = {
|
|
get: <T>(path: string) => apiRequest<T>('GET', path),
|
|
post: <T>(path: string, body?: unknown) => apiRequest<T>('POST', path, body),
|
|
patch: <T>(path: string, body?: unknown) => apiRequest<T>('PATCH', path, body),
|
|
delete: <T>(path: string) => apiRequest<T>('DELETE', path),
|
|
}
|