Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
FogNetwork
GitHub Repository: FogNetwork/Tsunami
Path: blob/main/lib/cookie.js
1036 views
1
// -------------------------------------------------------------
2
// WARNING: this file is used by both the client and the server.
3
// Do not use any browser or node-specific API!
4
// -------------------------------------------------------------
5
const { SetCookie, CookieStore } = require('./cookie-parser');
6
7
class CookieRewriter {
8
constructor(ctx) {
9
this.ctx = ctx;
10
};
11
decode(store, config = {}) {
12
const url = new URL(config.url);
13
const cookies = new CookieStore(store);
14
cookies.forEach((val, key) => {
15
if (!key.includes('@') || key.slice(key.length - url.hostname.length) != url.hostname) return cookies.delete(key);
16
cookies.delete(key);
17
cookies.set(key.substr(0, key.length - url.hostname.length - 1), val);
18
});
19
return cookies.serialize();
20
};
21
encode(input, config = {}) {
22
if (Array.isArray(input)) {
23
const rw = [ ...input ];
24
for (let i in rw) rw[i] = this.encode(rw[i], config);
25
return rw;
26
};
27
const url = new URL(config.url);
28
const cookie = new SetCookie(input);
29
if (!cookie.name) return null;
30
cookie.domain = config.domain;
31
cookie.secure = config.secure;
32
cookie.name += `@${url.hostname}`;
33
cookie.path = this.ctx.prefix;
34
return cookie.serialize() || '';
35
};
36
};
37
38
module.exports = CookieRewriter;
39
40