Files
Mangalord/frontend/src/lib/api/auth.ts
MechaCat02 1ed1a134ea feat: bot API token management page
The account page pointed users at a "bot-token list" that didn't exist: there
was no GET endpoint, no UI route, and the client type lacked expiry. Add
GET /v1/auth/tokens (caller-scoped, token_hash never serialised), extend the
auth client with listTokens/expires_at and createToken expiry, and add a
/profile/tokens page to list, create (revealing the raw bearer once), and
revoke tokens. Link the account-page copy to it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-11 14:55:24 +02:00

140 lines
4.4 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)
},
// A 401 here means the *current* password was wrong, not that the
// session expired — don't let the global hook clear the user and
// bounce them to /login; the form surfaces the error inline.
{ suppressOn401: true }
);
}
/**
* 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;
/** When the token stops authenticating; `null` = never expires. */
expires_at: string | null;
};
export type CreatedToken = ApiToken & { bearer: string };
/** The caller's bot tokens, newest first (metadata only — the raw bearer is
* shown once at creation and never returned again). */
export async function listTokens(): Promise<ApiToken[]> {
const res = await request<{ items: ApiToken[] }>('/v1/auth/tokens');
return res.items;
}
export async function createToken(
name: string,
expiresInDays?: number
): Promise<CreatedToken> {
const payload: { name: string; expires_in_days?: number } = { name };
if (expiresInDays !== undefined) payload.expires_in_days = expiresInDays;
return request<CreatedToken>('/v1/auth/tokens', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload)
});
}
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');
}