owltide/server/utils/session.ts
Hornwitser fe06d0d6bd
All checks were successful
/ build (push) Successful in 2m5s
/ deploy (push) Successful in 16s
Refactor API types and sync logic
Rename and refactor the types passed over the API to be based on an
entity that's either living or a tombstone.  A living entity has a
deleted property that's either undefined or false, while a tombstone
has a deleted property set to true.  All entities have a numeric id
and an updatedAt timestamp.

To sync entities, an array of replacements are passed around. Living
entities are replaced with tombstones when they're deleted. And
tombstones are replaced with living entities when restored.
2025-06-11 21:05:17 +02:00

72 lines
2.3 KiB
TypeScript

import type { H3Event } from "h3";
import { nextSessionId, readSessions, readSubscriptions, type ServerSession, writeSessions, writeSubscriptions } from "~/server/database";
const oneYearSeconds = 365 * 24 * 60 * 60;
async function removeSessionSubscription(sessionId: number) {
const subscriptions = await readSubscriptions();
const index = subscriptions.findIndex(subscription => subscription.sessionId === sessionId);
if (index !== -1) {
subscriptions.splice(index, 1);
await writeSubscriptions(subscriptions);
}
}
async function clearServerSessionInternal(event: H3Event, sessions: ServerSession[]) {
const existingSessionCookie = await getSignedCookie(event, "session");
if (existingSessionCookie) {
const sessionId = parseInt(existingSessionCookie, 10);
const sessionIndex = sessions.findIndex(session => session.id === sessionId);
if (sessionIndex !== -1) {
sessions.splice(sessionIndex, 1);
await removeSessionSubscription(sessionId);
return true;
}
}
return false;
}
export async function clearServerSession(event: H3Event) {
const sessions = await readSessions();
if (await clearServerSessionInternal(event, sessions)) {
await writeSessions(sessions);
}
deleteCookie(event, "session");
}
export async function setServerSession(event: H3Event, accountId: number) {
const sessions = await readSessions();
await clearServerSessionInternal(event, sessions);
const newSession: ServerSession = {
accountId,
id: await nextSessionId(),
};
sessions.push(newSession);
await writeSessions(sessions);
await setSignedCookie(event, "session", String(newSession.id), oneYearSeconds)
}
export async function refreshServerSession(event: H3Event, session: ServerSession) {
await setSignedCookie(event, "session", String(session.id), oneYearSeconds)
}
export async function getServerSession(event: H3Event) {
const sessionCookie = await getSignedCookie(event, "session");
if (sessionCookie) {
const sessionId = parseInt(sessionCookie, 10);
const sessions = await readSessions();
return sessions.find(session => session.id === sessionId);
}
}
export async function requireServerSession(event: H3Event) {
const session = await getServerSession(event);
if (!session)
throw createError({
status: 401,
message: "Account session required",
});
return session;
}