-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathauthorize-handler.js
355 lines (279 loc) · 9.96 KB
/
authorize-handler.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
'use strict';
/**
* Module dependencies.
*/
const AccessDeniedError = require('../errors/access-denied-error');
const AuthenticateHandler = require('../handlers/authenticate-handler');
const InvalidArgumentError = require('../errors/invalid-argument-error');
const InvalidClientError = require('../errors/invalid-client-error');
const InvalidRequestError = require('../errors/invalid-request-error');
const InvalidScopeError = require('../errors/invalid-scope-error');
const UnsupportedResponseTypeError = require('../errors/unsupported-response-type-error');
const OAuthError = require('../errors/oauth-error');
const Promise = require('bluebird');
const promisify = require('promisify-any').use(Promise);
const Request = require('../request');
const Response = require('../response');
const ServerError = require('../errors/server-error');
const UnauthorizedClientError = require('../errors/unauthorized-client-error');
const is = require('../validator/is');
const tokenUtil = require('../utils/token-util');
const url = require('url');
/**
* Response types.
*/
const responseTypes = {
code: require('../response-types/code-response-type'),
//token: require('../response-types/token-response-type')
};
/**
* Constructor.
*/
function AuthorizeHandler(options) {
options = options || {};
if (options.authenticateHandler && !options.authenticateHandler.handle) {
throw new InvalidArgumentError('Invalid argument: authenticateHandler does not implement `handle()`');
}
if (!options.authorizationCodeLifetime) {
throw new InvalidArgumentError('Missing parameter: `authorizationCodeLifetime`');
}
if (!options.model) {
throw new InvalidArgumentError('Missing parameter: `model`');
}
if (!options.model.getClient) {
throw new InvalidArgumentError('Invalid argument: model does not implement `getClient()`');
}
if (!options.model.saveAuthorizationCode) {
throw new InvalidArgumentError('Invalid argument: model does not implement `saveAuthorizationCode()`');
}
this.allowEmptyState = options.allowEmptyState;
this.authenticateHandler = options.authenticateHandler || new AuthenticateHandler(options);
this.authorizationCodeLifetime = options.authorizationCodeLifetime;
this.model = options.model;
}
/**
* Authorize Handler.
*/
AuthorizeHandler.prototype.handle = function(request, response) {
if (!(request instanceof Request)) {
throw new InvalidArgumentError('Invalid argument: `request` must be an instance of Request');
}
if (!(response instanceof Response)) {
throw new InvalidArgumentError('Invalid argument: `response` must be an instance of Response');
}
if ('false' === request.query.allowed) {
return Promise.reject(new AccessDeniedError('Access denied: user denied access to application'));
}
const fns = [
this.getAuthorizationCodeLifetime(),
this.getClient(request),
this.getUser(request, response)
];
return Promise.all(fns)
.bind(this)
.spread(function(expiresAt, client, user) {
const uri = this.getRedirectUri(request, client);
let scope;
let state;
let ResponseType;
return Promise.bind(this)
.then(function() {
const requestedScope = this.getScope(request);
return this.validateScope(user, client, requestedScope);
})
.then(function(validScope) {
scope = validScope;
return this.generateAuthorizationCode(client, user, scope);
})
.then(function(authorizationCode) {
state = this.getState(request);
ResponseType = this.getResponseType(request);
return this.saveAuthorizationCode(authorizationCode, expiresAt, scope, client, uri, user);
})
.then(function(code) {
const responseType = new ResponseType(code.authorizationCode);
const redirectUri = this.buildSuccessRedirectUri(uri, responseType);
this.updateResponse(response, redirectUri, state);
return code;
})
.catch(function(e) {
if (!(e instanceof OAuthError)) {
e = new ServerError(e);
}
const redirectUri = this.buildErrorRedirectUri(uri, e);
this.updateResponse(response, redirectUri, state);
throw e;
});
});
};
/**
* Generate authorization code.
*/
AuthorizeHandler.prototype.generateAuthorizationCode = function(client, user, scope) {
if (this.model.generateAuthorizationCode) {
return promisify(this.model.generateAuthorizationCode, 3).call(this.model, client, user, scope);
}
return tokenUtil.generateRandomToken();
};
/**
* Get authorization code lifetime.
*/
AuthorizeHandler.prototype.getAuthorizationCodeLifetime = function() {
const expires = new Date();
expires.setSeconds(expires.getSeconds() + this.authorizationCodeLifetime);
return expires;
};
/**
* Get the client from the model.
*/
AuthorizeHandler.prototype.getClient = function(request) {
const clientId = request.body.client_id || request.query.client_id;
if (!clientId) {
throw new InvalidRequestError('Missing parameter: `client_id`');
}
if (!is.vschar(clientId)) {
throw new InvalidRequestError('Invalid parameter: `client_id`');
}
const redirectUri = request.body.redirect_uri || request.query.redirect_uri;
if (redirectUri && !is.uri(redirectUri)) {
throw new InvalidRequestError('Invalid request: `redirect_uri` is not a valid URI');
}
return promisify(this.model.getClient, 2).call(this.model, clientId, null)
.then(function(client) {
if (!client) {
throw new InvalidClientError('Invalid client: client credentials are invalid');
}
if (!client.grants) {
throw new InvalidClientError('Invalid client: missing client `grants`');
}
if (!Array.isArray(client.grants) || !client.grants.includes('authorization_code')) {
throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid');
}
if (!client.redirectUris || 0 === client.redirectUris.length) {
throw new InvalidClientError('Invalid client: missing client `redirectUri`');
}
if (redirectUri && !client.redirectUris.includes(redirectUri)) {
throw new InvalidClientError('Invalid client: `redirect_uri` does not match client value');
}
return client;
});
};
/**
* Validate requested scope.
*/
AuthorizeHandler.prototype.validateScope = function(user, client, scope) {
if (this.model.validateScope) {
return promisify(this.model.validateScope, 3).call(this.model, user, client, scope)
.then(function (scope) {
if (!scope) {
throw new InvalidScopeError('Invalid scope: Requested scope is invalid');
}
return scope;
});
} else {
return Promise.resolve(scope);
}
};
/**
* Get scope from the request.
*/
AuthorizeHandler.prototype.getScope = function(request) {
const scope = request.body.scope || request.query.scope;
if (!is.nqschar(scope)) {
throw new InvalidScopeError('Invalid parameter: `scope`');
}
return scope;
};
/**
* Get state from the request.
*/
AuthorizeHandler.prototype.getState = function(request) {
const state = request.body.state || request.query.state;
const stateExists = state && state.length > 0;
const stateIsValid = stateExists
? is.vschar(state)
: this.allowEmptyState;
if (!stateIsValid) {
const message = (!stateExists) ? 'Missing' : 'Invalid';
throw new InvalidRequestError(`${message} parameter: \`state\``);
}
return state;
};
/**
* Get user by calling the authenticate middleware.
*/
AuthorizeHandler.prototype.getUser = function(request, response) {
if (this.authenticateHandler instanceof AuthenticateHandler) {
return this.authenticateHandler.handle(request, response).get('user');
}
return promisify(this.authenticateHandler.handle, 2)(request, response).then(function(user) {
if (!user) {
throw new ServerError('Server error: `handle()` did not return a `user` object');
}
return user;
});
};
/**
* Get redirect URI.
*/
AuthorizeHandler.prototype.getRedirectUri = function(request, client) {
return request.body.redirect_uri || request.query.redirect_uri || client.redirectUris[0];
};
/**
* Save authorization code.
*/
AuthorizeHandler.prototype.saveAuthorizationCode = function(authorizationCode, expiresAt, scope, client, redirectUri, user) {
const code = {
authorizationCode: authorizationCode,
expiresAt: expiresAt,
redirectUri: redirectUri,
scope: scope
};
return promisify(this.model.saveAuthorizationCode, 3).call(this.model, code, client, user);
};
/**
* Get response type.
*/
AuthorizeHandler.prototype.getResponseType = function(request) {
const responseType = request.body.response_type || request.query.response_type;
if (!responseType) {
throw new InvalidRequestError('Missing parameter: `response_type`');
}
if (!Object.prototype.hasOwnProperty.call(responseTypes, responseType)) {
throw new UnsupportedResponseTypeError('Unsupported response type: `response_type` is not supported');
}
return responseTypes[responseType];
};
/**
* Build a successful response that redirects the user-agent to the client-provided url.
*/
AuthorizeHandler.prototype.buildSuccessRedirectUri = function(redirectUri, responseType) {
return responseType.buildRedirectUri(redirectUri);
};
/**
* Build an error response that redirects the user-agent to the client-provided url.
*/
AuthorizeHandler.prototype.buildErrorRedirectUri = function(redirectUri, error) {
const uri = url.parse(redirectUri);
uri.query = {
error: error.name
};
if (error.message) {
uri.query.error_description = error.message;
}
return uri;
};
/**
* Update response with the redirect uri and the state parameter, if available.
*/
AuthorizeHandler.prototype.updateResponse = function(response, redirectUri, state) {
redirectUri.query = redirectUri.query || {};
if (state) {
redirectUri.query.state = state;
}
response.redirect(url.format(redirectUri));
};
/**
* Export constructor.
*/
module.exports = AuthorizeHandler;