-
Notifications
You must be signed in to change notification settings - Fork 2
/
cookie-monster.ts
95 lines (87 loc) · 2.84 KB
/
cookie-monster.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
92
93
94
95
import fs from 'fs';
import { Cookie, MemoryCookieStore, Store } from 'tough-cookie';
import util from 'util';
const fs2 = {
exists: util.promisify(fs.exists),
readFile: util.promisify(fs.readFile),
writeFile: util.promisify(fs.writeFile),
open: util.promisify(fs.open)
};
export class CookieMonster {
constructor(
private store: Store
) {
}
showCookies(): Promise<Cookie[]> {
return new Promise((resolve, reject) => {
this.store.getAllCookies((err, cookies) => {
if (err) {
reject(err);
} else {
resolve(cookies);
}
});
});
}
eatCookies(domain: string, path: string): Promise<void> {
return new Promise((resolve, reject) => {
this.store.removeCookies(domain, path, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
buryCookies(cookies: Cookie[], fileName: string): Promise<void> {
let json = cookies.map(cookie => cookie.toJSON());
let text = JSON.stringify(json, null, 2);
return fs2.writeFile(fileName, text);
}
fetchCookies(fileName: string): Promise<void> {
return fs2.open(fileName, 'a+')
.then(fd => fs2.readFile(fd, { encoding: 'utf-8' }))
.then(text => JSON.parse(text || '[]'))
.then(json => Array.isArray(json)
? json.map(cookie => Cookie.fromJSON(cookie))
: [])
.then(cookies => cookies.map(cookie => {
return new Promise((resolve, reject) => {
if (!cookie) {
reject('cookie is empty');
return;
}
this.store.putCookie(cookie, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}))
.then(tasks => Promise.all(tasks))
.then(() => undefined);
}
isExpiring(cookie: Cookie) {
return cookie.TTL() < 300;
}
isAuthenticated(): Promise<boolean> {
return new Promise((resolve, reject) => {
this.store.findCookie('shift.gearboxsoftware.com', '/', 'si', (err, cookie) => {
if (err) {
reject(err);
} else if (cookie == null) {
resolve(false);
} else {
if (this.isExpiring(cookie)) {
resolve(false);
} else {
resolve(true);
}
}
});
});
}
}