-
-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathclient-credentials-grant-type.js
More file actions
94 lines (72 loc) · 2.31 KB
/
client-credentials-grant-type.js
File metadata and controls
94 lines (72 loc) · 2.31 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
94
'use strict';
/**
* Module dependencies.
*/
const AbstractGrantType = require('./abstract-grant-type');
const InvalidArgumentError = require('../errors/invalid-argument-error');
const InvalidGrantError = require('../errors/invalid-grant-error');
/**
* Constructor.
*/
class ClientCredentialsGrantType extends AbstractGrantType {
constructor(options = {}) {
if (!options.model) {
throw new InvalidArgumentError('Missing parameter: `model`');
}
if (!options.model.getUserFromClient) {
throw new InvalidArgumentError('Invalid argument: model does not implement `getUserFromClient()`');
}
if (!options.model.saveToken) {
throw new InvalidArgumentError('Invalid argument: model does not implement `saveToken()`');
}
super(options);
}
/**
* Handle client credentials grant.
*
* @see https://tools.ietf.org/html/rfc6749#section-4.4.2
*/
async handle(request, client) {
if (!request) {
throw new InvalidArgumentError('Missing parameter: `request`');
}
if (!client) {
throw new InvalidArgumentError('Missing parameter: `client`');
}
const scope = this.getScope(request);
const user = await this.getUserFromClient(client);
return this.saveToken(user, client, scope);
}
/**
* Retrieve the user using client credentials.
*/
async getUserFromClient(client) {
const user = await this.model.getUserFromClient(client);
if (!user) {
throw new InvalidGrantError('Invalid grant: user credentials are invalid');
}
return user;
}
/**
* Save token.
*/
async saveToken(user, client, requestedScope) {
const validatedScope = await this.validateScope(user, client, requestedScope);
const accessToken = await this.generateAccessToken(client, user, validatedScope);
const refreshToken = await this.generateRefreshToken(client, user, validatedScope);
const accessTokenExpiresAt = await this.getAccessTokenExpiresAt(client, user, validatedScope);
const refreshTokenExpiresAt = await this.getRefreshTokenExpiresAt();
const token = {
accessToken,
accessTokenExpiresAt,
refreshToken,
refreshTokenExpiresAt,
scope: validatedScope,
};
return this.model.saveToken(token, client, user);
}
}
/**
* Export constructor.
*/
module.exports = ClientCredentialsGrantType;