Files
compor-academy/server/src/auth/session-cookie.ts
Cauê Faleiros 50905eefd7
All checks were successful
CI / Validate frontend and API (push) Successful in 3m5s
CI / Build and publish Docker images (push) Successful in 1m42s
feat: add 2FA, secure cookies and publishing tools
2026-11-06 10:29:37 -03:00

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: '/' });
};