-
Notifications
You must be signed in to change notification settings - Fork 5
/
token.js
33 lines (29 loc) · 843 Bytes
/
token.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
const jwt = require('jsonwebtoken')
const User = require('./model')
const isValid = (token) => {
if (!token) {
return false
}
try {
const { exp } = jwt.decode(token)
return !(Date.now() >= exp*1000)
} catch (err) {
console.log(err)
return false
}
}
const getAnyValidToken = async () => {
const users = await User.find({ token: { $ne: null } })
const validTokens = users.filter(u => isValid(u.token))
try {
const { token } = validTokens[Math.floor(Math.random() * validTokens.length)]
return token
} catch (err) {
return null
}
}
const getExpirationTime = (token) => {
const { exp } = jwt.decode(token)
return Math.floor(Math.abs(Date.now() - (exp*1000))/1000)
}
module.exports = { isValid, getAnyValidToken, getExpirationTime }