-
Notifications
You must be signed in to change notification settings - Fork 16
/
oauth2.js
212 lines (176 loc) · 6.78 KB
/
oauth2.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
const querystring= require('querystring');
const https= require('https');
const http= require('http');
const URL= require('url');
exports.OAuth2= function(clientId, clientSecret, baseSite, authorizePath, accessTokenPath, callbackURL, customHeaders) {
this._clientId= clientId;
this._clientSecret= clientSecret;
this._baseSite= baseSite;
this._authorizeUrl= authorizePath || "/oauth/authorize";
this._accessTokenUrl= accessTokenPath || "/oauth/access_token";
this._callbackURL = callbackURL;
this._accessTokenName= "access_token";
this._authMethod= "Basic";
this._customHeaders = customHeaders || {};
}
// 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;
}
exports.OAuth2.prototype._getAccessTokenUrl= function() {
return this._baseSite + this._accessTokenUrl;
}
// 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() {
const key = this._clientId + ':' + this._clientSecret;
const base64 = (new Buffer(key)).toString('base64');
return this._authMethod + ' ' + base64;
};
exports.OAuth2.prototype._request= function(method, url, headers, postBody, accessToken, callback) {
let httpLibrary= https;
const parsedUrl= URL.parse( url, true );
if( parsedUrl.protocol === "https:" && !parsedUrl.port ) {
parsedUrl.port= 443;
}
// As this is OAUth2, we *assume* https unless told explicitly otherwise.
if( parsedUrl.protocol !== "https:" ) {
httpLibrary= http;
}
const realHeaders= {};
for( const key in this._customHeaders ) {
realHeaders[key]= this._customHeaders[key];
}
if( headers ) {
for(const key in headers) {
realHeaders[key] = headers[key];
}
}
realHeaders.Host= parsedUrl.host;
//realHeaders['Content-Length']= postBody ? Buffer.byteLength(postBody) : 0;
if( accessToken && !('Authorization' in realHeaders)) {
if( ! parsedUrl.query ) {parsedUrl.query= {};}
parsedUrl.query[this._accessTokenName]= accessToken;
}
let queryStr= querystring.stringify(parsedUrl.query);
if( queryStr ) {queryStr= "?" + queryStr;}
const options = {
host:parsedUrl.hostname,
port: parsedUrl.port,
path: parsedUrl.pathname + queryStr,
method,
headers: realHeaders
};
this._executeRequest( httpLibrary, options, postBody, callback );
}
exports.OAuth2.prototype._executeRequest= function( httpLibrary, options, postBody, callback ) {
// Some hosts *cough* google appear to close the connection early / send no content-length header
// allow this behaviour.
const allowEarlyClose= options.host && options.host.match(".*google(apis)?.com$");
let callbackCalled= false;
function passBackControl( response, result, err ) {
if(!callbackCalled) {
callbackCalled=true;
if( response.statusCode !== 200 && response.statusCode !== 201 && (response.statusCode !== 301) && (response.statusCode !== 302) ) {
callback({ statusCode: response.statusCode, data: result });
} else {
callback(err, result, response);
}
}
}
let result= "";
const request = httpLibrary.request(options, function (response) {
response.on("data", function (chunk) {
result+= chunk
});
response.on("close", function (err) {
if( allowEarlyClose ) {
passBackControl( response, result, err );
}
});
response.addListener("end", function () {
passBackControl( response, result );
});
});
request.on('error', function(e) {
callbackCalled= true;
callback(e);
});
if(options.method === 'POST' && postBody) {
request.write(postBody);
}
request.end();
}
exports.OAuth2.prototype.getAuthorizeUrl= function(responseType) {
responseType = responseType || 'code';
return this._baseSite + this._authorizeUrl + '?response_type=' + responseType + '&client_id=' + this._clientId + '&state=xyz&redirect_uri=' + this._callbackURL;
}
exports.OAuth2.prototype.getAuthorizeUrlJWT= function(responseType) {
responseType = responseType || 'code';
return this._baseSite + this._authorizeUrl + '?response_type=' + responseType + '&client_id=' + this._clientId + '&state=xyz&scope=jwt&redirect_uri=' + this._callbackURL;
}
function getResults(data){
let results;
try {
results= JSON.parse(data);
}
catch(e) {
results= querystring.parse(data);
}
return results;
}
exports.OAuth2.prototype.getOAuthAccessToken= function(code) {
const that = this;
return new Promise((resolve, reject) => {
const postData = 'grant_type=authorization_code&code=' + code + '&redirect_uri=' + that._callbackURL;
const postHeaders= {
'Authorization': that.buildAuthHeader(),
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
};
console.log('Sending access token request to', that._getAccessTokenUrl(), 'with body', postData);
that._request("POST", that._getAccessTokenUrl(), postHeaders, postData, null, (error, data) => {
return error ? reject(error) : resolve(getResults(data));
});
});
}
exports.OAuth2.prototype.getOAuthClientCredentials= function() {
const that = this;
return new Promise((resolve, reject) => {
const postData = 'grant_type=client_credentials';
const postHeaders= {
'Authorization': that.buildAuthHeader(),
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
};
that._request("POST", that._getAccessTokenUrl(), postHeaders, postData, null, (error, data) => {
return error ? reject(error) : resolve(getResults(data));
});
});
}
exports.OAuth2.prototype.getOAuthPasswordCredentials= function(username, password) {
const that = this;
return new Promise((resolve, reject) => {
const postData = 'grant_type=password&username=' + username + '&password=' + password;
const postHeaders= {
'Authorization': that.buildAuthHeader(),
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
};
that._request("POST", that._getAccessTokenUrl(), postHeaders, postData, null, (error, data) => {
return error ? reject(error) : resolve(getResults(data));
});
});
}
exports.OAuth2.prototype.get= function(url, accessToken) {
const that = this;
return new Promise((resolve, reject) => {
that._request("GET", url, {}, "", accessToken, (error, data) => {
return error ? reject(error) : resolve(data);
});
});
}