3743e7fe45
- Add auth management functions to api.ts (getAuthSettings, listUsers, etc.) - Refactor auth settings page to use centralized api.ts instead of raw fetch (FUNC-H2) - Add loading skeleton to auth settings page (UX-M16) - Add exchangeOidcToken() for httpOnly cookie OIDC flow (SEC-H3) - Fix Settings TypeScript type: has_npm_password boolean (FUNC-L) - Add last_alive_at to Instance type (FUNC-L)
46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
/** Shared auth helpers for token management. */
|
|
|
|
const TOKEN_KEY = 'auth_token';
|
|
|
|
/** Returns the stored JWT token, or null if not authenticated. */
|
|
export function getAuthToken(): string | null {
|
|
if (typeof localStorage !== 'undefined') {
|
|
return localStorage.getItem(TOKEN_KEY);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/** Returns true if the user has a stored auth token. */
|
|
export function isAuthenticated(): boolean {
|
|
return getAuthToken() !== null;
|
|
}
|
|
|
|
/** Stores the JWT token after successful login. */
|
|
export function setAuthToken(token: string): void {
|
|
if (typeof localStorage !== 'undefined') {
|
|
localStorage.setItem(TOKEN_KEY, token);
|
|
}
|
|
}
|
|
|
|
/** Removes the stored token and redirects to login. */
|
|
export function clearAuth(): void {
|
|
if (typeof localStorage !== 'undefined') {
|
|
localStorage.removeItem(TOKEN_KEY);
|
|
}
|
|
}
|
|
|
|
/** Exchanges the httpOnly OIDC cookie for a JWT token via the server endpoint. */
|
|
export async function exchangeOidcToken(): Promise<string | null> {
|
|
try {
|
|
const res = await fetch('/api/auth/oidc/token', { method: 'POST' });
|
|
if (!res.ok) return null;
|
|
const envelope = await res.json();
|
|
if (envelope.success && envelope.data?.token) {
|
|
return envelope.data.token;
|
|
}
|
|
return null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|