-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcallback.js
4928 lines (4352 loc) · 185 KB
/
callback.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
require = (function () {
function r(e, n, t) {
function o(i, f) {
if (!n[i]) {
if (!e[i]) {
var c = "function" == typeof require && require;
if (!f && c) return c(i, !0);
if (u) return u(i, !0);
var a = new Error("Cannot find module '" + i + "'");
throw a.code = "MODULE_NOT_FOUND", a
}
var p = n[i] = {
exports: {}
};
e[i][0].call(p.exports, function (r) {
var n = e[i][1][r];
return o(n || r)
}, p, p.exports, r, e, n, t)
}
return n[i].exports
}
for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) o(t[i]);
return o
}
return r
})()({
1: [function (require, module, exports) {
/*!
* cookie
* Copyright(c) 2012-2014 Roman Shtylman
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict';
/**
* Module exports.
* @public
*/
exports.parse = parse;
exports.serialize = serialize;
/**
* Module variables.
* @private
*/
var decode = decodeURIComponent;
var encode = encodeURIComponent;
var pairSplitRegExp = /; */;
/**
* RegExp to match field-content in RFC 7230 sec 3.2
*
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* obs-text = %x80-FF
*/
var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
/**
* Parse a cookie header.
*
* Parse the given cookie header string into an object
* The object has the various cookies as keys(names) => values
*
* @param {string} str
* @param {object} [options]
* @return {object}
* @public
*/
function parse(str, options) {
if (typeof str !== 'string') {
throw new TypeError('argument str must be a string');
}
var obj = {}
var opt = options || {};
var pairs = str.split(pairSplitRegExp);
var dec = opt.decode || decode;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i];
var eq_idx = pair.indexOf('=');
// skip things that don't look like key=value
if (eq_idx < 0) {
continue;
}
var key = pair.substr(0, eq_idx).trim()
var val = pair.substr(++eq_idx, pair.length).trim();
// quoted values
if ('"' == val[0]) {
val = val.slice(1, -1);
}
// only assign once
if (undefined == obj[key]) {
obj[key] = tryDecode(val, dec);
}
}
return obj;
}
/**
* Serialize data into a cookie header.
*
* Serialize the a name value pair into a cookie string suitable for
* http headers. An optional options object specified cookie parameters.
*
* serialize('foo', 'bar', { httpOnly: true })
* => "foo=bar; httpOnly"
*
* @param {string} name
* @param {string} val
* @param {object} [options]
* @return {string}
* @public
*/
function serialize(name, val, options) {
var opt = options || {};
var enc = opt.encode || encode;
if (typeof enc !== 'function') {
throw new TypeError('option encode is invalid');
}
if (!fieldContentRegExp.test(name)) {
throw new TypeError('argument name is invalid');
}
var value = enc(val);
if (value && !fieldContentRegExp.test(value)) {
throw new TypeError('argument val is invalid');
}
var str = name + '=' + value;
if (null != opt.maxAge) {
var maxAge = opt.maxAge - 0;
if (isNaN(maxAge)) throw new Error('maxAge should be a Number');
str += '; Max-Age=' + Math.floor(maxAge);
}
if (opt.domain) {
if (!fieldContentRegExp.test(opt.domain)) {
throw new TypeError('option domain is invalid');
}
str += '; Domain=' + opt.domain;
}
if (opt.path) {
if (!fieldContentRegExp.test(opt.path)) {
throw new TypeError('option path is invalid');
}
str += '; Path=' + opt.path;
}
if (opt.expires) {
if (typeof opt.expires.toUTCString !== 'function') {
throw new TypeError('option expires is invalid');
}
str += '; Expires=' + opt.expires.toUTCString();
}
if (opt.httpOnly) {
str += '; HttpOnly';
}
if (opt.secure) {
str += '; Secure';
}
if (opt.sameSite) {
var sameSite = typeof opt.sameSite === 'string' ?
opt.sameSite.toLowerCase() : opt.sameSite;
switch (sameSite) {
case true:
str += '; SameSite=Strict';
break;
case 'lax':
str += '; SameSite=Lax';
break;
case 'strict':
str += '; SameSite=Strict';
break;
default:
throw new TypeError('option sameSite is invalid');
}
}
return str;
}
/**
* Try decoding a string using a decoding function.
*
* @param {string} str
* @param {function} decode
* @private
*/
function tryDecode(str, decode) {
try {
return decode(str);
} catch (e) {
return str;
}
}
}, {}],
2: [function (require, module, exports) {
exports.OAuth = require("./lib/oauth").OAuth;
exports.OAuthEcho = require("./lib/oauth").OAuthEcho;
exports.OAuth2 = require("./lib/oauth2").OAuth2;
}, {
"./lib/oauth": 4,
"./lib/oauth2": 5
}],
3: [function (require, module, exports) {
// Returns true if this is a host that closes *before* it ends?!?!
module.exports.isAnEarlyCloseHost = function (hostName) {
return hostName && hostName.match(".*google(apis)?.com$")
}
}, {}],
4: [function (require, module, exports) {
var crypto = require('crypto'),
sha1 = require('./sha1'),
http = require('http'),
https = require('https'),
URL = require('url'),
querystring = require('querystring'),
OAuthUtils = require('./_utils');
exports.OAuth = function (requestUrl, accessUrl, consumerKey, consumerSecret, version, authorize_callback, signatureMethod, nonceSize, customHeaders) {
this._isEcho = false;
this._requestUrl = requestUrl;
this._accessUrl = accessUrl;
this._consumerKey = consumerKey;
this._consumerSecret = this._encodeData(consumerSecret);
if (signatureMethod == "RSA-SHA1") {
this._privateKey = consumerSecret;
}
this._version = version;
if (authorize_callback === undefined) {
this._authorize_callback = "oob";
} else {
this._authorize_callback = authorize_callback;
}
if (signatureMethod != "PLAINTEXT" && signatureMethod != "HMAC-SHA1" && signatureMethod != "RSA-SHA1")
throw new Error("Un-supported signature method: " + signatureMethod)
this._signatureMethod = signatureMethod;
this._nonceSize = nonceSize || 32;
this._headers = customHeaders || {
"Accept": "*/*",
"Connection": "close",
"User-Agent": "Node authentication"
}
this._clientOptions = this._defaultClientOptions = {
"requestTokenHttpMethod": "POST",
"accessTokenHttpMethod": "POST",
"followRedirects": true
};
this._oauthParameterSeperator = ",";
};
exports.OAuthEcho = function (realm, verify_credentials, consumerKey, consumerSecret, version, signatureMethod, nonceSize, customHeaders) {
this._isEcho = true;
this._realm = realm;
this._verifyCredentials = verify_credentials;
this._consumerKey = consumerKey;
this._consumerSecret = this._encodeData(consumerSecret);
if (signatureMethod == "RSA-SHA1") {
this._privateKey = consumerSecret;
}
this._version = version;
if (signatureMethod != "PLAINTEXT" && signatureMethod != "HMAC-SHA1" && signatureMethod != "RSA-SHA1")
throw new Error("Un-supported signature method: " + signatureMethod);
this._signatureMethod = signatureMethod;
this._nonceSize = nonceSize || 32;
this._headers = customHeaders || {
"Accept": "*/*",
"Connection": "close",
"User-Agent": "Node authentication"
};
this._oauthParameterSeperator = ",";
}
exports.OAuthEcho.prototype = exports.OAuth.prototype;
exports.OAuth.prototype._getTimestamp = function () {
return Math.floor((new Date()).getTime() / 1000);
}
exports.OAuth.prototype._encodeData = function (toEncode) {
if (toEncode == null || toEncode == "") return ""
else {
var result = encodeURIComponent(toEncode);
// Fix the mismatch between OAuth's RFC3986's and Javascript's beliefs in what is right and wrong ;)
return result.replace(/\!/g, "%21")
.replace(/\'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A");
}
}
exports.OAuth.prototype._decodeData = function (toDecode) {
if (toDecode != null) {
toDecode = toDecode.replace(/\+/g, " ");
}
return decodeURIComponent(toDecode);
}
exports.OAuth.prototype._getSignature = function (method, url, parameters, tokenSecret) {
var signatureBase = this._createSignatureBase(method, url, parameters);
return this._createSignature(signatureBase, tokenSecret);
}
exports.OAuth.prototype._normalizeUrl = function (url) {
var parsedUrl = URL.parse(url, true)
var port = "";
if (parsedUrl.port) {
if ((parsedUrl.protocol == "http:" && parsedUrl.port != "80") ||
(parsedUrl.protocol == "https:" && parsedUrl.port != "443")) {
port = ":" + parsedUrl.port;
}
}
if (!parsedUrl.pathname || parsedUrl.pathname == "") parsedUrl.pathname = "/";
return parsedUrl.protocol + "//" + parsedUrl.hostname + port + parsedUrl.pathname;
}
// Is the parameter considered an OAuth parameter
exports.OAuth.prototype._isParameterNameAnOAuthParameter = function (parameter) {
var m = parameter.match('^oauth_');
if (m && (m[0] === "oauth_")) {
return true;
} else {
return false;
}
};
// build the OAuth request authorization header
exports.OAuth.prototype._buildAuthorizationHeaders = function (orderedParameters) {
var authHeader = "OAuth ";
if (this._isEcho) {
authHeader += 'realm="' + this._realm + '",';
}
for (var i = 0; i < orderedParameters.length; i++) {
// Whilst the all the parameters should be included within the signature, only the oauth_ arguments
// should appear within the authorization header.
if (this._isParameterNameAnOAuthParameter(orderedParameters[i][0])) {
authHeader += "" + this._encodeData(orderedParameters[i][0]) + "=\"" + this._encodeData(orderedParameters[i][1]) + "\"" + this._oauthParameterSeperator;
}
}
authHeader = authHeader.substring(0, authHeader.length - this._oauthParameterSeperator.length);
return authHeader;
}
// Takes an object literal that represents the arguments, and returns an array
// of argument/value pairs.
exports.OAuth.prototype._makeArrayOfArgumentsHash = function (argumentsHash) {
var argument_pairs = [];
for (var key in argumentsHash) {
if (argumentsHash.hasOwnProperty(key)) {
var value = argumentsHash[key];
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
argument_pairs[argument_pairs.length] = [key, value[i]];
}
} else {
argument_pairs[argument_pairs.length] = [key, value];
}
}
}
return argument_pairs;
}
// Sorts the encoded key value pairs by encoded name, then encoded value
exports.OAuth.prototype._sortRequestParams = function (argument_pairs) {
// Sort by name, then value.
argument_pairs.sort(function (a, b) {
if (a[0] == b[0]) {
return a[1] < b[1] ? -1 : 1;
} else return a[0] < b[0] ? -1 : 1;
});
return argument_pairs;
}
exports.OAuth.prototype._normaliseRequestParams = function (args) {
var argument_pairs = this._makeArrayOfArgumentsHash(args);
// First encode them #3.4.1.3.2 .1
for (var i = 0; i < argument_pairs.length; i++) {
argument_pairs[i][0] = this._encodeData(argument_pairs[i][0]);
argument_pairs[i][1] = this._encodeData(argument_pairs[i][1]);
}
// Then sort them #3.4.1.3.2 .2
argument_pairs = this._sortRequestParams(argument_pairs);
// Then concatenate together #3.4.1.3.2 .3 & .4
var args = "";
for (var i = 0; i < argument_pairs.length; i++) {
args += argument_pairs[i][0];
args += "="
args += argument_pairs[i][1];
if (i < argument_pairs.length - 1) args += "&";
}
return args;
}
exports.OAuth.prototype._createSignatureBase = function (method, url, parameters) {
url = this._encodeData(this._normalizeUrl(url));
parameters = this._encodeData(parameters);
return method.toUpperCase() + "&" + url + "&" + parameters;
}
exports.OAuth.prototype._createSignature = function (signatureBase, tokenSecret) {
if (tokenSecret === undefined) var tokenSecret = "";
else tokenSecret = this._encodeData(tokenSecret);
// consumerSecret is already encoded
var key = this._consumerSecret + "&" + tokenSecret;
var hash = ""
if (this._signatureMethod == "PLAINTEXT") {
hash = key;
} else if (this._signatureMethod == "RSA-SHA1") {
key = this._privateKey || "";
hash = crypto.createSign("RSA-SHA1").update(signatureBase).sign(key, 'base64');
} else {
if (crypto.Hmac) {
hash = crypto.createHmac("sha1", key).update(signatureBase).digest("base64");
} else {
hash = sha1.HMACSHA1(key, signatureBase);
}
}
return hash;
}
exports.OAuth.prototype.NONCE_CHARS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9'
];
exports.OAuth.prototype._getNonce = function (nonceSize) {
var result = [];
var chars = this.NONCE_CHARS;
var char_pos;
var nonce_chars_length = chars.length;
for (var i = 0; i < nonceSize; i++) {
char_pos = Math.floor(Math.random() * nonce_chars_length);
result[i] = chars[char_pos];
}
return result.join('');
}
exports.OAuth.prototype._createClient = function (port, hostname, method, path, headers, sslEnabled) {
var options = {
host: hostname,
port: port,
path: path,
method: method,
headers: headers
};
var httpModel;
if (sslEnabled) {
httpModel = https;
} else {
httpModel = http;
}
return httpModel.request(options);
}
exports.OAuth.prototype._prepareParameters = function (oauth_token, oauth_token_secret, method, url, extra_params) {
var oauthParameters = {
"oauth_timestamp": this._getTimestamp(),
"oauth_nonce": this._getNonce(this._nonceSize),
"oauth_version": this._version,
"oauth_signature_method": this._signatureMethod,
"oauth_consumer_key": this._consumerKey
};
if (oauth_token) {
oauthParameters["oauth_token"] = oauth_token;
}
var sig;
if (this._isEcho) {
sig = this._getSignature("GET", this._verifyCredentials, this._normaliseRequestParams(oauthParameters), oauth_token_secret);
} else {
if (extra_params) {
for (var key in extra_params) {
if (extra_params.hasOwnProperty(key)) oauthParameters[key] = extra_params[key];
}
}
var parsedUrl = URL.parse(url, false);
if (parsedUrl.query) {
var key2;
var extraParameters = querystring.parse(parsedUrl.query);
for (var key in extraParameters) {
var value = extraParameters[key];
if (typeof value == "object") {
// TODO: This probably should be recursive
for (key2 in value) {
oauthParameters[key + "[" + key2 + "]"] = value[key2];
}
} else {
oauthParameters[key] = value;
}
}
}
sig = this._getSignature(method, url, this._normaliseRequestParams(oauthParameters), oauth_token_secret);
}
var orderedParameters = this._sortRequestParams(this._makeArrayOfArgumentsHash(oauthParameters));
orderedParameters[orderedParameters.length] = ["oauth_signature", sig];
return orderedParameters;
}
exports.OAuth.prototype._performSecureRequest = function (oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback) {
var orderedParameters = this._prepareParameters(oauth_token, oauth_token_secret, method, url, extra_params);
if (!post_content_type) {
post_content_type = "application/x-www-form-urlencoded";
}
var parsedUrl = URL.parse(url, false);
if (parsedUrl.protocol == "http:" && !parsedUrl.port) parsedUrl.port = 80;
if (parsedUrl.protocol == "https:" && !parsedUrl.port) parsedUrl.port = 443;
var headers = {};
var authorization = this._buildAuthorizationHeaders(orderedParameters);
if (this._isEcho) {
headers["X-Verify-Credentials-Authorization"] = authorization;
} else {
headers["Authorization"] = authorization;
}
headers["Host"] = parsedUrl.host
for (var key in this._headers) {
if (this._headers.hasOwnProperty(key)) {
headers[key] = this._headers[key];
}
}
// Filter out any passed extra_params that are really to do with OAuth
for (var key in extra_params) {
if (this._isParameterNameAnOAuthParameter(key)) {
delete extra_params[key];
}
}
if ((method == "POST" || method == "PUT") && (post_body == null && extra_params != null)) {
// Fix the mismatch between the output of querystring.stringify() and this._encodeData()
post_body = querystring.stringify(extra_params)
.replace(/\!/g, "%21")
.replace(/\'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A");
}
if (post_body) {
if (Buffer.isBuffer(post_body)) {
headers["Content-length"] = post_body.length;
} else {
headers["Content-length"] = Buffer.byteLength(post_body);
}
} else {
headers["Content-length"] = 0;
}
headers["Content-Type"] = post_content_type;
var path;
if (!parsedUrl.pathname || parsedUrl.pathname == "") parsedUrl.pathname = "/";
if (parsedUrl.query) path = parsedUrl.pathname + "?" + parsedUrl.query;
else path = parsedUrl.pathname;
var request;
if (parsedUrl.protocol == "https:") {
request = this._createClient(parsedUrl.port, parsedUrl.hostname, method, path, headers, true);
} else {
request = this._createClient(parsedUrl.port, parsedUrl.hostname, method, path, headers);
}
var clientOptions = this._clientOptions;
if (callback) {
var data = "";
var self = this;
// Some hosts *cough* google appear to close the connection early / send no content-length header
// allow this behaviour.
var allowEarlyClose = OAuthUtils.isAnEarlyCloseHost(parsedUrl.hostname);
var callbackCalled = false;
var passBackControl = function (response) {
if (!callbackCalled) {
callbackCalled = true;
if (response.statusCode >= 200 && response.statusCode <= 299) {
callback(null, data, response);
} else {
// Follow 301 or 302 redirects with Location HTTP header
if ((response.statusCode == 301 || response.statusCode == 302) && clientOptions.followRedirects && response.headers && response.headers.location) {
self._performSecureRequest(oauth_token, oauth_token_secret, method, response.headers.location, extra_params, post_body, post_content_type, callback);
} else {
callback({
statusCode: response.statusCode,
data: data
}, data, response);
}
}
}
}
request.on('response', function (response) {
response.setEncoding('utf8');
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
passBackControl(response);
});
response.on('close', function () {
if (allowEarlyClose) {
passBackControl(response);
}
});
});
request.on("error", function (err) {
if (!callbackCalled) {
callbackCalled = true;
callback(err)
}
});
if ((method == "POST" || method == "PUT") && post_body != null && post_body != "") {
request.write(post_body);
}
request.end();
} else {
if ((method == "POST" || method == "PUT") && post_body != null && post_body != "") {
request.write(post_body);
}
return request;
}
return;
}
exports.OAuth.prototype.setClientOptions = function (options) {
var key,
mergedOptions = {},
hasOwnProperty = Object.prototype.hasOwnProperty;
for (key in this._defaultClientOptions) {
if (!hasOwnProperty.call(options, key)) {
mergedOptions[key] = this._defaultClientOptions[key];
} else {
mergedOptions[key] = options[key];
}
}
this._clientOptions = mergedOptions;
};
exports.OAuth.prototype.getOAuthAccessToken = function (oauth_token, oauth_token_secret, oauth_verifier, callback) {
var extraParams = {};
if (typeof oauth_verifier == "function") {
callback = oauth_verifier;
} else {
extraParams.oauth_verifier = oauth_verifier;
}
this._performSecureRequest(oauth_token, oauth_token_secret, this._clientOptions.accessTokenHttpMethod, this._accessUrl, extraParams, null, null, function (error, data, response) {
if (error) callback(error);
else {
var results = querystring.parse(data);
var oauth_access_token = results["oauth_token"];
delete results["oauth_token"];
var oauth_access_token_secret = results["oauth_token_secret"];
delete results["oauth_token_secret"];
callback(null, oauth_access_token, oauth_access_token_secret, results);
}
})
}
// Deprecated
exports.OAuth.prototype.getProtectedResource = function (url, method, oauth_token, oauth_token_secret, callback) {
this._performSecureRequest(oauth_token, oauth_token_secret, method, url, null, "", null, callback);
}
exports.OAuth.prototype.delete = function (url, oauth_token, oauth_token_secret, callback) {
return this._performSecureRequest(oauth_token, oauth_token_secret, "DELETE", url, null, "", null, callback);
}
exports.OAuth.prototype.get = function (url, oauth_token, oauth_token_secret, callback) {
return this._performSecureRequest(oauth_token, oauth_token_secret, "GET", url, null, "", null, callback);
}
exports.OAuth.prototype._putOrPost = function (method, url, oauth_token, oauth_token_secret, post_body, post_content_type, callback) {
var extra_params = null;
if (typeof post_content_type == "function") {
callback = post_content_type;
post_content_type = null;
}
if (typeof post_body != "string" && !Buffer.isBuffer(post_body)) {
post_content_type = "application/x-www-form-urlencoded"
extra_params = post_body;
post_body = null;
}
return this._performSecureRequest(oauth_token, oauth_token_secret, method, url, extra_params, post_body, post_content_type, callback);
}
exports.OAuth.prototype.put = function (url, oauth_token, oauth_token_secret, post_body, post_content_type, callback) {
return this._putOrPost("PUT", url, oauth_token, oauth_token_secret, post_body, post_content_type, callback);
}
exports.OAuth.prototype.post = function (url, oauth_token, oauth_token_secret, post_body, post_content_type, callback) {
return this._putOrPost("POST", url, oauth_token, oauth_token_secret, post_body, post_content_type, callback);
}
/**
* Gets a request token from the OAuth provider and passes that information back
* to the calling code.
*
* The callback should expect a function of the following form:
*
* function(err, token, token_secret, parsedQueryString) {}
*
* This method has optional parameters so can be called in the following 2 ways:
*
* 1) Primary use case: Does a basic request with no extra parameters
* getOAuthRequestToken( callbackFunction )
*
* 2) As above but allows for provision of extra parameters to be sent as part of the query to the server.
* getOAuthRequestToken( extraParams, callbackFunction )
*
* N.B. This method will HTTP POST verbs by default, if you wish to override this behaviour you will
* need to provide a requestTokenHttpMethod option when creating the client.
*
**/
exports.OAuth.prototype.getOAuthRequestToken = function (extraParams, callback) {
if (typeof extraParams == "function") {
callback = extraParams;
extraParams = {};
}
// Callbacks are 1.0A related
if (this._authorize_callback) {
extraParams["oauth_callback"] = this._authorize_callback;
}
this._performSecureRequest(null, null, this._clientOptions.requestTokenHttpMethod, this._requestUrl, extraParams, null, null, function (error, data, response) {
if (error) callback(error);
else {
var results = querystring.parse(data);
var oauth_token = results["oauth_token"];
var oauth_token_secret = results["oauth_token_secret"];
delete results["oauth_token"];
delete results["oauth_token_secret"];
callback(null, oauth_token, oauth_token_secret, results);
}
});
}
exports.OAuth.prototype.signUrl = function (url, oauth_token, oauth_token_secret, method) {
if (method === undefined) {
var method = "GET";
}
var orderedParameters = this._prepareParameters(oauth_token, oauth_token_secret, method, url, {});
var parsedUrl = URL.parse(url, false);
var query = "";
for (var i = 0; i < orderedParameters.length; i++) {
query += orderedParameters[i][0] + "=" + this._encodeData(orderedParameters[i][1]) + "&";
}
query = query.substring(0, query.length - 1);
return parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname + "?" + query;
};
exports.OAuth.prototype.authHeader = function (url, oauth_token, oauth_token_secret, method) {
if (method === undefined) {
var method = "GET";
}
var orderedParameters = this._prepareParameters(oauth_token, oauth_token_secret, method, url, {});
return this._buildAuthorizationHeaders(orderedParameters);
};
}, {
"./_utils": 3,
"./sha1": 6,
"crypto": undefined,
"http": undefined,
"https": undefined,
"querystring": undefined,
"url": undefined
}],
5: [function (require, module, exports) {
var querystring = require('querystring'),
crypto = require('crypto'),
https = require('https'),
http = require('http'),
URL = require('url'),
OAuthUtils = require('./_utils');
exports.OAuth2 = function (clientId, clientSecret, baseSite, authorizePath, accessTokenPath, customHeaders) {
this._clientId = clientId;
this._clientSecret = clientSecret;
this._baseSite = baseSite;
this._authorizeUrl = authorizePath || "/oauth/authorize";
this._accessTokenUrl = accessTokenPath || "/oauth/access_token";
this._accessTokenName = "access_token";
this._authMethod = "Bearer";
this._customHeaders = customHeaders || {};
this._useAuthorizationHeaderForGET = false;
//our agent
this._agent = undefined;
};
// Allows you to set an agent to use instead of the default HTTP or
// HTTPS agents. Useful when dealing with your own certificates.
exports.OAuth2.prototype.setAgent = function (agent) {
this._agent = agent;
};
// This 'hack' method is required for sites that don't use
// 'access_token' as the name of the access token (for requests).
// ( http://tools.ietf.org/html/draft-ietf-oauth-v2-16#section-7 )
// it isn't clear what the correct value should be atm, so allowing
// for specific (temporary?) override for now.
exports.OAuth2.prototype.setAccessTokenName = function (name) {
this._accessTokenName = name;
}
// Sets the authorization method for Authorization header.
// e.g. Authorization: Bearer <token> # "Bearer" is the authorization method.
exports.OAuth2.prototype.setAuthMethod = function (authMethod) {
this._authMethod = authMethod;
};
// If you use the OAuth2 exposed 'get' method (and don't construct your own _request call )
// this will specify whether to use an 'Authorize' header instead of passing the access_token as a query parameter
exports.OAuth2.prototype.useAuthorizationHeaderforGET = function (useIt) {
this._useAuthorizationHeaderForGET = useIt;
}
exports.OAuth2.prototype._getAccessTokenUrl = function () {
return this._baseSite + this._accessTokenUrl;
/* + "?" + querystring.stringify(params); */
}
// Build the authorization header. In particular, build the part after the colon.
// e.g. Authorization: Bearer <token> # Build "Bearer <token>"
exports.OAuth2.prototype.buildAuthHeader = function (token) {
return this._authMethod + ' ' + token;
};
exports.OAuth2.prototype._chooseHttpLibrary = function (parsedUrl) {
var http_library = https;
// As this is OAUth2, we *assume* https unless told explicitly otherwise.
if (parsedUrl.protocol != "https:") {
http_library = http;
}
return http_library;
};
exports.OAuth2.prototype._request = function (method, url, headers, post_body, access_token, callback) {
var parsedUrl = URL.parse(url, true);
if (parsedUrl.protocol == "https:" && !parsedUrl.port) {
parsedUrl.port = 443;
}
var http_library = this._chooseHttpLibrary(parsedUrl);
var realHeaders = {};
for (var key in this._customHeaders) {
realHeaders[key] = this._customHeaders[key];
}
if (headers) {
for (var key in headers) {
realHeaders[key] = headers[key];
}
}
realHeaders['Host'] = parsedUrl.host;
if (!realHeaders['User-Agent']) {
realHeaders['User-Agent'] = 'Node-oauth';
}
if (post_body) {
if (Buffer.isBuffer(post_body)) {
realHeaders["Content-Length"] = post_body.length;
} else {
realHeaders["Content-Length"] = Buffer.byteLength(post_body);
}
} else {
realHeaders["Content-length"] = 0;
}
if (access_token && !('Authorization' in realHeaders)) {
if (!parsedUrl.query) parsedUrl.query = {};
parsedUrl.query[this._accessTokenName] = access_token;
}
var queryStr = querystring.stringify(parsedUrl.query);
if (queryStr) queryStr = "?" + queryStr;
var options = {
host: parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.pathname + queryStr,
method: method,
headers: realHeaders
};
this._executeRequest(http_library, options, post_body, callback);
}
exports.OAuth2.prototype._executeRequest = function (http_library, options, post_body, callback) {
// Some hosts *cough* google appear to close the connection early / send no content-length header
// allow this behaviour.
var allowEarlyClose = OAuthUtils.isAnEarlyCloseHost(options.host);
var callbackCalled = false;
function passBackControl(response, result) {
if (!callbackCalled) {
callbackCalled = true;
if (!(response.statusCode >= 200 && response.statusCode <= 299) && (response.statusCode != 301) && (response.statusCode != 302)) {
callback({
statusCode: response.statusCode,
data: result
});
} else {
callback(null, result, response);
}
}
}
var result = "";
//set the agent on the request options
if (this._agent) {
options.agent = this._agent;
}
var request = http_library.request(options);
request.on('response', function (response) {
response.on("data", function (chunk) {
result += chunk
});
response.on("close", function (err) {
if (allowEarlyClose) {
passBackControl(response, result);
}
});
response.addListener("end", function () {
passBackControl(response, result);
});
});
request.on('error', function (e) {
callbackCalled = true;
callback(e);
});