forked from node-oauth/node-oauth2-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauthorize-handler.js
395 lines (304 loc) · 10.8 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
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
'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 Request = require('../request');
const Response = require('../response');
const ServerError = require('../errors/server-error');
const UnauthorizedClientError = require('../errors/unauthorized-client-error');
const isFormat = require('@node-oauth/formats');
const tokenUtil = require('../utils/token-util');
const url = require('url');
const pkce = require('../pkce/pkce');
const { parseScope } = require('../utils/scope-util');
/**
* Response types.
*/
const responseTypes = {
code: require('../response-types/code-response-type'),
//token: require('../response-types/token-response-type')
};
/**
* Constructor.
*/
class AuthorizeHandler {
constructor (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.
*/
async handle (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');
}
const expiresAt = await this.getAuthorizationCodeLifetime();
const client = await this.getClient(request);
const user = await this.getUser(request, response);
let uri;
let state;
try {
uri = this.getRedirectUri(request, client);
state = this.getState(request);
if (request.query.allowed === 'false' || request.body.allowed === 'false') {
throw new AccessDeniedError('Access denied: user denied access to application');
}
const requestedScope = await this.getScope(request);
const validScope = await this.validateScope(user, client, requestedScope);
const authorizationCode = await this.generateAuthorizationCode(client, user, validScope);
const ResponseType = this.getResponseType(request);
const codeChallenge = this.getCodeChallenge(request);
const codeChallengeMethod = this.getCodeChallengeMethod(request);
const code = await this.saveAuthorizationCode(
authorizationCode,
expiresAt,
validScope,
client,
uri,
user,
codeChallenge,
codeChallengeMethod
);
const responseTypeInstance = new ResponseType(code.authorizationCode);
const redirectUri = this.buildSuccessRedirectUri(uri, responseTypeInstance);
this.updateResponse(response, redirectUri, state);
return code;
} catch (err) {
let e = err;
if (!(e instanceof OAuthError)) {
e = new ServerError(e);
}
const redirectUri = this.buildErrorRedirectUri(uri, e);
this.updateResponse(response, redirectUri, state);
throw e;
}
}
/**
* Generate authorization code.
*/
async generateAuthorizationCode (client, user, scope) {
if (this.model.generateAuthorizationCode) {
return this.model.generateAuthorizationCode(client, user, scope);
}
return tokenUtil.generateRandomToken();
}
/**
* Get authorization code lifetime.
*/
getAuthorizationCodeLifetime () {
const expires = new Date();
expires.setSeconds(expires.getSeconds() + this.authorizationCodeLifetime);
return expires;
}
/**
* Get the client from the model.
*/
async getClient (request) {
const self = this;
const clientId = request.body.client_id || request.query.client_id;
if (!clientId) {
throw new InvalidRequestError('Missing parameter: `client_id`');
}
if (!isFormat.vschar(clientId)) {
throw new InvalidRequestError('Invalid parameter: `client_id`');
}
const redirectUri = request.body.redirect_uri || request.query.redirect_uri;
if (redirectUri && !isFormat.uri(redirectUri)) {
throw new InvalidRequestError('Invalid request: `redirect_uri` is not a valid URI');
}
const client = await this.model.getClient(clientId, null);
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) {
const valid = await self.validateRedirectUri(redirectUri, client);
if (!valid) {
throw new InvalidClientError('Invalid client: `redirect_uri` does not match client value');
}
}
return client;
}
/**
* Validate requested scope.
*/
async validateScope (user, client, scope) {
if (this.model.validateScope) {
const validatedScope = await this.model.validateScope(user, client, scope);
if (!validatedScope) {
throw new InvalidScopeError('Invalid scope: Requested scope is invalid');
}
return validatedScope;
}
return scope;
}
/**
* Get scope from the request.
*/
getScope (request) {
const scope = request.body.scope || request.query.scope;
return parseScope(scope);
}
/**
* Get state from the request.
*/
getState (request) {
const state = request.body.state || request.query.state;
const stateExists = state && state.length > 0;
const stateIsValid = stateExists
? isFormat.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.
*/
async getUser (request, response) {
if (this.authenticateHandler instanceof AuthenticateHandler) {
const handled = await this.authenticateHandler.handle(request, response);
return handled
? handled.user
: undefined;
}
const user = await this.authenticateHandler.handle(request, response);
if (!user) {
throw new ServerError('Server error: `handle()` did not return a `user` object');
}
return user;
}
/**
* Get redirect URI.
*/
getRedirectUri (request, client) {
return request.body.redirect_uri || request.query.redirect_uri || client.redirectUris[0];
}
/**
* Save authorization code.
*/
async saveAuthorizationCode (authorizationCode, expiresAt, scope, client, redirectUri, user, codeChallenge, codeChallengeMethod) {
let code = {
authorizationCode: authorizationCode,
expiresAt: expiresAt,
redirectUri: redirectUri,
scope: scope
};
if(codeChallenge && codeChallengeMethod){
code = Object.assign({
codeChallenge: codeChallenge,
codeChallengeMethod: codeChallengeMethod
}, code);
}
return this.model.saveAuthorizationCode(code, client, user);
}
async validateRedirectUri (redirectUri, client) {
if (this.model.validateRedirectUri) {
return this.model.validateRedirectUri(redirectUri, client);
}
return client.redirectUris.includes(redirectUri);
}
/**
* Get response type.
*/
getResponseType (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.
*/
buildSuccessRedirectUri (redirectUri, responseType) {
return responseType.buildRedirectUri(redirectUri);
}
/**
* Build an error response that redirects the user-agent to the client-provided url.
*/
buildErrorRedirectUri (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.
*/
updateResponse (response, redirectUri, state) {
redirectUri.query = redirectUri.query || {};
if (state) {
redirectUri.query.state = state;
}
response.redirect(url.format(redirectUri));
}
getCodeChallenge (request) {
return request.body.code_challenge || request.query.code_challenge;
}
/**
* Get code challenge method from request or defaults to plain.
* https://www.rfc-editor.org/rfc/rfc7636#section-4.3
*
* @throws {InvalidRequestError} if request contains unsupported code_challenge_method
* (see https://www.rfc-editor.org/rfc/rfc7636#section-4.4)
*/
getCodeChallengeMethod (request) {
const algorithm = request.body.code_challenge_method || request.query.code_challenge_method;
if (algorithm && !pkce.isValidMethod(algorithm)) {
throw new InvalidRequestError(`Invalid request: transform algorithm '${algorithm}' not supported`);
}
return algorithm || 'plain';
}
}
/**
* Export constructor.
*/
module.exports = AuthorizeHandler;