forked from topcoder-platform/tc-lambda-auth0-proxy-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda.js
More file actions
107 lines (102 loc) · 3.91 KB
/
lambda.js
File metadata and controls
107 lines (102 loc) · 3.91 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
const redis = require('redis'),
_ = require('lodash'),
request = require('request'),
md5 = require('md5'),
jwt = require('jsonwebtoken')
/**
*
* @param String token
* @returns expiryTime in seconds
*/
function getTokenExipryTime(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
}
exports.handler = (event, context, callback) => {
let redisUrl = process.env.REDIS_URL || 'redis://localhost:6379'
let auth0Payload = {}
let cacheKey = ''
let options = {}
let redisClient = null
let errorResponse = {
statusCode: 500,
body: 'something went wrong.'
}
let successResponse = {
statusCode: 200,
body: "Bye!"
}
let freshToken = false
if (!_.isEmpty(event['body'])) {
auth0Payload = typeof event['body'] === 'string' ? JSON.parse(event['body']) : event['body']
// cache key is combination of : clientid-md5(client_secret)
cacheKey = auth0Payload.client_id || ''
cacheKey += `-${md5(auth0Payload.client_secret)}` || ' '
options = {
url: auth0Payload.auth0_url,
headers: { 'content-type': 'application/json' },
body: auth0Payload,
json: true
}
freshToken = JSON.parse(auth0Payload.fresh_token ? auth0Payload.fresh_token : 0)
} else {
errorResponse.body = "Empty body."
callback(null, errorResponse)
}
if (!_.isEmpty(redisUrl)) {
redisClient = redis.createClient(redisUrl)
redisClient.on("error", function (err) {
errorResponse.body = "redis client connecting error: " + err
callback(null, errorResponse)
redisClient.quit()
})
redisClient.on("ready", () => {
// try to get token from cache first
redisClient.get(cacheKey, function (err, token) {
// todo err implementation
if (token != null && !freshToken && getTokenExipryTime(token.toString()) > 0) {
console.log("Fetched from Redis Cache for cache key: ", cacheKey)
successResponse.body = JSON.stringify({
access_token: token.toString(),
expires_in: getTokenExipryTime(token.toString())
})
callback(null, successResponse)
redisClient.quit()
}
else {
request.post(options, function (error, response, body) {
if (error) {
errorResponse.body = error
callback(null, errorResponse)
}
if (body.access_token) {
let token = body.access_token
// Time to live in cache
let ttl = getTokenExipryTime(token)
redisClient.set(cacheKey, token, 'EX', ttl)
console.log("Fetched from Auth0 for cache key: ", cacheKey)
successResponse.body = JSON.stringify({
access_token: token.toString(),
expires_in: ttl
})
callback(null, successResponse)
}
else {
errorResponse.body = new Error('Unknown Error')
callback(null, errorResponse)
}
redisClient.quit()
})
}
})
})
} else {
errorResponse.body = "Empty redis url."
callback(null, errorResponse)
}
};