dashboard/src/http/cookies.ts

42 lines
1.1 KiB
TypeScript

import { FastifyReply, FastifyRequest } from 'fastify';
export type SameSite = 'Strict' | 'Lax' | 'None';
export function set_cookie(res: FastifyReply, name: string, value: string, expires: Date, secure: boolean, same_site: SameSite = 'Strict', path?: string) {
const cookie
= `${name}=${value}; `
+ `Expires=${expires.toUTCString()}; `
+ (path ? ` Path=${path}; ` : '')
+ `HttpOnly; `
+ `SameSite=${same_site};`
+ (secure ? ' Secure;' : '')
;
res.header('set-cookie', cookie);
}
export function invalidate_cookie(res: FastifyReply, name: string, secure: boolean, path?: string) {
set_cookie(res, name, 'invalidate', new Date(0), secure, 'Strict', path);
}
export function parse_req_cookies(req: FastifyRequest) : Record<string, string> {
const result: Record<string, string> = { };
const cookies = req.headers.cookie || '';
for (const cookie of cookies.split(';')) {
const index = cookie.indexOf('=');
if (index < 0) {
continue;
}
const name = cookie.slice(0, index).trim();
const value = cookie.slice(index + 1).trim();
result[name] = decodeURIComponent(value);
}
return result;
}