-
Notifications
You must be signed in to change notification settings - Fork 939
/
Cookie.ts
91 lines (80 loc) · 2.35 KB
/
Cookie.ts
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import JSCookie, { CookieAttributes } from "js-cookie";
import { TechnicalError } from "./Errors";
/**
* Options for Cookie
*
* @category SDK
* @subcategory Internal
* @property {string} cookieName - The name of the session cookie set from the SDK.
* @property {string=} cookieDomain - The domain where the cookie set from the SDK is available. Defaults to the domain of the page where the cookie was created.
* @property {string=} cookieSameSite -Specify whether/when cookies are sent with cross-site requests. Defaults to "lax".
*/
interface CookieOptions {
cookieName: string;
cookieDomain?: string;
cookieSameSite?: CookieSameSite;
}
export type CookieSameSite =
| "strict"
| "Strict"
| "lax"
| "Lax"
| "none"
| "None";
/**
* A class to manage cookies.
*
* @category SDK
* @subcategory Internal
* @param {CookieOptions} options - The options that can be used
*/
export class Cookie {
authCookieName: string;
authCookieDomain?: string;
authCookieSameSite: CookieSameSite;
// eslint-disable-next-line require-jsdoc
constructor(options: CookieOptions) {
this.authCookieName = options.cookieName;
this.authCookieDomain = options.cookieDomain;
this.authCookieSameSite = options.cookieSameSite ?? "lax";
}
/**
* Returns the authentication token that was stored in the cookie.
*
* @return {string}
*/
getAuthCookie(): string {
return JSCookie.get(this.authCookieName);
}
/**
* Stores the authentication token to the cookie.
*
* @param {string} token - The authentication token to be stored.
* @param {CookieAttributes} options - Options for setting the auth cookie.
*/
setAuthCookie(token: string, options?: CookieAttributes) {
const defaults: CookieAttributes = {
secure: true,
sameSite: this.authCookieSameSite,
};
if (this.authCookieDomain !== undefined) {
defaults.domain = this.authCookieDomain;
}
const o: CookieAttributes = { ...defaults, ...options };
if (
(o.sameSite === "none" || o.sameSite === "None") &&
o.secure === false
) {
throw new TechnicalError(
new Error("Secure attribute must be set when SameSite=None"),
);
}
JSCookie.set(this.authCookieName, token, o);
}
/**
* Removes the cookie used for authentication.
*/
removeAuthCookie() {
JSCookie.remove(this.authCookieName);
}
}