38 lines
1.2 KiB
TypeScript
38 lines
1.2 KiB
TypeScript
import type { FastifyReply } from 'fastify';
|
|
import { config } from '../config.js';
|
|
|
|
export const SESSION_COOKIE = 'compor_session';
|
|
export const ADMIN_SESSION_COOKIE = 'compor_admin_session';
|
|
|
|
const SESSION_MAX_AGE_SECONDS = (() => {
|
|
const match = /^(\d+)([smhd])$/.exec(config.JWT_SESSION_TTL);
|
|
if (!match) return 60 * 60 * 24 * 7;
|
|
const value = Number(match[1]);
|
|
const unit = match[2];
|
|
return unit === 's' ? value : unit === 'm' ? value * 60 : unit === 'h' ? value * 3600 : value * 86400;
|
|
})();
|
|
|
|
const cookieOptions = {
|
|
httpOnly: true,
|
|
secure: config.APP_ENV === 'production',
|
|
sameSite: 'lax' as const,
|
|
path: '/',
|
|
maxAge: SESSION_MAX_AGE_SECONDS,
|
|
};
|
|
|
|
export const setSessionCookie = (reply: FastifyReply, token: string) => {
|
|
reply.setCookie(SESSION_COOKIE, token, cookieOptions);
|
|
};
|
|
|
|
export const clearSessionCookie = (reply: FastifyReply) => {
|
|
reply.clearCookie(SESSION_COOKIE, { path: '/' });
|
|
};
|
|
|
|
export const setAdminSessionCookie = (reply: FastifyReply, token: string) => {
|
|
reply.setCookie(ADMIN_SESSION_COOKIE, token, cookieOptions);
|
|
};
|
|
|
|
export const clearAdminSessionCookie = (reply: FastifyReply) => {
|
|
reply.clearCookie(ADMIN_SESSION_COOKIE, { path: '/' });
|
|
};
|