This commit is contained in:
commit
421043c9b5
67 changed files with 3455 additions and 0 deletions
52
src/lib/auth/cookies.ts
Normal file
52
src/lib/auth/cookies.ts
Normal file
|
@ -0,0 +1,52 @@
|
|||
import { environment } from "#environment/config";
|
||||
import { jwt } from "#environment/jwt";
|
||||
|
||||
import type { CookieOptions } from "#types/config";
|
||||
|
||||
class CookieService {
|
||||
extractToken(request: Request): 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 };
|
Loading…
Add table
Add a link
Reference in a new issue