mirror of
https://github.com/Sendouc/sendou.ink.git
synced 2026-03-21 18:04:39 -05:00
40 lines
1.2 KiB
TypeScript
40 lines
1.2 KiB
TypeScript
import { createCookieSessionStorage } from "@remix-run/node";
|
|
import { IS_E2E_TEST_RUN } from "~/utils/e2e";
|
|
import invariant from "~/utils/invariant";
|
|
import type { Theme } from "./provider";
|
|
import { isTheme } from "./provider";
|
|
|
|
const TEN_YEARS_IN_SECONDS = 315_360_000;
|
|
|
|
if (process.env.NODE_ENV === "production") {
|
|
invariant(process.env.SESSION_SECRET, "SESSION_SECRET is required");
|
|
}
|
|
const sessionSecret = process.env.SESSION_SECRET ?? "secret";
|
|
|
|
const themeStorage = createCookieSessionStorage({
|
|
cookie: {
|
|
name: "theme",
|
|
secure: process.env.NODE_ENV === "production" && !IS_E2E_TEST_RUN,
|
|
secrets: [sessionSecret],
|
|
sameSite: "lax",
|
|
path: "/",
|
|
httpOnly: true,
|
|
maxAge: TEN_YEARS_IN_SECONDS,
|
|
},
|
|
});
|
|
|
|
async function getThemeSession(request: Request) {
|
|
const session = await themeStorage.getSession(request.headers.get("Cookie"));
|
|
return {
|
|
getTheme: () => {
|
|
const themeValue = session.get("theme");
|
|
return isTheme(themeValue) ? themeValue : null;
|
|
},
|
|
setTheme: (theme: Theme) => session.set("theme", theme),
|
|
commit: () => themeStorage.commitSession(session),
|
|
destroy: () => themeStorage.destroySession(session, { maxAge: 0 }),
|
|
};
|
|
}
|
|
|
|
export { getThemeSession };
|