Files
superbrain/web/lib/auth-guard.ts
T
2026-10-22 00:33:44 -05:00

34 lines
1.4 KiB
TypeScript

import { backendFetch } from '@/lib/api'
export const VIEW_AS_COOKIE = 'superbrain_view_as'
export type AuthUser = { id: string; name?: string | null; email?: string | null; image?: string | null; role: 'USER' | 'ADMIN'; actingAdminId?: string }
// Review M-6: Go distinguishes "no session" (401) from backend degradation
// (503). Collapsing both to null sent an authenticated admin to /login during
// a database outage, as if their credentials had failed. Only 401 means
// signed out; anything else is an outage the UI must show as such.
export class BackendUnavailableError extends Error {
status: number
constructor(status: number) {
super('Backend unavailable')
this.name = 'BackendUnavailableError'
this.status = status
}
}
async function account() {
let res: Response
try {
res = await backendFetch('/api/me')
} catch (error) {
const status = (error as { status?: unknown })?.status
throw new BackendUnavailableError(typeof status === 'number' ? status : 502)
}
if (res.status === 401) return null
if (!res.ok) throw new BackendUnavailableError(res.status)
return res.json()
}
export async function getRealUser(): Promise<AuthUser | null> { return (await account())?.user ?? null }
export async function getAuthUser(): Promise<AuthUser | null> { const me = await account(); return me ? { ...me.effectiveUser, ...(me.viewingAs ? { actingAdminId: me.user.id } : {}) } : null }