forked from af83/oauth2_server_node
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
398 lines (351 loc) · 13.1 KB
/
server.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
/*
* This implements a OAuth2 server methods, as specified at:
* http://tools.ietf.org/html/draft-ietf-oauth-v2-10
*
* Only features the "web server" schema:
* http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-1.4.1
*
* Terminology:
* http://tools.ietf.org/html/draft-ietf-oauth-v2-10#section-1.2
*
*/
var util = require("util");
var url = require('url')
, querystring = require('querystring')
, serializer = require('serializer')
, randomString = serializer.randomString
, connectRoute = require('connect-route')
, oauth2 = require('./common')
;
function redirect(res, url) {
res.writeHead(303, {'Location': url});
res.end();
}
function server_error(res, err) {
res.writeHead(500, {'Content-Type': 'text/plain'});
if(typeof err == "string") res.end(err);
else {
res.write('An error has occurred: ' + err.message);
res.write('\n\n');
res.end(err.stack);
}
}
var SERVER = exports;
// To be set by connect middleware: SERVER.RFactory, SERVER.authentication
/* Render a particular error.
*
* Arguments:
* - res
* - type: the class of the error ('eua' or 'oat').
* - id: the id of the error (invalid_request, invalid_client...).
*/
SERVER.oauth_error = function(res, type, id) {
res.writeHead(400, {'Content-Type': 'text/plain'});
res.end(JSON.stringify({error: {
type: 'OAuthException',
message: id + ': ' + oauth2.ERRORS[type][id],
}}));
};
/**
* To call when an unknown error happens (server error).
*/
var unknown_error = exports.unknown_error = function(res, err) {
server_error(res, err);
};
// Parameters we must/can have in different kinds of requests:
var PARAMS = exports.PARAMS = {
eua: { // eua = end user authorization
mandatory: ['client_id', 'response_type'],
optional: ['state', 'scope', 'redirect_uri'],
// possible values for response_type param:
response_types: {'token': 1, 'code': 1, 'code_and_token': 1},
},
oat: { // oat = Obtaining an access token
mandatory: ['grant_type', 'client_id', 'code', 'redirect_uri'],
// client_secret might be provided with the 'Authorization: Basic ...' header
optional: ['scope', 'client_secret'],
},
};
PARAMS.eua.all = PARAMS.eua.mandatory.concat(PARAMS.eua.optional);
/**
* Create a grant and send it to the user.
* The code sent is of the form: grand.id + '.' + grant.code
*
* Arguments:
* - req
* - res
* - Grant:
* - user_id: id of the user
* - client_data: hash, data about the client:
* - client_id
* - redirect_uri
* - state: str, optional, if given, will be sent with the grant.
* - additional_info: optional hash, anything you want to be stored with
* the grant.
*
*/
exports.send_grant = function(res, Grant, user_id, client_data, additional_info) {
console.log("======>send grant");
var grant = new Grant({
client_id: client_data.client_id,
time: Date.now(),
user_id: user_id,
code: randomString(128),
redirect_uri: client_data.redirect_uri
});
if(additional_info) grant.set('additional_info', additional_info);
grant.save(function(err, result) {
if (err) return console.error(err);
var qs = {code: grant.get('id') + '.' + grant.get('code')};
if(client_data.state) qs.state = client_data.state;
qs = querystring.stringify(qs);
redirect(res, client_data.redirect_uri + '?' + qs);
});
};
/**
* Valid the grant, call callback(err, token|null)
* token being a JSON object.
* If valid, the grant is invalidated and cannot be used anymore.
*
* To be valid, a grant must exist, not be deprecated and have the right
* associated client.
*
* Arguments:
* - Grant: Grant instance
* - data:
* - code: grant code given by client.
* - client_id: the client id giving the grant
* - redirect_uri: the redirect_uri given with the grant
* - callback: to be called with a token if the grant was valid,
* or null otherwise.
*
*/
SERVER.valid_grant = function(Grant, data, callback) {
console.log("======>valid_grant:"+data.code);
var id_code = data.code.split('.');
if(id_code.length != 2) return callback(null);
Grant.getById(id_code[0], function(err, grant) {
if (err) return callback(err);
// var minute_ago = Date.now() - 60000;
//console.log("client_id="+grant.get('client_id'));
//console.log("data="+data.client_id);
if(!grant
//|| grant.get('time') < minute_ago
||grant.get('client_id') != data.client_id
// || grant.get('code') != id_code[1]
// ||grant.get('redirect_uri') != data.redirect_uri
) return callback('error in grant');
var additional_info = grant.get('additional_info');
// Delete the grant so that it cannot be used anymore:
grant.remove(function(err, result) {
if (err) return callback(err);
// Generate and send an access_token to the client:
var token = {
access_token: oauth2.create_access_token(grant.get('user_id'), grant.get('client_id'),
additional_info)
// optional: expires_in, refresh_token, scope
};
callback(null, token);
});
});
};
SERVER.get_new_access_token = function(res, username, client_id, client_data){
var access_token = oauth2.create_access_token(username, client_id, "");
// optional: expires_in, refresh_token, scope
//redirect(res, client_data.redirect_uri + '?access_token=' + access_token+'&user=' + user.get('io_username')+'&uuid=' + user.get('io_uuid'));
// FIXED added to return token so it can be stored by auth server
return access_token;
}
/**
* OAuth2 token endpoint.
* Check the authorization_code, uri_redirect and client secret, issue a token.
*
* POST to config.oauth2.token_url
*
* Arguments:
* - req
* - res
*
*/
var token_endpoint = exports.token_endpoint = function(req, res) {
if(!req.body) return SERVER.oauth_error(res, 'oat', 'invalid_request');
var params = req.body;
// We check there is no invalid_requet error:
var error = false;
params && PARAMS.oat.mandatory.forEach(function(param) {
if(!params[param]) error = true;
});
if(error) return SERVER.oauth_error(res, 'oat', 'invalid_request');
// We do only support 'authorization_code' as grant_type:
if(params.grant_type != 'authorization_code')
return SERVER.oauth_error(res, 'oat', 'unsupported_grant_type');
// Check the client_secret is given once (and only once),
// either by HTTP basic auth, or by client_secret parameter:
var secret = req.headers['authorization'];
if(secret) {
if(params.client_secret)
return SERVER.oauth_error(res, 'oat', 'invalid_request');
params.client_secret = secret.slice(6); // remove the leading 'Basic'
}
else if(!params.client_secret) {
return SERVER.oauth_error(res, 'oat', 'invalid_request');
}
var model = SERVER.Model
, Client = model.Client
, Grant = model.Grant;
// Check the client_id exists and does have correct client_secret:
Client.getById(params.client_id, function(err, client) {
// console.log("params:"+util.inspect(params, false, 1));
if (err) return unknown_error(res, err);
if(!client || client.get('secret') != params.client_secret)
return SERVER.oauth_error(res, 'oat', 'invalid_client');
var data = {code: params.code,
client_id: client.get('clientId'),
redirect_uri: params.redirect_uri};
SERVER.valid_grant(Grant, data, function(err, token) {
if (err) return unknown_error(res, err);
if (!token) return SERVER.oauth_error(res, 'oat', 'invalid_grant');
res.writeHead(200, { 'Content-Type': 'application/json'
, 'Cache-Control': 'no-store'
});
res.end(JSON.stringify(token));
});
});
};
/* OAuth2 Authorize function.
* Serve an authentication form to the end user at browser.
*
* This function should only be called by oauth2.authorize
*
* Arguments:
* - params:
* - req
* - res
*
*/
SERVER.authorize = function(params, req, res) {
// We check there is no invalid_requet error:
var error = false;
PARAMS.eua.mandatory.forEach(function(param) {
if(!params[param]) error = true;
});
if(error) return SERVER.oauth_error(res, 'eua', 'invalid_request');
if(!PARAMS.eua.response_types[params.response_type])
return SERVER.oauth_error(res, 'eua', 'unsupported_response_type');
// XXX: For now, we only support 'code' response type
// which is used in case of a web server (Section 1.4.1 in oauth2 spec draft 10)
// TODO: make it more compliant with the specs
if(params.response_type != "code" && params.response_type != "token" ) {
res.writeHead(501, {'Content-Type': 'text/plain'});
res.end('Only code and token request type supported for now ' +
'(schema 1.4.1 in oauth2 spec draft 10).');
return;
}
var Client = SERVER.Model.Client;
Client.getById(params.client_id, function(err, client) {
if (err) return unknown_error(res, err);
if(!client) return SERVER.oauth_error(res, 'eua', 'invalid_client');
// Check the redirect_uri is the one we know about (if we do):
var clientRedirectUri = client.get('redirectUri');
if(!params.redirect_uri) {
return SERVER.oauth_error(res, 'eua', 'redirect_uri_mismatch');
}
var params_redirect_uri = params.redirect_uri.replace(/^http{1}s{0,1}:{1}/, '');
if( clientRedirectUri && params_redirect_uri
&& (clientRedirectUri == params_redirect_uri || clientRedirectUri == params.redirect_uri)) {
//continue
}
// when the x-forwarded-for contains 127.0.0.1 we allow as its just local port forwarding access
else if(/127.0.0.1/.test(req.headers['x-forwarded-for'])) {
//continue
}
else {
return SERVER.oauth_error(res, 'eua', 'redirect_uri_mismatch');
}
// Eveything is allright, ask the user to sign in.
if(params.lang && req.session) {
req.session.lang = params.lang;
}
SERVER.authentication.login(req, res, {
client_id: client.get('clientId'),
client_name: client.get('name'),
redirect_uri: params_redirect_uri,
state: params.state,
response_type: params.response_type,
username: params.username,
logout_uri: params.logout_uri
});
});
};
/**
* OAuth2 Authorize end-point.
* Serve an authentication form to the end user at browser.
*
* GET or POST on config.oauth2.authorize_url
*
* Arguments:
* - req
* - res
*
*/
SERVER.authorize_endpoint = function(req, res) {
if (req.method == 'GET') {
var params = url.parse(req.url, true).query;
return SERVER.authorize(params, req, res);
} else {
if(!req.body) return SERVER.oauth_error(res, 'eua', 'invalid_request');
SERVER.authorize(req.body, req, res);
}
};
/* Returns Oauth2 server connect middleware.
*
* This middleware will intercept requests aiming at OAuth2 server
* and treat them.
*
* Arguments:
* - config, hash containing:
* - authorize_url: end-user authorization endpoint,
* the URL the end-user must be redirected to to be served the
* authentication form.
* - token_url: OAuth2 token endpoint,
* the URL the client will use to check the authorization_code given by
* user and get a token.
* - crypt_key: string, encryption key used to crypt information contained
* in the issued tokens. This is a symmetric key and must be kept secret.
* - sign_key: string, signature key used to sign issued tokens.
* This is a symmetric key and must be kept secret.
* - RFactory: RFactory object initialized whith minimal schema info
* (Grant and Client objects). cf. README file for more info.
* - authentication: module (or object) defining the following functions:
* * login: function to render the login page to end user in browser.
* * process_login: to process the credentials given by user.
* This function should use the send_grant function once user is
* authenticated.
*
*/
exports.connector = function(config, Model, authentication, forget_password) {
var sserializer = serializer.createSecureSerializer(config.crypt_key, config.sign_key);
oauth2.set_serializer(sserializer);
SERVER.Model = Model;
SERVER.authentication = authentication;
console.log(util.inspect(config, false, 1));
return connectRoute(function(router) {
router.get(config.authorize_url, SERVER.authorize_endpoint);
router.post(config.authorize_url, SERVER.authorize_endpoint);
router.post(config.process_login_url, authentication.process_login);
router.post(config.token_url, authentication.request_token);
router.get(config.failure_url, authentication.failed_login);
router.get(config.process_logout_url, authentication.logout);
router.post(config.process_forget_url, forget_password.process_forget);
router.get(config.reset_password_url, forget_password.reset_password);
router.post(config.process_reset_password_url, forget_password.process_reset_password);
router.post(config.regist_new_user_url, forget_password.regist_new_user);
router.get(config.authorize_new_user_url, forget_password.authorize_new_user);
});
};
var common = require('./common');
exports.set_serializer = common.set_serializer;
exports.ERRORS = common.ERRORS;
exports.create_access_token = common.create_access_token;
exports.token_info = common.token_info;
exports.check_token = common.check_token;