-
Notifications
You must be signed in to change notification settings - Fork 9
/
m2m.js
81 lines (71 loc) · 2.29 KB
/
m2m.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
'use strict'
var _ = require('lodash'),
request = require('request'),
jwt = require('jsonwebtoken')
const getTokenExpiryTime = function (token) {
let expiryTime = 0
if (token) {
let decodedToken = jwt.decode(token)
let expiryTimeInMilliSeconds = (decodedToken.exp - 60) * 1000 - (new Date().getTime())
expiryTime = Math.floor(expiryTimeInMilliSeconds / 1000)
}
return expiryTime
}
let cachedToken = {}
module.exports = function (config) {
let auth0Url = _.get(config, 'AUTH0_URL', '')
let auth0Audience = _.get(config, 'AUTH0_AUDIENCE', '')
let auth0ProxyServerUrl = _.get(config, 'AUTH0_PROXY_SERVER_URL', auth0Url)
return {
/**
* Generate machine to machine token from Auth0
* V3 API specification
* @param clientId client Id provided from Auth0
* @param clientSecret client secret provided from Auth0
* @return Promise promise to pass responses
*/
getMachineToken: (clientId, clientSecret) => {
var options = {
url: auth0ProxyServerUrl,
headers: { 'content-type': 'application/json' },
body: {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret,
audience: auth0Audience,
auth0_url: auth0Url
},
json: true
}
return new Promise(function (resolve, reject) {
// We cached the token to cachedToken variable,
// So we check the variable and the time here.
let appCachedToken = cachedToken[clientId]
let appCachedTokenExpired = false
//Check the token expiry
if (appCachedToken) {
if (getTokenExpiryTime(appCachedToken) <= 0) {
appCachedTokenExpired = true
}
}
if (!appCachedToken || appCachedTokenExpired ) {
request.post(options, function (error, response, body) {
if (error) {
return reject(new Error(error))
}
if (body.access_token) {
cachedToken[clientId] = body.access_token
resolve(cachedToken[clientId])
}
else {
reject(new Error('Unknown Error'))
}
})
}
else {
resolve(appCachedToken)
}
})
}
}
}