This repository has been archived by the owner on Mar 4, 2024. It is now read-only.
forked from dgcgh/iodocs
-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
executable file
·1028 lines (902 loc) · 36.7 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) 2011 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'),
OAuth = require('oauth').OAuth,
query = require('querystring'),
url = require('url'),
http = require('http'),
https = require('https'),
crypto = require('crypto'),
redis = require('redis'),
pathy = require('path'),
RedisStore = require('connect-redis')(express);
// Configuration
try {
var config = require('./config.json');
} catch(e) {
console.error("File config.json not found or is invalid. Try: `cp config.json.sample config.json`");
process.exit(1);
}
//
// Redis connection
//
var defaultDB = '0';
var db;
if (process.env.REDISTOGO_URL) {
var rtg = require("url").parse(process.env.REDISTOGO_URL);
db = require("redis").createClient(rtg.port, rtg.hostname);
db.auth(rtg.auth.split(":")[1]);
} else {
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
//
try {
var apisConfig = require('./public/data/apiconfig.json');
if (config.debug) {
console.log(util.inspect(apisConfig));
}
} catch(e) {
console.error("File apiconfig.json not found or is invalid.");
process.exit(1);
}
//
// Determine if we should launch as http/s and get keys and certs if needed
//
var app, httpsKey, httpsCert;
if (config.https && config.https.on && config.https.keyPath && config.https.certPath) {
console.log("Starting secure server (https)");
// try reading the key and cert files, die if that fails
try {
httpsKey = fs.readFileSync(config.https.keyPath);
}
catch (err) {
console.error("Failed to read https key", config.https.keyPath);
console.log(err);
process.exit(1);
}
try {
httpsCert = fs.readFileSync(config.https.certPath);
}
catch (err) {
console.error("Failed to read https cert", config.https.certPath);
console.log(err);
process.exit(1);
}
app = module.exports = express.createServer({
key: httpsKey,
cert: httpsCert
});
}
else if (config.https && config.https.on) {
console.error("No key or certificate specified.");
process.exit(1);
}
else {
app = module.exports = express.createServer();
}
if (process.env.REDISTOGO_URL) {
var rtg = require("url").parse(process.env.REDISTOGO_URL);
config.redis.host = rtg.hostname;
config.redis.port = rtg.port;
config.redis.password = rtg.auth.split(":")[1];
}
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());
app.use(express.session({
secret: config.sessionSecret,
store: new RedisStore({
'host': config.redis.host,
'port': config.redis.port,
'pass': config.redis.password,
'maxAge': 1209600000
})
}));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function() {
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function() {
app.use(express.errorHandler());
});
//
// Middleware
//
function oauth(req, res, next) {
console.log('OAuth process started');
var apiName = req.body.apiName,
apiConfig = apisConfig[apiName];
if (apiConfig.oauth) {
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(apiConfig.oauth.requestURL,
apiConfig.oauth.accessURL,
apiKey,
apiSecret,
apiConfig.oauth.version,
callbackURL,
apiConfig.oauth.crypt);
if (config.debug) {
console.log('OAuth type: ' + apiConfig.oauth.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 (apiConfig.oauth.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(util.inspect(req));
console.log('sessionID: ' + util.inspect(req.sessionID));
// console.log(util.inspect(req.sessionStore));
};
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.header('Content-Type', 'application/json');
res.send({ 'signin': apiConfig.oauth.signinURL + oauthToken });
}
});
} else if (apiConfig.oauth.type == 'two-legged' && req.body.oauth == 'authrequired') {
// Two legged stuff... for now nothing.
next();
} else {
next();
}
} else {
next();
}
}
//
// OAuth Success!
//
function oauthSuccess(req, res, next) {
var oauthRequestToken,
oauthRequestTokenSecret,
apiKey,
apiSecret,
apiName = req.params.api,
apiConfig = apisConfig[apiName],
key = req.sessionID + ':' + apiName; // Unique key using the sessionID and API name to store tokens and secrets
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(apiConfig.oauth.requestURL,
apiConfig.oauth.accessURL,
apiKey,
apiSecret,
apiConfig.oauth.version,
null,
apiConfig.oauth.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) {
if (config.debug) {
console.log(util.inspect(req.body, null, 3));
};
var reqQuery = req.body,
customHeaders = {},
params = reqQuery.params || {},
content = reqQuery.requestContent || '',
contentType = reqQuery.contentType || '',
locations = reqQuery.locations || {},
methodURL = reqQuery.methodUri,
httpMethod = reqQuery.httpMethod,
apiKey = reqQuery.apiKey,
apiSecret = reqQuery.apiSecret,
apiName = reqQuery.apiName,
apiConfig = apisConfig[apiName],
key = req.sessionID + ':' + apiName;
// Extract custom headers from the params
for( var param in params )
{
if (params.hasOwnProperty(param))
{
if (params[param] !== '' && locations[param] == 'header' )
{
customHeaders[param] = params[param];
delete params[param];
}
}
}
// Replace placeholders in the methodURL with matching params
for (var param in params) {
if (params.hasOwnProperty(param)) {
if (params[param] !== '') {
// URL params are prepended with ":"
var regx = new RegExp(':' + param);
// If the param is actually a part of the URL, put it in the URL and remove the param
if (!!regx.test(methodURL)) {
methodURL = methodURL.replace(regx, params[param]);
delete params[param]
}
} else {
delete params[param]; // Delete blank params
}
}
}
var baseHostInfo = apiConfig.baseURL.split(':');
var baseHostUrl = baseHostInfo[0],
baseHostPort = (baseHostInfo.length > 1) ? baseHostInfo[1] : "";
var headers = {};
for( header in apiConfig.headers )
headers[header] = apiConfig.headers[header];
for( header in customHeaders )
headers[header] = customHeaders[header];
var paramString = query.stringify(params),
privateReqURL = apiConfig.protocol + '://' + apiConfig.baseURL + apiConfig.privatePath + methodURL + ((paramString.length > 0) ? '?' + paramString : ""),
options = {
headers: headers,
protocol: apiConfig.protocol + ':',
host: baseHostUrl,
port: baseHostPort,
method: httpMethod,
path: apiConfig.publicPath + methodURL + ((paramString.length > 0) ? '?' + paramString : ""),
rejectUnauthorized: false
};
if (apiConfig.oauth) {
console.log('Using OAuth');
// Three legged OAuth
if (apiConfig.oauth.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];
console.log(apiKey);
console.log(apiSecret);
console.log(accessToken);
console.log(accessTokenSecret);
var oa = new OAuth(apiConfig.oauth.requestURL || null,
apiConfig.oauth.accessURL || null,
apiKey || null,
apiSecret || null,
apiConfig.oauth.version || null,
null,
apiConfig.oauth.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;
// console.log(util.inspect(response));
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 (apiConfig.oauth.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,
apiConfig.oauth.version || null,
null,
apiConfig.oauth.crypt);
var resource = options.protocol + '://' + 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 {
console.log(util.inspect(data));
var responseContentType = response.headers['content-type'];
switch (true) {
case /application\/javascript/.test(responseContentType):
case /text\/javascript/.test(responseContentType):
case /application\/json/.test(responseContentType):
body = JSON.parse(data);
break;
case /application\/xml/.test(responseContentType):
case /text\/xml/.test(responseContentType):
default:
}
}
// Set Headers and Call
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;
req.statusCode = response.statusCode;
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 {
// API does not use authentication
unsecuredCall();
}
// Unsecured API Call helper
function unsecuredCall() {
console.log('Unsecured Call');
// Add API Key to params, if any.
if (apiKey != '' && apiKey != 'undefined' && apiKey != undefined) {
if (options.path.indexOf('?') !== -1) {
options.path += '&';
}
else {
options.path += '?';
}
options.path += apiConfig.keyParam + '=' + apiKey;
}
// Perform signature routine, if any.
if (apiConfig.signature) {
if (apiConfig.signature.type == 'signed_md5') {
// Add signature parameter
var timeStamp = Math.round(new Date().getTime()/1000);
var sig = crypto.createHash('md5').update('' + apiKey + apiSecret + timeStamp + '').digest(apiConfig.signature.digest);
options.path += '&' + apiConfig.signature.sigParam + '=' + sig;
}
else if (apiConfig.signature.type == 'signed_sha256') { // sha256(key+secret+epoch)
// Add signature parameter
var timeStamp = Math.round(new Date().getTime()/1000);
var sig = crypto.createHash('sha256').update('' + apiKey + apiSecret + timeStamp + '').digest(apiConfig.signature.digest);
options.path += '&' + apiConfig.signature.sigParam + '=' + sig;
}
}
// Setup headers, if any
if (reqQuery.headerNames && reqQuery.headerNames.length > 0) {
if (config.debug) {
console.log('Setting headers');
};
var headers = {};
for (var x = 0, len = reqQuery.headerNames.length; x < len; x++) {
if (config.debug) {
console.log('Setting header: ' + reqQuery.headerNames[x] + ':' + reqQuery.headerValues[x]);
};
if (reqQuery.headerNames[x] != '') {
headers[reqQuery.headerNames[x]] = reqQuery.headerValues[x];
}
}
options.headers = headers;
}
if(options.headers === void 0){
options.headers = {}
}
if (!options.headers['Content-Length']) {
if (content) {
options.headers['Content-Length'] = content.length;
}
else {
options.headers['Content-Length'] = 0;
}
}
if (!options.headers['Content-Type'] && content) {
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
}
if (config.debug) {
console.log(util.inspect(options));
};
var doRequest;
if (options.protocol === 'https' || options.protocol === 'https:') {
console.log('Protocol: HTTPS');
options.protocol = 'https:'
doRequest = https.request;
} else {
console.log('Protocol: HTTP');
doRequest = http.request;
}
if(contentType !== ''){
if (config.debug) {
console.log('Setting Content-Type: ' + contentType);
}
options.headers['Content-Type'] = contentType;
}
// API Call. response is the response from the API, res is the response we will send back to the user.
var apiCall = doRequest(options, function(response) {
response.setEncoding('utf-8');
if (config.debug) {
console.log('HEADERS: ' + JSON.stringify(response.headers));
console.log('STATUS CODE: ' + response.statusCode);
};
res.statusCode = response.statusCode;
var body = '';
response.on('data', function(data) {
body += data;
})
response.on('end', function() {
delete options.agent;
var responseContentType = response.headers['content-type'];
switch (true) {
case /application\/javascript/.test(responseContentType):
case /application\/json/.test(responseContentType):
console.log(util.inspect(body));
// body = JSON.parse(body);
break;
case /application\/xml/.test(responseContentType):
case /text\/xml/.test(responseContentType):
default:
}
// Set Headers and Call
req.resultHeaders = response.headers;
req.call = url.parse(options.host + options.path);
req.call = url.format(req.call);
req.statusCode = response.statusCode;
// Response body
req.result = body;
console.log(util.inspect(body));
next();
})
}).on('error', function(e) {
if (config.debug) {
console.log('HEADERS: ' + JSON.stringify(res.headers));
console.log("Got error: " + e.message);
console.log("Error: " + util.inspect(e));
};
});
if(content !== ''){
apiCall.write(content,'utf-8');
}
apiCall.end();
}
}
var cachedApiInfo = [];
// Dynamic Helpers
// Passes variables to the view
app.dynamicHelpers({
session: function(req, res) {
// If api wasn't passed in as a parameter, check the path to see if it's there
if (!req.params.api) {
pathName = req.url.replace('/','');
// Is it a valid API - if there's a config file we can assume so
fs.stat(__dirname + '/public/data/' + pathName + '.json', function (error, stats) {
if (stats) {
req.params.api = pathName;
}
});
}
// If the cookie says we're authed for this particular API, set the session to authed as well
if (req.params.api && req.session[req.params.api] && req.session[req.params.api]['authed']) {
req.session['authed'] = true;
}
return req.session;
},
apiInfo: function(req, res) {
if (req.params.api) {
return apisConfig[req.params.api];
} else {
return apisConfig;
}
},
apiName: function(req, res) {
if (req.params.api) {
return req.params.api;
}
},
apiDefinition: function(req, res) {
if (req.params.api) {
var data = getData(req.params.api);
processApiIncludes(data, req.params.api);
cachedApiInfo = data;
return data;
}
}
});
/*
Can be called in the following ways:
getData("klout");
getData("klout", "./klout/get-methods.json");
getData("klout", "/user/home/klout/klout.json");
getData("klout", "/user/home/random/nonsense.json");
*/
function getData(api, passedPath) {
var end = ".json";
var loc;
// Error checking
if ( /[A-Za-z_\-\d]+/.test(api)) {
//console.log('Valid input for API name.');
}
else {
console.log('API name provided contains invalid characters.');
}
/*
Check whether api-name given is in apiconfig.
Check whether api has 'href' property in config.
If so, check if 'href' property is of 'file' or 'htttp'.
If 'file', check that 'href' property contains a directory; print warning
if not a directory
Check if there was a second argument given (passedPath)
If passedPath, check whether it is a relative path (should start with './'
if it is).
Otherwise, check that the passedPath is of 'file' type and get the data
from it. Assuming a full path is being given.
If no passedPath, attempt to return the api-name.json file from the directory
given in the config file.
If no 'href' property in given config for given api name, but passedPath
exists with a relative directory, use default location and attempt to
return data.
If no 'href' property and no passedPath, attempt to get api-name.json from
default location (iodocs installation directory + '/public/data').
If given api name isn't found in the config file, print statement stating
as much.
*/
if (apisConfig.hasOwnProperty(api)) {
if (apisConfig[api].hasOwnProperty('href')) {
loc = url.parse(apisConfig[api]['href']);
if (loc.protocol.match(/^file:$/)) {
// Need a directory check on loc.path here
// Not sure if that should be sync or async.
if (undefined !== passedPath) {
if (/^.\//.test(passedPath)) {
return require(pathy.resolve(loc.path, passedPath));
}
else if (url.parse(passedPath).protocol
&& url.parse(passedPath).protocol.match(/^file:$/)) {
return require(passedPath);
}
}
else {
return require(pathy.join(loc.path + api + end));
}
}
}
else if (/^.\//.test(passedPath)) {
return require(pathy.resolve(__dirname + '/public/data/' , passedPath));
}
else {
return require(__dirname + '/public/data/' + api + '.json');
}
}
else {
console.log("'" + api + "' does not exist in config file.");
}
}
// This function was developed with the assumption that the starting input
// would be the main api file, which would look like the following:
// { "endpoints":
// [...]
// }
//
// The include statement syntax looks like this:
// {
// "external":
// {
// "href": "./public/data/desired/data.json",
// "type": "list"
// }
// }
// "type": "list" is used only when the contents of the file to be included is a list object
// that will be merged into an existing list.
// An example would be storing all the get methods for an endpoint as a list of objects in
// an external file.
function processApiIncludes (jsonData, apiName) {
// used to determine object types in a more readable manner
var what = Object.prototype.toString;
var includeKeyword = 'external';
var includeLocation = 'href';
if (typeof jsonData === "object") {
for (var key in jsonData) {
// If an object's property contains an array, go through the objects in the array
// Endpoints and Methods are examples of this
// Endpoints contains a list of javascript objects, which are easily split into individual files.
// Each endpoint is basically a 1 to 1 javascript object relationship
// Methods aren't quite as nice.
// It could be convenient to split methods into get/put/post/delete externals.
// This then creates a 1 to many javascript object relationship
if (what.call(jsonData[key]) === '[object Array]') {
var i = jsonData[key].length;
// Iterating through the array in reverse so that if an element needs to be replaced
// by multiple elements, the array index does not need to be updated.
while (i--) {
var arrayObj = jsonData[key][i];
if ( includeKeyword in arrayObj ) {
var tempArray = getData(apiName, arrayObj[includeKeyword][includeLocation]);
// 1 include request to be replaced by multiple objects (methods)
if (arrayObj[includeKeyword]['type'] == 'list') {
// recurse here to replace values of properties that may need replacing
processApiIncludes(tempArray, apiName);
// why isn't this jsonData[key][i]?
// Because the array itself is being replaced with an updated version
jsonData[key] = mergeExternal(i, jsonData[key], tempArray);
}
// 1 include request to be replaced by 1 object (endpoint)
else {
jsonData[key][i] = tempArray;
processApiIncludes(jsonData[key][i], apiName);
}
}
}
}
// If an object's property contains an include statement, this will handle it.
if (what.call(jsonData[key]) === '[object Object]') {
for (var property in jsonData[key]) {
if (what.call(jsonData[key][property]) === '[object Object]') {
if (includeKeyword in jsonData[key][property]) {
jsonData[key][property] = getData(apiName, jsonData[key][property][includeKeyword][includeLocation]);
processApiIncludes(jsonData[key][property], apiName);
}
}
}
}
}
}
}
// Takes the array position of an element in array1, removes that element,
// and in its place, the contents of array2 are merged in.
function mergeExternal (arrayPos, array1, array2) {
var a1_tail = array1.splice(arrayPos, array1.length);
a1_tail.splice(0, 1);
return array1.concat(array2).concat(a1_tail);
}
// Search function.
// Expects processed API json data and a search term.
// There should be no 'external' link objects present.
function search (jsonData, searchTerm) {
// From: http://simonwillison.net/2006/Jan/20/escape/#p-6
var regexFriendly = function(text) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};
// If ' OR ' is present in the search string, the search term will be split on ' OR ',
// and the first two parts will be used. These two parts will have spaces
// stripped from them and then the regex term will present results that contain
// matches that have either term.
//
// If ' OR ' is not present, the given term will be searched for, spaces will not be
// removed from the given term in this case.
var regex;
if (/\s+OR\s+/.test(searchTerm)) {
var terms = searchTerm.split(/\s+OR\s+/);
terms[0] = regexFriendly(terms[0].replace(/\s+/, ''));
terms[1] = regexFriendly(terms[1].replace(/\s+/, ''));
regex = new RegExp ( "("+terms[0]+"|"+terms[1]+")" , "i");
}
else {
var terms = searchTerm.split(/\s+/);
var regexString = "";
for (var t = 0; t < terms.length; t++) {
regexString += "(?=.*" + regexFriendly(terms[t]) + ")";
}
regex = new RegExp( regexString, "i" );
}
// Get a list of all methods from the data.
var searchMatches = [];
// Iterate through endpoints
for (var i = 0; i < jsonData.endpoints.length; i++) {
var object = jsonData.endpoints[i];
// Iterate through methods
for (var j = 0; j < object.methods.length; j++) {
if ( filterSearchObject(object.methods[j], regex) ) {
searchMatches.push({"label":object.methods[j]['MethodName'], "category": object.name, "type":object.methods[j]['HTTPMethod']});
}
}
}
return searchMatches;
}
// Method searching function
// Recursively check properties of a method object for a match to the given search term.
function filterSearchObject (randomThing, regex) {
var what = Object.prototype.toString;
if (what.call(randomThing) === '[object Array]') {
for (var i = 0; i < randomThing.length; i++) {
if (filterSearchObject(randomThing[i], regex)) {
return true;
}
}
}
else if (what.call(randomThing) === '[object Object]') {
for (var methodProperty in randomThing) {
if (randomThing.hasOwnProperty(methodProperty)) {
if (filterSearchObject(randomThing[methodProperty], regex)) {
return true;
}
}
}
}
else if (what.call(randomThing) === '[object String]' || what.call(randomThing) === '[object Number]' ) {
if ( regex.test(randomThing)) {
return true;
}
}
else {
return false;
}
return false;
}
//
// Routes
//
app.get('/', function(req, res) {
res.render('listAPIs', {
title: config.title
});
});
//
// Search function
//
// Note: If a change is made to app.js, the node process restarted, and the search
// function is used immediately without restart, there will be an error coming from the
// search() function regarding the use of '.length'. Refresh the page, and the error
// will go away. A page refresh is necessary to create a cached version of the api
// which this route uses.
// Not sure what the fix for this is.
app.get('/search', function(req, res) {
var searchTerm = decodeURIComponent(req.query.term);
res.send( search(cachedApiInfo, searchTerm) );
});
// Process the API request
app.post('/processReq', oauth, processRequest, function(req, res) {
var result = {
headers: req.resultHeaders,
response: req.result,
call: req.call,
code: req.res.statusCode
};
res.send(result);
});
// Just auth
app.all('/auth', oauth);