oauth2.js
2.03 KB
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
var https = require('https')
, qs = require('querystring');
exports.OAuth2 = OAuth2 = function(options) {
this.base = options.base;
this.tokenUrl = options.tokenUrl;
this.redirectUri = options.redirectUri;
this.id = options.id;
this.secret = options.secret;
this.version = '0.0.1';
}
OAuth2.prototype.tokenRequest = function(params, headers, callback) {
var self = this
, body
, headers
, params
, req;
params['client_id'] = self.id;
params['client_secret'] = self.secret;
params['redirect_uri'] = self.redirectUri;
body = new Buffer(qs.stringify(params));
headers['host'] = self.base;
headers['accept'] = 'application/json';
headers['content-type'] = 'application/x-www-form-urlencoded';
headers['content-length'] = body.length;
var options = {
host: self.base,
port: 443,
path: self.tokenUrl,
method: 'POST',
headers: headers
};
var req = https.request(options, function(res) {
res.setEncoding('utf8');
var result = '';
res.on('data', function(data) {
result += data;
});
res.on('end', function() {
try {
result = JSON.parse(result);
} catch(err) {
console.log(err);
}
if(callback) callback(res.statusCode, result);
});
});
req.write(body);
req.end();
req.on('error', function(e) {
console.error(e);
});
req.write(body);
}
OAuth2.prototype.accessToken = function(code, headers, callback) {
var params = { 'code': code
, 'grant_type': 'authorization_code'
};
this.tokenRequest(params, headers, callback);
}
OAuth2.prototype.refreshToken = function(refreshToken, headers, callback) {
var params = { 'refresh_token': refreshToken
, 'grant_type': 'refresh_token'
};
this.tokenRequest(params, headers, callback);
}
OAuth2.prototype.request = function(method, url, headers, auth) {
headers['Authorization'] = 'OAuth ' + auth['access_token'];
headers['Host'] = this.base;
return this.client.request(method, url, headers);
}