Repository Public
1import { sql } from "./db";2import { sha256 } from "./crypto";34/** Session lookup without any Next.js import, so the native media server can use it too. */5export const SESSION_COOKIE = "spmusic_session";6export type Role = "admin" | "listener";7export interface UserContext { userId: string; email: string; displayName: string; role: Role; isOwner: boolean; locale: "fr" | "en"; accent: string; sessionId: string; csrfToken: string }89/** Session lookup from a raw cookie value. Used by Next (through cookies()) and by the native media server. */10export async function userFromToken(token: string | undefined | null): Promise<UserContext | null> {11 if (!token) return null;12 const [row] = await sql<{ id: string; user_id: string; csrf_token: string; email: string; display_name: string; role: Role; is_owner: boolean; locale: "fr" | "en"; accent: string; last_seen_at: Date }[]>`13 SELECT s.id, s.user_id, s.csrf_token, u.email, u.display_name, u.role, u.is_owner, u.locale, u.accent, s.last_seen_at14 FROM sessions s JOIN users u ON u.id = s.user_id15 WHERE s.token_hash = ${sha256(token)} AND s.revoked_at IS NULL AND s.expires_at > now() AND u.disabled_at IS NULL`;16 if (!row) return null;17 if (Date.now() - new Date(row.last_seen_at).getTime() > 60_000) await sql`UPDATE sessions SET last_seen_at = now() WHERE id = ${row.id}`;18 return { userId: row.user_id, email: row.email, displayName: row.display_name, role: row.role, isOwner: row.is_owner, locale: row.locale, accent: row.accent, sessionId: row.id, csrfToken: row.csrf_token };19}2021