56 lines
1.6 KiB
TypeScript
56 lines
1.6 KiB
TypeScript
import { createCookieSessionStorage, redirect, Session } from "react-router";
|
|
import { loadRequiredWebConfig, resolveSessionCookiePolicy } from "@toolctrl/config";
|
|
import { randomBytes } from "crypto";
|
|
|
|
export type AnalyticsSession = {
|
|
userAnalyticsId: string;
|
|
};
|
|
|
|
const webConfig = loadRequiredWebConfig();
|
|
|
|
const storage = createCookieSessionStorage({
|
|
cookie: {
|
|
...resolveSessionCookiePolicy({
|
|
nodeEnv: webConfig.nodeEnv,
|
|
routing: webConfig.routing,
|
|
name: "app_analytics",
|
|
maxAge: 60 * 60 * 24 * 30,
|
|
}),
|
|
secrets: webConfig.sessionSecret ? [webConfig.sessionSecret] : [],
|
|
},
|
|
});
|
|
|
|
export function getAnalyticsSession(request: Request) {
|
|
return storage.getSession(request.headers.get("Cookie"));
|
|
}
|
|
|
|
export async function getAnalyticsInfo(request: Request): Promise<AnalyticsSession> {
|
|
const session = await getAnalyticsSession(request);
|
|
const userAnalyticsId = session.get("userAnalyticsId") ?? null;
|
|
return {
|
|
userAnalyticsId,
|
|
};
|
|
}
|
|
|
|
export async function createAnalyticsSession(analyticsSession: AnalyticsSession, redirectTo = "/") {
|
|
const session = await storage.getSession();
|
|
session.set("userAnalyticsId", analyticsSession.userAnalyticsId);
|
|
return redirect(redirectTo, {
|
|
headers: {
|
|
"Set-Cookie": await storage.commitSession(session),
|
|
},
|
|
});
|
|
}
|
|
|
|
export async function commitAnalyticsSession(session: Session) {
|
|
return await storage.commitSession(session);
|
|
}
|
|
|
|
export async function destroyAnalyticsSession(session: Session) {
|
|
return await storage.destroySession(session);
|
|
}
|
|
|
|
export function generateAnalyticsUserId() {
|
|
return randomBytes(100).toString("base64");
|
|
}
|