Files
Mangalord/frontend/src/lib/api/auth.ts
MechaCat02 e50fc093c3 feat: add PRIVATE_MODE site-wide auth gate (0.48.0)
When `PRIVATE_MODE=true`, every API path except a small allowlist
(`/health`, `/auth/{config,login,logout,register}`) requires a valid
session cookie or bearer token — anonymous reads are rejected with
401. Self-registration is force-disabled in private mode regardless
of `ALLOW_SELF_REGISTER`, so a locked-down instance flips with a
single switch (admins still mint accounts via `POST /admin/users`).

The backend gate is a tower middleware that reuses the existing
`CurrentUser` extractor, so the cookie + bearer paths cannot drift
from per-handler auth. `/auth/config` now exposes the flag plus the
effective `self_register_enabled` value so the frontend can render
the navbar correctly on the first paint.

On the frontend, a new universal root `+layout.ts` fetches the
config and redirects anonymous visitors to `/login?next=<path>`
before page-specific loads fire. The redirect is UX only — the
backend middleware is the source of truth, so crafted requests
still 401.

Defaults stay public (`PRIVATE_MODE=false`); existing deployments
need no env change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-01 20:11:22 +02:00

119 lines
3.5 KiB
TypeScript

import { ApiError, request } from './client';
export type User = {
id: string;
username: string;
created_at: string;
is_admin: boolean;
};
export type Credentials = {
username: string;
password: string;
};
type AuthResponse = { user: User };
export async function register(creds: Credentials): Promise<User> {
const r = await request<AuthResponse>('/v1/auth/register', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(creds)
});
return r.user;
}
export async function login(creds: Credentials): Promise<User> {
const r = await request<AuthResponse>('/v1/auth/login', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(creds)
});
return r.user;
}
export async function logout(): Promise<void> {
await request<void>('/v1/auth/logout', {
method: 'POST',
// Consistent with the other POST/PATCH helpers in this module.
// axum doesn't require it (no body), but keeping the header
// on every mutation request avoids the false-flag in logs and
// matches the project's style.
headers: { 'content-type': 'application/json' }
});
}
export type ChangePassword = {
current_password: string;
new_password: string;
};
/**
* Rotates the password. Backend signs out every other session for this
* user and mints a fresh cookie for the caller (returned as Set-Cookie,
* applied automatically by the browser). Bot tokens are left alone.
*
* Throws ApiError with `status=401, code='unauthenticated'` for wrong
* `current_password`; `status=400, code='invalid_input'` for a weak new
* password.
*/
export async function changePassword(input: ChangePassword): Promise<void> {
await request<void>('/v1/auth/me/password', {
method: 'PATCH',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(input)
});
}
/**
* Returns the current user, or `null` if no valid session.
* Re-throws any non-401 error.
*/
export async function me(): Promise<User | null> {
try {
const r = await request<AuthResponse>('/v1/auth/me');
return r.user;
} catch (e) {
if (e instanceof ApiError && e.status === 401) return null;
throw e;
}
}
export type ApiToken = {
id: string;
user_id: string;
name: string;
created_at: string;
last_used_at: string | null;
};
export type CreatedToken = ApiToken & { bearer: string };
export async function createToken(name: string): Promise<CreatedToken> {
return request<CreatedToken>('/v1/auth/tokens', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name })
});
}
export async function deleteToken(id: string): Promise<void> {
await request<void>(`/v1/auth/tokens/${encodeURIComponent(id)}`, { method: 'DELETE' });
}
export type AuthConfig = {
/** Effective value (`allow_self_register && !private_mode`).
* When false, /v1/auth/register returns 403 and the UI should
* hide its register affordance. Admins can still mint accounts
* via POST /v1/admin/users. */
self_register_enabled: boolean;
/** When true, every read endpoint requires auth and anonymous
* visitors are redirected to `/login` (see `+layout.ts`). */
private_mode: boolean;
};
/** Public — no auth, no cookie required. */
export async function getAuthConfig(): Promise<AuthConfig> {
return request<AuthConfig>('/v1/auth/config');
}