Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { cookies } from "next/headers.js";
- import { getSession } from "@server/auth/session-db";
- import { lucia } from "@/fd/fd-toolbox/auth/lucia";
- import jwt from "jsonwebtoken";
- import { envSettingKeys } from "@root/infra/env-settings";
- import { Cookie } from "lucia";
- import { setCoreCache } from "@server/fd/fd-toolbox/cachings/core-memory-cache";
- import { fdCacheKeys } from "@server/fd/fd-toolbox-web/constants/fd-cache-keys";
- import { getNowAsString, parseStringEndDate } from "@/fd/fd-toolbox/dates/date-times";
- import { WithIndexer } from "@server/fd/fd-toolbox/types/with-indexer";
- interface SessionValidationResult {
- userId: string;
- workspaceId: string | null;
- }
- interface SessionTokenPayload {
- sessionId: string;
- userId: string;
- passwordHash: string;
- workspaceId: string;
- expires: string;
- }
- const sessionConfig = {
- durationInDays: 30,
- secondsInDay: 24 * 60 * 60,
- cookieOptions: {
- httpOnly: true,
- secure: true,
- sameSite: "strict" as const,
- path: "/",
- },
- } as const;
- const sessionDurationSeconds = sessionConfig.durationInDays * sessionConfig.secondsInDay;
- const emptySessionValidationResult: SessionValidationResult = {
- userId: null!,
- workspaceId: null,
- };
- const sessionTokenRequiredProperties = [
- "sessionId",
- "userId",
- "passwordHash",
- "workspaceId",
- "expires",
- ] as const;
- export function getSessionToken() {
- const sessionCookie = cookies().get(lucia.sessionCookieName);
- return sessionCookie?.value;
- }
- export async function validateSessionToken(sessionToken: string) {
- const session = await getSession(sessionToken);
- if (!session) {
- await lucia.invalidateSession(sessionToken);
- return emptySessionValidationResult;
- }
- const result: SessionValidationResult = {
- userId: session.userId,
- workspaceId: session.workspaceId,
- };
- return result;
- }
- export function decodeSessionToken(token: string) {
- const decoded = jwt.verify(token, envSettingKeys.JwtKey);
- if (validateDecodedToken(decoded)) {
- return extractSessionData(decoded);
- }
- return null;
- }
- export async function createSession(userId: string, workspaceId: string, passwordHash: string | undefined) {
- const expiresDate = parseStringEndDate(getNowAsString(), sessionDurationSeconds);
- const session = await lucia.createSession(userId, { workspaceId });
- const sessionPayload = {
- sessionId: session.id,
- userId,
- passwordHash,
- workspaceId,
- expires: expiresDate,
- };
- const token = jwt.sign(sessionPayload, envSettingKeys.JwtKey, {
- expiresIn: `${sessionConfig.durationInDays}d`,
- });
- const sessionCookie = new Cookie(lucia.sessionCookieName, token, {
- ...sessionConfig.cookieOptions,
- expires: new Date(expiresDate),
- });
- cookies().set(sessionCookie.name, sessionCookie.value, sessionCookie.attributes);
- setCoreCache(session.id, session, {
- absoluteExpirationRelativeToNowSeconds: fdCacheKeys.secondsInFifteenMinutes,
- });
- return { sessionCookie, session };
- }
- function isObject(value: unknown): value is WithIndexer<unknown> {
- return typeof value === "object" && value !== null;
- }
- function validateDecodedToken(decoded: unknown): decoded is SessionTokenPayload {
- if (!isObject(decoded)) return false;
- return sessionTokenRequiredProperties.every(
- (prop) => prop in decoded && typeof decoded[prop] === "string",
- );
- }
- function extractSessionData(decoded: SessionTokenPayload) {
- return {
- sessionId: decoded.sessionId,
- userId: decoded.userId,
- passwordHash: decoded.passwordHash,
- workspaceId: decoded.workspaceId,
- expires: decoded.expires,
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement