Files
lunch/lib/auth/session.ts
T
kai d1bf5196dd
release / which version (push) Successful in 1s
release / olares chart · sanity (push) Successful in 3s
release / app (push) Successful in 1m7s
release / tag and release (push) Successful in 2s
Own sign-in with passkeys, public entrance, market (26.11.2) (#3)
2026-11-06 19:32:34 +00:00

112 lines
3.8 KiB
TypeScript

import "server-only";
import type { PoolClient } from "pg";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { withAuth } from "@/lib/db";
import { LOCALE_COOKIE, isLocale } from "@/lib/locale";
import { hashToken, randomToken } from "./tokens";
// Sitzungen: ein Zufallsgeheimnis im Keks (HttpOnly), in der Datenbank nur
// sein Hash. 180 Tage, gleitend — eine Familien-App auf dem Handy soll nicht
// jede Woche nach dem Passkey fragen. Abmelden löscht die Zeile.
export const SESSION_COOKIE = "lunch_session";
const LIFETIME_DAYS = 180;
export type Session = {
sessionId: string;
memberId: string;
householdId: string;
displayName: string;
role: "owner" | "adult" | "child";
householdName: string;
};
/** Legt eine Sitzung an und setzt den Keks. Aufruf in einer withAuth-Transaktion. */
export async function startSession(
client: PoolClient,
member: { id: string; householdId: string; passkeyId: string },
request: Request,
secure: boolean,
): Promise<void> {
const { rows } = await client.query("select locale from members where id = $1", [member.id]);
const token = randomToken();
await client.query(
`insert into sessions (token_hash, member_id, household_id, passkey_id, user_agent, expires_at)
values ($1, $2, $3, $4, $5, now() + make_interval(days => $6))`,
[
hashToken(token),
member.id,
member.householdId,
member.passkeyId,
request.headers.get("user-agent")?.slice(0, 300) ?? null,
LIFETIME_DAYS,
],
);
(await cookies()).set(SESSION_COOKIE, token, {
httpOnly: true,
secure,
sameSite: "lax",
path: "/",
maxAge: LIFETIME_DAYS * 24 * 60 * 60,
});
// Die Sprache gehört der Person: Was sie gewählt hat, gilt auf jedem Gerät.
const locale = rows[0]?.locale;
if (isLocale(locale)) (await cookies()).set(LOCALE_COOKIE, locale, { path: "/", sameSite: "lax", maxAge: 365 * 24 * 60 * 60 });
}
/** Die Sitzung zum Keks, oder null. Verlängert sie höchstens einmal am Tag. */
export async function getSession(): Promise<Session | null> {
const token = (await cookies()).get(SESSION_COOKIE)?.value;
if (!token) return null;
return withAuth(async (client) => {
const { rows } = await client.query(
`select s.id, s.member_id, s.household_id, s.last_seen_at < now() - interval '1 day' as stale,
m.display_name, m.role, h.name as household_name
from sessions s
join members m on m.id = s.member_id
join households h on h.id = s.household_id
where s.token_hash = $1 and s.expires_at > now()`,
[hashToken(token)],
);
const row = rows[0];
if (!row) return null;
if (row.stale) {
await client.query(
"update sessions set last_seen_at = now(), expires_at = now() + make_interval(days => $2) where id = $1",
[row.id, LIFETIME_DAYS],
);
}
return {
sessionId: row.id,
memberId: row.member_id,
householdId: row.household_id,
displayName: row.display_name,
role: row.role,
householdName: row.household_name,
};
});
}
/** Für geschützte Seiten: ohne Sitzung zur Anmeldung. */
export async function requireSession(): Promise<Session> {
const session = await getSession();
if (!session) redirect("/anmelden");
return session;
}
export async function endSession(): Promise<void> {
const jar = await cookies();
const token = jar.get(SESSION_COOKIE)?.value;
if (token) await withAuth((client) => client.query("delete from sessions where token_hash = $1", [hashToken(token)]));
jar.delete(SESSION_COOKIE);
}
/** Gibt es schon einen Haushalt? Sonst führt jeder Weg zur Einrichtung. */
export async function isSetUp(): Promise<boolean> {
return withAuth(async (client) => {
const { rows } = await client.query("select exists (select 1 from instance) as done");
return Boolean(rows[0]?.done);
});
}