peppa/apps/web/lib/session-user.ts

24 lines
1.0 KiB
TypeScript

// The signed-in user of a session cookie value (PEP-225): the same checks for pages
// (lib/auth.ts currentUser) and for the tab's WebSocket, which has no `next/headers`.
import { getUser, isUserAllowed, sessionsValidAfter, verify, type User } from "@peppa/core";
import { db } from "./db";
export const SESSION_COOKIE = "peppa_session";
export const SESSION_DAYS = 30;
export interface SessionPayload {
uid: number;
exp: number;
}
export async function userFromSessionToken(token: string | undefined): Promise<User | null> {
const p = verify<SessionPayload>(token);
if (!p || p.exp < Date.now()) return null;
// PEP-95: «выкинуть всех» — a session issued before the cut-off is no longer valid.
const after = await sessionsValidAfter(db);
if (after !== null && p.exp - SESSION_DAYS * 86400_000 < after) return null;
const user = await getUser(db, p.uid);
// Removed from the allowlist → the session stops working right away.
return user && (await isUserAllowed(db, user)) ? user : null;
}