Repository navigation
Expand file tree
/
Copy pathTokenManager.ts
More file actions
93 lines (82 loc) · 2.52 KB
/
Copy pathTokenManager.ts
File metadata and controls
93 lines (82 loc) · 2.52 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
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
import { AesPkcs5 } from "encrypted-fetcher";
import { Pair } from "tstl/utility/Pair";
import { randint } from "tstl/algorithm/random";
import { v4 } from "uuid";
export namespace TokenManager
{
export function generate
(
table: string,
id: string,
writable: boolean,
duration: number
): string
{
// PAYLOAD DATA WITH CONFUSER
const payload: IPayload = {
[v4()]: v4(),
table,
id,
writable,
expired_at: Date.now() + duration,
[v4()]: randint(10000, 100000)
};
// RETURNS WITH ENCRYPTION
const iv: string = _Get_iv(table);
return AesPkcs5.encode(JSON.stringify(payload), ENCRYPT_KEY, iv);
}
export function refresh(table: string, token: string, writable: boolean, duration: number): string | null
{
// PARSE PAYLOAD
let iv: string = _Get_iv(table);
let payload: IPayload | null = _Parse(table, token, iv);
if (payload === null)
return null;
// RE-GENERATE TOKEN
return generate(table, payload.id, writable, duration);
}
export function parse(table: string, token: string): Pair<string, boolean> | null
{
const payload: IPayload | null = _Parse(table, token);
return (payload !== null)
? new Pair(payload.id, payload.writable)
: null;
}
/* -----------------------------------------------------------
HIDDEN MEMBERS
----------------------------------------------------------- */
function _Parse(table: string, token: string, iv: string = _Get_iv(table)): IPayload | null
{
// PARSE PAYLOAD
let payload: IPayload;
try
{
let content: string = AesPkcs5.decode(token, ENCRYPT_KEY, iv);
payload = JSON.parse(content);
}
catch
{
return null;
}
// JUDGEMENT
return (payload.table !== table || payload.expired_at < Date.now())
? null
: payload;
}
function _Get_iv(table: string): string
{
if (table.length > 16)
table = table.substr(0, 16);
else if (table.length < 16)
table = table + "_".repeat(16 - table.length);
return table;
}
const ENCRYPT_KEY = "12iDCMJDvwwCjYeJE6TSEDL8CQlJQcgN";
interface IPayload
{
table: string;
id: string;
writable: boolean;
expired_at: number;
}
}