backend/src/lib/auth/cookies.ts
creations ca0410f7fb
All checks were successful
Code quality checks / biome (push) Successful in 9s
add guild sql, move things around for req body
2025-06-18 17:45:30 -04:00

53 lines
1.4 KiB
TypeScript

import { environment } from "#environment/config";
import { jwt } from "#environment/jwt";
import type { CookieOptions } from "#types/config";
import type { ExtendedRequest } from "#types/server";
class CookieService {
extractToken(request: Request | ExtendedRequest): string | null {
return request.headers.get("Cookie")?.match(/session=([^;]+)/)?.[1] || null;
}
generateCookie(
token: string,
maxAge = jwt.expiration,
options?: CookieOptions,
): string {
const {
secure = !environment.development,
httpOnly = true,
sameSite = environment.development ? "Lax" : "None",
path = "/",
domain,
} = options || {};
let cookie = `session=${encodeURIComponent(token)}; Path=${path}; Max-Age=${maxAge}`;
if (httpOnly) cookie += "; HttpOnly";
if (secure) cookie += "; Secure";
if (sameSite) cookie += `; SameSite=${sameSite}`;
if (domain) cookie += `; Domain=${domain}`;
return cookie;
}
clearCookie(options?: Omit<CookieOptions, "httpOnly" | "secure">): string {
const {
sameSite = environment.development ? "Lax" : "None",
path = "/",
domain,
} = options || {};
let cookie = `session=; Path=${path}; Max-Age=0; HttpOnly`;
if (!environment.development) cookie += "; Secure";
if (sameSite) cookie += `; SameSite=${sameSite}`;
if (domain) cookie += `; Domain=${domain}`;
return cookie;
}
}
const cookieService = new CookieService();
export { CookieService, cookieService };