This repository has been archived by the owner on Mar 2, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhandler.js
216 lines (190 loc) · 6.33 KB
/
handler.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
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
'use strict';
console.log('Loading function');
var Client = require('3scale').Client;
var createClient = require('then-redis').createClient
var Q = require('q');
var _ = require('underscore');
var AWS = require('aws-sdk');
AWS.config.region = process.env.AWS_REGION;
var client = new Client(process.env.THREESCALE_PROVIDER_KEY);
var service_id = process.env.THREESCALE_SERVICE_ID
var db = createClient({
host: process.env.ELASTICACHE_ENDPOINT,
port: process.env.ELASTICACHE_PORT
});
module.exports.authorizer = (event, context, callback) => {
var token = event.authorizationToken;
if(process.env.THREESCALE_AUTH_TYPE == "OAUTH"){
oauthAuthorizer(token,context,event)
}else{
userKeyAuthorizer(token,context,event)
}
};
module.exports.authRepAsync = (event, context, callback) => {
console.log('Received event:', JSON.stringify(event, null, 2));
var token = JSON.parse(event.Records[0].Sns.Message).token;
if(process.env.THREESCALE_AUTH_TYPE == "OAUTH"){
var app_id = JSON.parse(event.Records[0].Sns.Message).app_id
oauth_authorize(app_id).then(function(result){
console.log("reported",result)
}).catch(function(err){
console.log("ERROR:",err);
//delete ken from cache
db.del(token)
}).done(function(){
console.log("DONE")
context.done();
});
}else{
auth(token).then(function(result){
console.log("3scale response",result);
var metrics = _.pluck(result.usage_reports,'metric')
var cached_key = service_id+":"
_.each(metrics,function(m){
cached_key += "usage['"+m+"']=1&"
})
//store in cache
db.set(token,cached_key);
}).catch(function(err){
console.log("ERROR:",err);
//delete ken from cache
db.del(token)
}).done(function(){
console.log("DONE")
context.done();
});
}
}
//oAuth flow
function oauthAuthorizer(token, context, event){
db.get(token).then(function(value){
if (value != null) {
console.log('Token exists in cache, value is',value);
var sns = new AWS.SNS();
var message = {token: token, app_id: value}
sns.publish({
Message: JSON.stringify(message),
TopicArn: process.env.SNS_AUTHREP_ARN
}, function(err, data) {
if (err) {
console.log(err.stack);
return;
}
console.log('push sent',data);
context.succeed(generatePolicy('user', 'Allow', event.methodArn));
});
} else {
console.log('Token does not exist in cache');
console.log("ERROR:","Token not in cache, needs to call /oauth/token");
context.succeed(generatePolicy('user', 'Deny', event.methodArn));
}
})
}
//UserKey flow
function userKeyAuthorizer(token, context, event){
db.get(token).then(function(value){
if (value != null) {
console.log('Token exists in cache, value is',value);
//Send message on threescaleAsync SNS topic
//message contains token
var sns = new AWS.SNS();
var message = {token: token}
sns.publish({
Message: JSON.stringify(message),
TopicArn: process.env.SNS_AUTHREP_ARN
}, function(err, data) {
if (err) {
console.log(err.stack);
return;
}
console.log('push sent',data);
context.succeed(generatePolicy('user', 'Allow', event.methodArn));
});
} else {
console.log('Token does not exist in cache');
auth(token).then(function(result){
console.log("3scale response",result);
var metrics = _.pluck(result.usage_reports,'metric')
var cached_key = service_id+":"
_.each(metrics,function(m){
cached_key += "usage['"+m+"']=1&"
})
//sotre key and its usage in cache
db.set(token,cached_key);
context.succeed(generatePolicy('user', 'Allow', event.methodArn));
}).catch(function(err){
console.log("ERROR:",err);
context.succeed(generatePolicy('user', 'Deny', event.methodArn));
}).done(function(){
context.done();
})
}
})
}
//Function to authenticate against 3scale platform
function auth(token){
var options = { 'user_key': token, 'usage': { 'hits': 1 }, 'service_id': process.env.THREESCALE_SERVICE_ID};
var q = Q.defer();
client.authrep_with_user_key(options, function (res) {
if (res.is_success()) {
q.resolve(res);
} else {
q.reject(res);
}
});
return q.promise;
}
//Function to authenticate against 3scale platform
function oauth_authorize(app_id){
var options = { 'service_token': process.env.THREESCALE_SERVICE_TOKEN, 'app_id': app_id, 'service_id': process.env.THREESCALE_SERVICE_ID};
var q = Q.defer();
client.oauth_authorize(options, function (res) {
// console.log("oauth_authorize res", res)
if (res.is_success()) {
var trans = [{ service_token: process.env.THREESCALE_SERVICE_TOKEN, app_id: app_id, usage: {"hits": 1} }];
client.report(process.env.THREESCALE_SERVICE_ID, trans, function (response) {
console.log("RRR",response);
q.resolve(response);
});
} else {
q.reject(res);
}
});
return q.promise;
}
//Create a AWS Policy document that will be evaluate by the API Gateway
var generatePolicy = function(principalId, effect, resource) {
var authResponse = {};
authResponse.principalId = principalId;
if (effect && resource) {
var policyDocument = {};
policyDocument.Version = '2012-10-17'; // default version
policyDocument.Statement = [];
var statementOne = {};
statementOne.Action = 'execute-api:Invoke'; // default action
statementOne.Effect = effect;
statementOne.Resource = resource;
policyDocument.Statement[0] = statementOne;
authResponse.policyDocument = policyDocument;
}
return authResponse;
}
Array.prototype.find = function(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};