-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathlambda.js
More file actions
199 lines (185 loc) · 6.74 KB
/
lambda.js
File metadata and controls
199 lines (185 loc) · 6.74 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
const redis = require('redis')
const _ = require('lodash')
const request = require('request')
const md5 = require('md5')
const jwt = require('jsonwebtoken')
const joi = require('joi')
const ignoredClients = ['zYw8u52siLqHu7PmHODYndeIpD4vGe1R']
function validatePayload(event) {
if (_.isEmpty(event['body'])) {
return { error: getErrorResponse({ body: "Empty body." }) }
}
const auth0Payload = typeof event['body'] === 'string' ? JSON.parse(event['body']) : event['body']
const { value, error } = schema.validate(auth0Payload)
if (error != null) {
return { error: getErrorResponse({ statusCode: 400, body: "Payload validation error: " + JSON.stringify(error.details) }) }
}
return { auth0Payload: value }
}
const schema = joi.object().keys({
client_id: joi.string().required(),
grant_type: joi.string().required(),
client_secret: joi.string().required(),
audience: joi.string().optional(),
scope: joi.string().optional(),
auth0_url: joi.string().required(),
fresh_token: joi.boolean(),
provider: joi.string().default('auth0'),
content_type: joi.string().valid('application/json', 'application/x-www-form-urlencoded').default('application/json'),
expires_in: joi.number().min(1).optional()
}).oxor('audience', 'scope')
let redisClient = null
function acquireRedisClient() {
if (redisClient == null) {
console.log("Creating new redis client")
redisClient = createRedisClient()
} else {
const pong = redisClient.ping()
if (!pong) {
console.log("Redis connection lost, creating new redis client")
redisClient = createRedisClient()
}
}
}
function createRedisClient() {
const redisUrl = process.env.REDIS_URL || 'redis://localhost:6379'
const con = redis.createClient(redisUrl)
con.on("error", function (err) {
console.log(err)
})
return con
}
function getCacheKey(auth0Payload) {
const copyAuth0Payload = {
"client_id": auth0Payload.client_id,
"client_secret": auth0Payload.client_secret,
}
if (!_.isUndefined(auth0Payload.audience)) {
copyAuth0Payload.audience = auth0Payload.audience
} else if (!_.isUndefined(auth0Payload.scope)) {
copyAuth0Payload.scope = auth0Payload.scope
}
return `${auth0Payload.provider}-${auth0Payload.client_id}-${md5(JSON.stringify(copyAuth0Payload))}`
}
function callAuth0(auth0Payload, cacheKey, callback) {
const options = {
url: auth0Payload.auth0_url,
headers: { 'content-type': auth0Payload.content_type },
json: auth0Payload.content_type === 'application/json'
}
const data = {
grant_type: auth0Payload.grant_type,
client_id: auth0Payload.client_id,
client_secret: auth0Payload.client_secret
}
if (!_.isUndefined(auth0Payload.audience)) {
data.audience = auth0Payload.audience
} else if (!_.isUndefined(auth0Payload.scope)) {
data.scope = auth0Payload.scope
}
if (options.json) {
options.body = data
} else {
options.form = data
}
request.post(options, function (error, response, body) {
if (error) {
const errorResponse = getErrorResponse({ statusCode: response.statusCode, body: error })
console.log(errorResponse)
callback(null, errorResponse)
}
if (response.statusCode === 200) {
let token
if (_.isString(body)) {
token = JSON.parse(body).access_token
} else {
token = body.access_token
}
if (token) {
console.log(`Fetched from Auth0 for client-id: ${cacheKey}`)
const ttl = saveToRedisCache(cacheKey, token, auth0Payload.expires_in)
callback(null, getSuccessResponse({ body: JSON.stringify({ access_token: token, expires_in: ttl }) }))
} else {
const errorResponse = getErrorResponse({ statusCode: response.statusCode, body: _.isString(body) ? body : JSON.stringify(body) })
console.log(errorResponse)
callback(null, errorResponse)
}
} else {
const errorResponse = getErrorResponse({ statusCode: response.statusCode, body: _.isString(body) ? body : JSON.stringify(body) })
console.log(errorResponse)
callback(null, errorResponse)
}
})
}
function getFromRedisCache(auth0Payload, cacheKey, callback) {
redisClient.get(cacheKey, function (err, token) {
if (err) {
console.log(err)
callAuth0(auth0Payload, cacheKey, callback)
} else {
const ttl = getTokenExpiryTime(token)
if (ttl > 0) {
console.log(`Fetched from Redis Cache for cache key: ${cacheKey}`)
callback(null, getSuccessResponse({ body: JSON.stringify({ access_token: token, expires_in: ttl }) }))
} else {
console.log("Token expired in cache")
callAuth0(auth0Payload, cacheKey, callback)
}
}
})
}
function saveToRedisCache(cacheKey, token, defaultExpiry) {
const ttl = getTokenExpiryTime(token, defaultExpiry)
redisClient.set(cacheKey, token, 'EX', ttl)
return ttl
}
/**
*
* @param String token
* @returns expiryTime in seconds
*/
function getTokenExpiryTime(token, defaultExpiry = 1) {
if (!token) {
return 0
} else {
const decodedToken = jwt.decode(token)
if (decodedToken == null) {
return defaultExpiry
}
const expiryTimeInMilliSeconds = (decodedToken.exp - 60) * 1000 - (new Date().getTime())
return Math.floor(expiryTimeInMilliSeconds / 1000)
}
}
function getErrorResponse(error) {
const errorResponse = {
statusCode: 500,
body: 'something went wrong.'
}
return _.assign(errorResponse, error)
}
function getSuccessResponse(response) {
const successResponse = {
statusCode: 200,
body: "Bye!"
}
return _.assign(successResponse, response)
}
exports.handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false
const { error, auth0Payload } = validatePayload(event)
if (error) {
callback(null, error)
} else {
acquireRedisClient()
const cacheKey = getCacheKey(auth0Payload)
console.log(`Request for ${cacheKey}`)
const freshToken = JSON.parse(auth0Payload.fresh_token ? auth0Payload.fresh_token : 0)
&& !_.includes(ignoredClients, auth0Payload.client_id)
if (freshToken) {
console.log("Requested fresh token")
callAuth0(auth0Payload, cacheKey, callback)
} else {
getFromRedisCache(auth0Payload, cacheKey, callback)
}
}
}