/
tokenGenerators.js
90 lines (69 loc) · 2.34 KB
/
tokenGenerators.js
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
const jwt = require('jsonwebtoken')
const tokenTypes = {
MAIN: "main",
SESSION: "session"
}
let blacklistedTokens = []
let lastInvalidationDate = null
const getBlacklistedTokens = () => blacklistedTokens
const setBlacklistedTokens = tokens => {
if (Array.isArray(tokens))
blacklistedTokens = tokens
else
throw new Error("You must provide an array of tokens")
}
const getLastInvalidationDate = () => lastInvalidationDate
const setLastInvalidationDate = date => {
if (date instanceof Date)
lastInvalidationDate = date
else
throw new Error("You must provide a valid Date object")
}
const generateMainToken = (id, roles, customParams = {}, lastPasswordChange) => {
const { getSecret } = require("./middleware")
return jwt.sign({
id,
roles,
...customParams,
tokenType: tokenTypes.MAIN,
createdAt: new Date(),
lastPasswordChange
}, getSecret())
}
const generateSessionToken = (mainToken, customParams = {}, lastPasswordChange) => {
const { getSecret } = require("./middleware")
if (blacklistedTokens.includes(mainToken))
throw new Error("Cannot use this token to generate session tokens")
const decoded = jwt.verify(mainToken, getSecret())
if (decoded.tokenType !== tokenTypes.MAIN)
throw new Error("You must provide a main token to generate a session token")
if (lastInvalidationDate !== null) {
const mainCreatedAt = new Date(decoded.createdAt)
if (mainCreatedAt.getTime() <= lastInvalidationDate.getTime()) {
throw new Error("This main token is expired, you cannot use it")
}
}
if (lastPasswordChange) {
const date = new Date(lastPasswordChange)
const mainTokenLastPasswordChange = new Date(decoded.lastPasswordChange)
if (date.getTime() > mainTokenLastPasswordChange.getTime()) {
throw new Error("This main token is expired, you cannot use it")
}
}
return jwt.sign({
id: decoded.id,
roles: decoded.roles,
...customParams,
tokenType: tokenTypes.SESSION,
createdAt: new Date()
}, getSecret())
}
module.exports = {
generateMainToken,
generateSessionToken,
getBlacklistedTokens,
setBlacklistedTokens,
tokenTypes,
getLastInvalidationDate,
setLastInvalidationDate
}