/** * Who a request is signed in as. * * Resolved from the bearer token or the auth cookie the request carries, the * way the framework's own guards do, and outside any collection so the * lookup's queries are not blamed on the request being inspected. */ import type { DebugbarUser } from '@stacksjs/types' import { withoutCollection } from './context' interface Cached { user: DebugbarUser | null at: number } const cache = new Map() const CACHE_MS = 3000 export function describeUser(row: unknown): DebugbarUser | null { if (!row || typeof row !== 'object') return null const read = (key: string): unknown => { try { return (row as Record)[key] } catch { return undefined } } const id = read('id') if (typeof id !== 'number' && typeof id !== 'string') return null const text = (key: string): string | undefined => { const value = read(key) return typeof value === 'string' && value.trim() ? value.trim() : undefined } const email = text('email') const name = text('name') ?? ([text('first_name') ?? text('firstName'), text('last_name') ?? text('lastName')].filter(Boolean).join(' ') || undefined) ?? text('username') ?? email ?? `User #${id}` return { id, name, ...(email && { email }) } } export function requestToken(request: Request, cookieToken?: (request: Request) => string | undefined): { token: string, via: 'bearer' | 'cookie' } | undefined { const header = request.headers.get('authorization') if (header && /^bearer\s+\S/i.test(header)) return { token: header.replace(/^bearer\s+/i, '').trim(), via: 'bearer' } const fromCookie = cookieToken?.(request) return fromCookie ? { token: fromCookie, via: 'cookie' } : undefined } /** The user a request's token belongs to, or null for a guest or a dead token. */ export async function resolveRequestUser(request: Request): Promise<{ user: DebugbarUser | null, via: 'bearer' | 'cookie' | 'none' }> { try { const auth = await import('@stacksjs/auth') const found = requestToken(request, auth.authCookieToken) if (!found) return { user: null, via: 'none' } const hit = cache.get(found.token) if (hit && Date.now() - hit.at < CACHE_MS) return { user: hit.user, via: found.via } const row = await withoutCollection(() => auth.Auth.getUserFromToken(found.token)) const user = describeUser(row) if (cache.size > 100) cache.clear() cache.set(found.token, { user, at: Date.now() }) return { user, via: found.via } } catch { return { user: null, via: 'none' } } } /** Forget cached lookups, after a sign-in or a sign-out changes the answer. */ export function forgetResolvedUsers(): void { cache.clear() }