forked from mashery/iodocs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
1268 lines (1102 loc) · 47.3 KB
/
app.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2014 Mashery, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// 'Software'), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Module dependencies
//
var express = require('express'),
util = require('util'),
fs = require('fs'),
path = require('path'),
OAuth = require('oauth').OAuth,
OAuth2 = require('oauth/lib/oauth2').OAuth2,
query = require('querystring'),
url = require('url'),
http = require('http'),
https = require('https'),
crypto = require('crypto'),
clone = require('clone'),
redis = require('redis'),
RedisStore = require('connect-redis')(express),
server;
//
// Add minify to the JSON object
//
JSON.minify = JSON.minify || require("node-json-minify");
//
// Parse arguments
//
var yargs = require('yargs')
.usage('Usage: $0 --config-file [file]')
.alias('c', 'config-file')
.alias('h', 'help')
.describe('c', 'Specify the config file location')
.default('c', './config.json');
var argv = yargs.argv;
if (argv.help) {
yargs.showHelp();
process.exit(0);
}
//
// Configuration
//
var configFilePath = path.resolve(argv['config-file']);
try {
var config = JSON.parse(JSON.minify(fs.readFileSync(configFilePath, 'utf8')));
} catch(e) {
console.error("File " + configFilePath + " not found or is invalid. Try: `cp config.json.sample config.json`");
process.exit(1);
}
//
// Redis connection
//
var defaultDB = '0';
if(config.redis) {
config.redis.database = config.redis.database || defaultDB;
if (process.env.REDISTOGO_URL || process.env.REDIS_URL) {
var rtg = require("url").parse(process.env.REDISTOGO_URL || process.env.REDIS_URL);
config.redis.host = rtg.hostname;
config.redis.port = rtg.port;
config.redis.password = rtg.auth && rtg.auth.split(":")[1] ? rtg.auth.split(":")[1] : '';
}
var db = redis.createClient(config.redis.port, config.redis.host);
db.auth(config.redis.password);
db.on("error", function(err) {
if (config.debug) {
console.log("Error " + err);
}
});
}
//
// Load API Configs
//
config.apiConfigDir = path.resolve(config.apiConfigDir || 'public/data');
if (!fs.existsSync(config.apiConfigDir)) {
console.error("Could not find API config directory: " + config.apiConfigDir);
process.exit(1);
}
try {
var apisConfig = JSON.parse(JSON.minify(fs.readFileSync(path.join(config.apiConfigDir, 'apiconfig.json'), 'utf8')));
if (config.debug) {
console.log(util.inspect(apisConfig));
}
} catch(e) {
console.error("File apiconfig.json not found or is invalid.");
process.exit(1);
}
var app = module.exports = express();
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
if(config.redis) {
app.use(express.session({
secret: config.sessionSecret,
store: new RedisStore({
'host': config.redis.host,
'port': config.redis.port,
'pass': config.redis.password,
'db' : config.redis.database,
'maxAge': 1209600000
})
}));
} else {
app.use(express.session({
secret: config.sessionSecret
}));
}
//
// Global basic authentication on server (applied if configured)
//
if (checkObjVal(config,'basicAuth').exists && checkObjVal(config, 'basicAuth', 'password').exists) {
app.use(express.basicAuth(function(user, pass, callback) {
var result = (user === config.basicAuth.username && pass === config.basicAuth.password);
callback(null /* error */, result);
}));
}
app.use(checkPathForAPI);
app.use(dynamicHelpers);
app.use(app.router);
app.use(express.static(__dirname + '/public'));
app.use('/data', express.static(config.apiConfigDir));
});
app.configure('development', function() {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
//
// Middleware
//
function oauth1(req, res, next) {
console.log('OAuth process started');
var apiName = req.body.apiName,
apiConfig = JSON.parse(JSON.minify(fs.readFileSync(path.join(config.apiConfigDir, apiName + '.json'), 'utf8')));
var oauth1_type = checkObjVal(apiConfig,"auth","oauth","type").value,
oauth1_request_url = checkObjVal(apiConfig,"auth","oauth","requestURL").value,
oauth1_access_url = checkObjVal(apiConfig,"auth","oauth","accessURL").value,
oauth1_version = checkObjVal(apiConfig,"auth","oauth","version").value,
oauth1_crypt = checkObjVal(apiConfig,"auth","oauth","crypt").value,
oauth1_signin_url = checkObjVal(apiConfig,"auth","oauth","signinURL").value;
if (oauth1_version == "1.0") {
var apiKey = req.body.apiKey || req.body.key,
apiSecret = req.body.apiSecret || req.body.secret,
refererURL = url.parse(req.headers.referer),
callbackURL = refererURL.protocol + '//' + refererURL.host + '/authSuccess/' + apiName,
oa = new OAuth(
oauth1_request_url,
oauth1_access_url,
apiKey,
apiSecret,
oauth1_version,
callbackURL,
oauth1_crypt
);
if (config.debug) {
console.log('OAuth type: ' + oauth1_type);
console.log('Method security: ' + req.body.oauth);
console.log('Session authed: ' + req.session[apiName]);
console.log('apiKey: ' + apiKey);
console.log('apiSecret: ' + apiSecret);
}
// Check if the API even uses OAuth, then if the method requires oauth, then if the session is not authed
if (oauth1_type == 'three-legged' && req.body.oauth == 'authrequired' && (!req.session[apiName] || !req.session[apiName].authed) ) {
if (config.debug) {
console.log('req.session: ' + util.inspect(req.session));
console.log('headers: ' + util.inspect(req.headers));
console.log(util.inspect(oa));
console.log('sessionID: ' + util.inspect(req.sessionID));
}
oa.getOAuthRequestToken(function(err, oauthToken, oauthTokenSecret, results) {
if (err) {
res.send("Error getting OAuth request token : " + util.inspect(err), 500);
} else {
// Unique key using the sessionID and API name to store tokens and secrets
var key = req.sessionID + ':' + apiName;
db.set(key + ':apiKey', apiKey, redis.print);
db.set(key + ':apiSecret', apiSecret, redis.print);
db.set(key + ':requestToken', oauthToken, redis.print);
db.set(key + ':requestTokenSecret', oauthTokenSecret, redis.print);
// Set expiration to same as session
db.expire(key + ':apiKey', 1209600000);
db.expire(key + ':apiSecret', 1209600000);
db.expire(key + ':requestToken', 1209600000);
db.expire(key + ':requestTokenSecret', 1209600000);
res.send({'signin': oauth1_signin_url + oauthToken });
}
});
} else if (oauth1_type == 'two-legged' && req.body.oauth == 'authrequired') {
// Two legged stuff... for now nothing.
next();
} else {
next();
}
} else {
next();
}
}
function oauth2(req, res, next){
console.log('OAuth2 process started');
var apiName = req.body.apiName,
apiConfig = JSON.parse(JSON.minify(fs.readFileSync(path.join(config.apiConfigDir, apiName + '.json'), 'utf8')));
var oauth2_base_uri = checkObjVal(apiConfig,"auth","oauth","base_uri").value,
oauth2_authorize_uri = checkObjVal(apiConfig,"auth","oauth","authorize_uri").value,
oauth2_access_token_uri = checkObjVal(apiConfig,"auth","oauth","access_token_uri").value,
oauth2_token_location = checkObjVal(apiConfig,"auth","oauth","token","location").value,
oauth2_version = checkObjVal(apiConfig,"auth","oauth","version").value,
oauth2_token_param = checkObjVal(apiConfig,"auth","oauth","token","param").value;
if (oauth2_version == "2.0") {
var apiKey = req.body.apiKey || req.body.key,
apiSecret = req.body.apiSecret || req.body.secret,
refererURL = url.parse(req.headers.referer),
callbackURL = refererURL.protocol + '//' + refererURL.host + '/oauth2Success/' + apiName,
key = req.sessionID + ':' + apiName,
oauth_type = checkObjVal(apiConfig,'auth','oauth','type').value || "authorization_code",
oa = new OAuth2(
apiKey,
apiSecret,
oauth2_base_uri,
oauth2_authorize_uri,
oauth2_access_token_uri
);
if (oauth2_token_param) {
oa.setAccessTokenName(oauth2_token_param);
}
if (config.debug) {
console.log('OAuth type: ' + oauth_type);
console.log('Method security: ' + req.body.oauth2);
console.log('Session authed: ' + req.session[apiName]);
console.log('apiKey: ' + apiKey);
console.log('apiSecret: ' + apiSecret);
}
var redirectUrl;
if (oauth_type == 'authorization_code') {
redirectUrl = oa.getAuthorizeUrl({redirect_uri : callbackURL, response_type : 'code'});
db.set(key + ':apiKey', apiKey, redis.print);
db.set(key + ':apiSecret', apiSecret, redis.print);
db.set(key + ':callbackURL', callbackURL, redis.print);
// Set expiration to same as session
db.expire(key + ':apiKey', 1209600000);
db.expire(key + ':apiSecret', 1209600000);
db.expire(key + ':callbackURL', 1209600000);
res.send({'signin': redirectUrl});
}
else if (oauth_type == 'implicit') {
oa._authorizeUrl = oa._accessTokenUrl;
redirectUrl = oa.getAuthorizeUrl({redirect_uri : callbackURL, response_type : 'token'});
db.set(key + ':apiKey', apiKey, redis.print);
db.set(key + ':apiSecret', apiSecret, redis.print);
db.set(key + ':callbackURL', callbackURL, redis.print);
// Set expiration to same as session
db.expire(key + ':apiKey', 1209600000);
db.expire(key + ':apiSecret', 1209600000);
db.expire(key + ':callbackURL', 1209600000);
res.send({'implicit': redirectUrl});
}
else if (oauth_type == 'client_credentials') {
var accessURL = oauth2_base_uri + oauth2_access_token_uri;
var basic_cred = apiKey + ':' + apiSecret;
var encoded_basic = new Buffer(basic_cred).toString('base64');
var http_method = (oauth2_token_location == "header" || oauth2_token_location == null) ? "POST" : "GET";
var header = {
'Content-Type': 'application/x-www-form-urlencoded'
};
if (oauth2_token_location == "header" || !oauth2_token_location) {
header[ 'Authorization' ] = 'Basic ' + encoded_basic;
}
var fillerpost = query.stringify({grant_type : "client_credentials", client_id : apiKey, client_secret : apiSecret});
db.set(key + ':apiKey', apiKey, redis.print);
db.set(key + ':apiSecret', apiSecret, redis.print);
db.set(key + ':callbackURL', callbackURL, redis.print);
// Set expiration to same as session
db.expire(key + ':apiKey', 1209600000);
db.expire(key + ':apiSecret', 1209600000);
db.expire(key + ':callbackURL', 1209600000);
//client_credentials w/Authorization header
oa._request(
http_method,
accessURL,
header,
fillerpost,
'',
function(error, data, response) {
if (error) {
res.send("Error getting OAuth access token : " + util.inspect(error), 500);
}
else {
var results;
try {
results = JSON.parse(data);
}
catch(e) {
results = query.parse(data)
}
var oauth2access_token = results["access_token"];
var oauth2refresh_token = results["refresh_token"];
if (config.debug) {
console.log('results: ' + util.inspect(results));
}
db.mset(
[
key + ':access_token', oauth2access_token,
key + ':refresh_token', oauth2refresh_token
],
function(err, results2) {
db.set(key + ':accessToken', oauth2access_token, redis.print);
db.set(key + ':refreshToken', oauth2refresh_token, redis.print);
db.expire(key + ':accessToken', 1209600000);
db.expire(key + ':refreshToken', 1209600000);
res.send({'refresh': callbackURL});
}
);
}
}
)
}
}
}
function oauth2Success(req, res, next) {
console.log('oauth2Success started');
var apiKey,
apiSecret,
apiName = req.params.api,
apiConfig = JSON.parse(JSON.minify(fs.readFileSync(path.join(config.apiConfigDir, apiName + '.json'), 'utf8'))),
key = req.sessionID + ':' + apiName,
basePath;
var oauth2_type = checkObjVal(apiConfig,'auth','oauth','type').value || "authorization_code",
oauth2_base_uri = checkObjVal(apiConfig,"auth","oauth","base_uri").value,
oauth2_authorize_uri = checkObjVal(apiConfig,"auth","oauth","authorize_uri").value,
oauth2_access_token_uri = checkObjVal(apiConfig,"auth","oauth","access_token_uri").value,
oauth2_token_param = checkObjVal(apiConfig,"auth","oauth","token","param").value;
if (config.debug) {
console.log('apiName: ' + apiName);
console.log('key: ' + key);
console.log(util.inspect(req.params));
}
db.mget(
[
key + ':apiKey',
key + ':apiSecret',
key + ':callbackURL',
key + ':accessToken',
key + ':refreshToken'
],
function(err, result) {
if (err) {
console.log(util.inspect(err));
}
apiKey = result[0],
apiSecret = result[1],
callbackURL = result[2];
if (result[3] && oauth2_type == 'client_credentials') {
req.session[apiName] = {};
req.session[apiName].authed = true;
if (config.debug) {
console.log('session[apiName].authed: ' + util.inspect(req.session));
}
next();
}
if (config.debug) {
console.log(util.inspect(">>"+req.query.oauth_verifier));
}
var oa = new OAuth2(
apiKey,
apiSecret,
oauth2_base_uri,
oauth2_authorize_uri,
oauth2_access_token_uri
);
if (oauth2_token_param) {
oa.setAccessTokenName(oauth2_token_param);
}
if (config.debug) {
console.log(util.inspect(oa));
}
if (oauth2_type == 'authorization_code') {
console.log("in oauth2Success in authorization_code");
oa.getOAuthAccessToken(
req.query.code,
{
grant_type : "authorization_code",
redirect_uri : callbackURL,
client_id : apiKey,
client_secret : apiSecret
},
function(error, oauth2access_token, oauth2refresh_token, results) {
if (error) {
res.send("Error getting OAuth access token : " + util.inspect(error) + "["+oauth2access_token+"]"+ "["+oauth2refresh_token+"]", 500);
} else {
if (config.debug) {
console.log('results: ' + util.inspect(results));
}
db.mset(
[
key + ':access_token', oauth2access_token,
key + ':refresh_token', oauth2refresh_token
],
function(err, results2) {
req.session[apiName] = {};
req.session[apiName].authed = true;
if (config.debug) {
console.log('session[apiName].authed: ' + util.inspect(req.session));
}
next();
}
);
}
}
);
} else if (oauth2_type == 'implicit') {
next();
}
}
);
}
//
// OAuth Success!
//
function oauth1Success(req, res, next) {
console.log('oauthSuccess 1.0 started');
var oauthRequestToken,
oauthRequestTokenSecret,
apiKey,
apiSecret,
apiName = req.params.api,
apiConfig = JSON.parse(JSON.minify(fs.readFileSync(path.join(config.apiConfigDir, apiName + '.json'), 'utf8'))),
key = req.sessionID + ':' + apiName; // Unique key using the sessionID and API name to store tokens and secrets
var oauth1_request_url = checkObjVal(apiConfig,"auth","oauth","requestURL").value,
oauth1_access_url = checkObjVal(apiConfig,"auth","oauth","accessURL").value,
oauth1_version = checkObjVal(apiConfig,"auth","oauth","version").value,
oauth1_crypt = checkObjVal(apiConfig,"auth","oauth","crypt").value;
if (config.debug) {
console.log('apiName: ' + apiName);
console.log('key: ' + key);
console.log(util.inspect(req.params));
}
db.mget(
[
key + ':requestToken',
key + ':requestTokenSecret',
key + ':apiKey',
key + ':apiSecret'
],
function(err, result) {
if (err) {
console.log(util.inspect(err));
}
oauthRequestToken = result[0];
oauthRequestTokenSecret = result[1];
apiKey = result[2];
apiSecret = result[3];
if (config.debug) {
console.log(util.inspect(">>"+oauthRequestToken));
console.log(util.inspect(">>"+oauthRequestTokenSecret));
console.log(util.inspect(">>"+req.query.oauth_verifier));
}
var oa = new OAuth(
oauth1_request_url,
oauth1_access_url,
apiKey,
apiSecret,
oauth1_version,
null,
oauth1_crypt
);
if (config.debug) {
console.log(util.inspect(oa));
}
oa.getOAuthAccessToken(
oauthRequestToken,
oauthRequestTokenSecret,
req.query.oauth_verifier,
function (error, oauthAccessToken, oauthAccessTokenSecret, results) {
if (error) {
res.send("Error getting OAuth access token : " + util.inspect(error) + "[" + oauthAccessToken + "]" + "[" + oauthAccessTokenSecret + "]" + "[" + util.inspect(results) + "]", 500);
} else {
if (config.debug) {
console.log('results: ' + util.inspect(results));
}
db.mset(
[
key + ':accessToken', oauthAccessToken,
key + ':accessTokenSecret', oauthAccessTokenSecret
],
function (err, results2) {
req.session[apiName] = {};
req.session[apiName].authed = true;
if (config.debug) {
console.log('session[apiName].authed: ' + util.inspect(req.session));
}
next();
}
);
}
}
);
}
);
}
//
// processRequest - handles API call
//
function processRequest(req, res, next) {
console.log("in processRequest");
if (config.debug) {
console.log(util.inspect(req.body, null, 3));
}
var reqQuery = req.body,
customHeaders = {},
bodyParams = {},
params = {},
json = reqQuery.json || {},
locations = reqQuery.locations || {},
methodURL = reqQuery.methodUri,
httpMethod = reqQuery.httpMethod,
apiKey = reqQuery.apiKey,
apiSecret = reqQuery.apiSecret,
apiName = reqQuery.apiName,
apiConfig = JSON.parse(JSON.minify(fs.readFileSync(path.join(config.apiConfigDir, apiName + '.json'), 'utf8'))),
key = req.sessionID + ':' + apiName,
implicitAccessToken = reqQuery.accessToken;
json = JSON.parse(json);
locations = JSON.parse(locations);
console.log("json: ", json);
console.log("locations: ", locations);
for (var k in json) {
var v = json[k];
if (v !== '') {
// Set custom headers from the params
if (locations[k] == 'header' ) {
customHeaders[k] = v;
} else if (locations[k] == 'body') {
bodyParams[k] = v;
} else {
// URL params are contained within "{param}"
var regx = new RegExp('{' + k + '}');
// If the param is actually a part of the URL, put it in the URL
if (!!regx.test(methodURL)) {
methodURL = methodURL.replace(regx, v);
} else {
// Stores param in params to later put into the query
params[k] = v;
}
}
}
}
var baseHostInfo = apiConfig.basePath.split(':');
var baseHostUrl = baseHostInfo[1].split('//')[1],
baseHostPort = (baseHostInfo.length > 2) ? baseHostInfo[2] : "";
var headers = {};
for (var configHeader in apiConfig.headers) {
if (apiConfig.headers.hasOwnProperty(configHeader)) {
headers[configHeader] = apiConfig.headers[configHeader];
}
}
for (var customHeader in customHeaders) {
if (customHeaders.hasOwnProperty(customHeader)) {
headers[customHeader] = customHeaders[customHeader];
}
}
var paramString = query.stringify(params),
privateReqURL = (apiConfig.privatePath) ? apiConfig.basePath + apiConfig.privatePath + methodURL +
((paramString.length > 0) ? '?' + paramString : "") : apiConfig.basePath + methodURL + ((paramString.length > 0) ? '?' + paramString : ""),
options = {
headers: clone(headers),
host: baseHostUrl,
port: baseHostPort,
method: httpMethod,
path: apiConfig.publicPath + methodURL
};
if (['POST','PUT'].indexOf(httpMethod) !== -1) {
var requestBody;
requestBody = (options.headers['Content-Type'] === 'application/json')
? JSON.stringify(bodyParams)
: query.stringify(bodyParams);
}
if (checkObjVal(apiConfig,"auth","oauth","version").value == "1.0") {
console.log('Using OAuth 1.0');
var oauth1_type = checkObjVal(apiConfig,"auth","oauth","type").value || "three-legged",
oauth1_request_url = checkObjVal(apiConfig,"auth","oauth","requestURL").value,
oauth1_access_url = checkObjVal(apiConfig,"auth","oauth","accessURL").value,
oauth1_version = checkObjVal(apiConfig,"auth","oauth","version").value,
oauth1_crypt = checkObjVal(apiConfig,"auth","oauth","crypt").value;
// Three legged OAuth
if (oauth1_type == 'three-legged' && (reqQuery.oauth == 'authrequired' || (req.session[apiName] && req.session[apiName].authed))) {
if (config.debug) {
console.log('Three Legged OAuth');
}
db.mget(
[
key + ':apiKey',
key + ':apiSecret',
key + ':accessToken',
key + ':accessTokenSecret'
],
function(err, results) {
var apiKey = (typeof reqQuery.apiKey == "undefined" || reqQuery.apiKey == "undefined")?results[0]:reqQuery.apiKey,
apiSecret = (typeof reqQuery.apiSecret == "undefined" || reqQuery.apiSecret == "undefined")?results[1]:reqQuery.apiSecret,
accessToken = results[2],
accessTokenSecret = results[3];
var oa = new OAuth(
oauth1_request_url,
oauth1_access_url,
apiKey || null,
apiSecret || null,
oauth1_version,
null,
oauth1_crypt
);
if (config.debug) {
console.log('Access token: ' + accessToken);
console.log('Access token secret: ' + accessTokenSecret);
console.log('key: ' + key);
}
oa.getProtectedResource(
privateReqURL,
httpMethod,
accessToken,
accessTokenSecret,
function (error, data, response) {
req.call = privateReqURL;
if (error) {
console.log('Got error: ' + util.inspect(error));
if (error.data == 'Server Error' || error.data == '') {
req.result = 'Server Error';
} else {
req.result = error.data;
}
res.statusCode = error.statusCode;
next();
} else {
req.resultHeaders = response.headers;
req.result = JSON.parse(data);
next();
}
}
);
}
);
} else if (oauth1_type == 'two-legged' && reqQuery.oauth == 'authrequired') { // Two-legged
if (config.debug) {
console.log('Two Legged OAuth');
}
var body,
oa = new OAuth(
null,
null,
apiKey || null,
apiSecret || null,
oauth1_version,
null,
oauth1_crypt
);
var resource = options.host + options.path,
cb = function(error, data, response) {
if (error) {
if (error.data == 'Server Error' || error.data == '') {
req.result = 'Server Error';
} else {
console.log(util.inspect(error));
body = error.data;
}
res.statusCode = error.statusCode;
} else {
var responseContentType = response.headers['content-type'];
if (/application\/javascript/.test(responseContentType)
|| /text\/javascript/.test(responseContentType)
|| /application\/json/.test(responseContentType)) {
body = JSON.parse(data);
}
}
// Set Headers and Call
if (options.headers) req.requestHeaders = options.headers;
if (requestBody) req.requestBody = requestBody;
if (response) {
req.resultHeaders = response.headers || 'None';
} else {
req.resultHeaders = req.resultHeaders || 'None';
}
req.call = url.parse(options.host + options.path);
req.call = url.format(req.call);
// Response body
req.result = body;
next();
};
switch (httpMethod) {
case 'GET':
console.log(resource);
oa.get(resource, '', '',cb);
break;
case 'PUT':
case 'POST':
oa.post(resource, '', '', JSON.stringify(obj), null, cb);
break;
case 'DELETE':
oa.delete(resource,'','',cb);
break;
}
} else {
// API uses OAuth, but this call doesn't require auth and the user isn't already authed, so just call it.
unsecuredCall();
}
} else if (checkObjVal(apiConfig,"auth","oauth","version").value == "2.0") {
console.log('Using OAuth 2.0');
var oauth2_base_uri = checkObjVal(apiConfig,"auth","oauth","base_uri").value,
oauth2_authorize_uri = checkObjVal(apiConfig,"auth","oauth","authorize_uri").value,
oauth2_access_token_uri = checkObjVal(apiConfig,"auth","oauth","access_token_uri").value,
oauth2_token_location = checkObjVal(apiConfig,"auth","oauth","token","location").value,
oauth2_token_param = checkObjVal(apiConfig,"auth","oauth","token","param").value;
if (implicitAccessToken) {
db.mset([key + ':access_token', implicitAccessToken
], function(err, results2) {
req.session[apiName] = {};
req.session[apiName].authed = true;
if (config.debug) {
console.log('session[apiName].authed: ' + util.inspect(req.session));
}
});
}
if (reqQuery.oauth == 'authrequired' || (req.session[apiName] && req.session[apiName].authed)) {
if (config.debug) {
console.log('Session authed');
}
db.mget([key + ':apiKey',
key + ':apiSecret',
key + ':access_token',
key + ':refresh_token'
],
function(err, results) {
var apiKey = (typeof reqQuery.apiKey == "undefined" || reqQuery.apiKey == "undefined")?results[0]:reqQuery.apiKey,
apiSecret = (typeof reqQuery.apiSecret == "undefined" || reqQuery.apiSecret == "undefined")?results[1]:reqQuery.apiSecret,
access_token = (implicitAccessToken) ? implicitAccessToken : results[2],
refresh_token = results[3];
var oa = new OAuth2(
apiKey,
apiSecret,
oauth2_base_uri,
oauth2_authorize_uri,
oauth2_access_token_uri
);
if (oauth2_token_param) {
oa.setAccessTokenName(oauth2_token_param);
}
if (config.debug) {
console.log('Access token: ' + access_token);
console.log('Access token secret: ' + refresh_token);
console.log('key: ' + key);
}
if (oauth2_token_location == 'header' || !oauth2_token_location) {
options.headers["Authorization"] = "Bearer " + access_token;
}
console.log(httpMethod, privateReqURL, options.headers, requestBody, access_token);
oa._request(httpMethod, privateReqURL, options.headers, requestBody, access_token, function (error, data, response) {
req.call = privateReqURL;
if (options.headers) req.requestHeaders = options.headers;
if (requestBody) req.requestBody = requestBody;
if (error) {
console.log('Got error: ' + util.inspect(error));
if (error.data == 'Server Error' || error.data == '') {
req.result = 'Server Error';
} else {
req.result = error.data;
}
res.statusCode = error.statusCode;
next();
} else {
req.resultHeaders = response.headers;
// TODO: More robust content-type matching.
if (response.headers['content-type'] == 'application/json') {
try {
req.result = JSON.parse(data);
}
catch(err) {
req.result = data;
}
}
else {
req.result = data;
}
next();
}
});
}
);
} else {
// API uses OAuth, but this call doesn't require auth and the user isn't already authed, so just call it.
unsecuredCall();
}
} else {
// API does not use authentication
unsecuredCall();
}
//
// Unsecured API Call helper
//
function unsecuredCall() {
console.log('Unsecured Call');
options.path += ((paramString.length > 0) ? '?' + paramString : "");
// Add API Key to params, if any.
if (apiKey != '' && apiKey != 'undefined' && apiKey != undefined) {
if (apiConfig.auth.key.location === 'header') {
options.headers = (options.headers === void 0) ? {} : options.headers;
options.headers[apiConfig.auth.key.param] = apiKey;
}
else {
if (options.path.indexOf('?') !== -1) {
options.path += '&';
}
else {
options.path += '?';
}
console.log(apiConfig.auth.key.param);
options.path += apiConfig.auth.key.param + '=' + apiKey;
}
}
// Basic Auth support
if (apiConfig.auth == 'basicAuth') {
options.headers['Authorization'] = 'Basic ' + new Buffer(reqQuery.apiUsername + ':' + reqQuery.apiPassword).toString('base64');
console.log(options.headers['Authorization'] );
}
//
// Perform signature routine - force defaults on required configuration items.
//
if (checkObjVal(apiConfig,'auth','key','signature').exists) {
var timeStamp, sig;
var sig_param = checkObjVal(apiConfig,'auth','key','signature','param').value || 'sig';
var sig_type = checkObjVal(apiConfig,'auth','key','signature','type').value || 'signed_md5';
var sig_digest = checkObjVal(apiConfig,'auth','key','signature','digest').value || 'hex';
var sig_location = checkObjVal(apiConfig,'auth','key','signature','location').value || 'query';
if (sig_type == 'signed_md5') {
// Add signature parameter
timeStamp = Math.round(new Date().getTime()/1000);
sig = crypto.createHash('md5').update('' + apiKey + apiSecret + timeStamp + '').digest(sig_digest);
}
else if (sig_type == 'signed_sha256') {
// Add signature parameter
timeStamp = Math.round(new Date().getTime()/1000);
sig = crypto.createHash('sha256').update('' + apiKey + apiSecret + timeStamp + '').digest(sig_digest);
}
if (sig_location == 'query') {
options.path += '&' + sig_param + '=' + sig;
}
else if (sig_location == 'header') {
options.headers = (options.headers === void 0) ? {} : options.headers;
options.headers[sig_param] = sig;
}
}
if (options.headers === void 0){
options.headers = {}
}
if (['POST','PUT'].indexOf(httpMethod) !== -1 && !options.headers['Content-Length']) {
if (requestBody) {
options.headers['Content-Length'] = Buffer.byteLength(requestBody);