-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtoken-service.mjs
40 lines (30 loc) · 1.01 KB
/
token-service.mjs
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
import jwt from 'jsonwebtoken'
export default function makeGetToken ({ readToken, httpClient, saveToken, clientId, clientSecret }) {
return async function getToken () {
const existingToken = await readToken()
if (existingToken) {
const { sub, exp } = jwt.decode(existingToken)
if (sub === clientId && stillValid(exp)) {
console.info('Reusing existing token ')
return existingToken
}
}
console.info('Fetching new token')
const newToken = await getTokenFromService()
await saveToken(newToken)
return newToken
}
async function getTokenFromService () {
return httpClient({
method: 'POST',
url: '/oauth/token',
data: 'grant_type=client_credentials',
auth: { username: clientId, password: clientSecret },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(({ data }) => data.access_token)
}
function stillValid (time) {
const now = new Date().getTime() / 1000
return time - now - 60 > 0
}
}