forked from auth0/nextjs-auth0
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcookies.ts
More file actions
62 lines (53 loc) · 2.04 KB
/
cookies.ts
File metadata and controls
62 lines (53 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import type { IncomingMessage, ServerResponse } from 'http';
import { CookieSerializeOptions, parse, serialize } from 'cookie';
export abstract class Cookies {
protected cookies: string[];
constructor() {
this.cookies = [];
}
set(name: string, value: string, options: CookieSerializeOptions = {}): void {
const cookieString = serialize(name, value, options);
this.cookies.push(cookieString);
}
clear(name: string, options: CookieSerializeOptions = {}): void {
const { domain, path, secure, sameSite } = options;
const clearOptions: CookieSerializeOptions = {
domain,
path,
maxAge: 0
};
// If SameSite=None is set, the cookie Secure attribute must also be set (or the cookie will be blocked)
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite#none
if (sameSite === 'none') {
clearOptions.secure = secure;
clearOptions.sameSite = sameSite;
}
this.set(name, '', clearOptions);
}
commit(res: unknown, filterCookiePrefix?: string): void {
let previousCookies = this.getSetCookieHeader(res);
if (filterCookiePrefix) {
const re = new RegExp(`^${filterCookiePrefix}(\\.\\d+)?=`);
previousCookies = previousCookies.filter((cookie: string) => !re.test(cookie));
}
this.setSetCookieHeader(res, [...previousCookies, ...this.cookies]);
}
protected abstract getSetCookieHeader(res: unknown): string[];
protected abstract setSetCookieHeader(res: unknown, cookies: string[]): void;
abstract getAll(req: unknown): Record<string, string>;
}
export default class NodeCookies extends Cookies {
protected getSetCookieHeader(res: ServerResponse): string[] {
let cookies = res.getHeader('Set-Cookie') || [];
if (!Array.isArray(cookies)) {
cookies = [cookies as string];
}
return cookies;
}
protected setSetCookieHeader(res: ServerResponse, cookies: string[]): void {
res.setHeader('Set-Cookie', cookies);
}
getAll(req: IncomingMessage): Record<string, string> {
return parse(req.headers.cookie || '');
}
}