forked from MrSwitch/node-oauth-shim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoauth.js
97 lines (83 loc) · 2.32 KB
/
oauth.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
//
// OAuth
// Author Andrew Dodson
var crypto = require('crypto'),
url = require('url'),
querystring = require('querystring');
function merge(a,b){
var x,r = {};
if( typeof(a) === 'object' && typeof(b) === 'object' ){
for(x in a){if(a.hasOwnProperty(x)){
r[x] = a[x];
if(x in b){
r[x] = merge( a[x], b[x]);
}
}}
for(x in b){if(b.hasOwnProperty(x)){
if(!(x in a)){
r[x] = b[x];
}
}}
}
else{
r = b;
}
return r;
}
function hashString(key, str, encoding){
var hmac = crypto.createHmac("sha1", key);
hmac.update(str);
return hmac.digest(encoding);
}
function encode(s){
return encodeURIComponent(s).replace(/\!/g, "%21")
.replace(/\'/g, "%27")
.replace(/\(/g, "%28")
.replace(/\)/g, "%29")
.replace(/\*/g, "%2A");
}
module.exports = new (function(){
this.sign = function( uri, opts, consumer_secret, token_secret, nonce, method, data ){
// Damage control
if(!opts.oauth_consumer_key){
console.error('OAuth requires opts.oauth_consumer_key');
}
// Seperate querystring from path
var path = uri.replace(/[\?\#].*/,''),
qs = querystring.parse(url.parse(uri).query);
// Create OAuth Properties
var query = {
oauth_nonce : nonce || parseInt(Math.random()*1e20,10).toString(16),
oauth_timestamp : nonce || parseInt((new Date()).getTime()/1000,10),
oauth_signature_method : 'HMAC-SHA1',
oauth_version : '1.0'
};
// Merge opts and querystring
query = merge( query, opts || {} );
query = merge( query, qs || {} );
query = merge( query, data || {} );
// Sort in order of properties
var keys = Object.keys(query);
keys.sort();
var params = [],
_queryString = [];
keys.forEach(function(k){
if(query[k]){
params.push( k + "=" + encode(query[k]) );
if( !data || !(k in data)){
_queryString.push( k + "=" + encode(query[k]) );
}
}
});
params = params.join('&');
_queryString = _queryString.join('&');
var http = [method || "GET", encode(path).replace(/\+/g," ").replace(/\%7E/g,'~'), encode(params).replace(/\+/g," ").replace(/\%7E/g,'~') ];
// Create oauth_signature
query.oauth_signature = hashString(
consumer_secret+'&'+(token_secret||''),
http.join('&'),
"base64"
);
return path + '?' + _queryString +'&oauth_signature='+encode( query.oauth_signature );
};
});