rallly/packages/backend/session.ts
Luke Vella c22b3abc4d
⬆️ v3.0.0 (#704)
2023-06-19 17:17:00 +01:00

46 lines
971 B
TypeScript

import { TimeFormat } from "@rallly/database";
import { sealData, unsealData } from "iron-session";
import { sessionConfig } from "./session-config";
type UserSessionData = {
id: string;
isGuest: boolean;
preferences?: {
timeZone?: string;
weekStart?: number;
timeFormat?: TimeFormat;
};
};
declare module "iron-session" {
export interface IronSessionData {
user?: UserSessionData;
}
}
export const decryptToken = async <P extends Record<string, unknown>>(
token: string,
): Promise<P | null> => {
const payload = await unsealData(token, {
password: sessionConfig.password,
});
if (Object.keys(payload).length === 0) {
return null;
}
return payload as P;
};
export const createToken = async <T extends Record<string, unknown>>(
payload: T,
options?: {
ttl?: number;
},
) => {
return await sealData(payload, {
password: sessionConfig.password,
ttl: options?.ttl ?? 60 * 15, // 15 minutes
});
};