|
2 | 2 | Extension Grants
|
3 | 3 | ==================
|
4 | 4 |
|
5 |
| -.. todo:: Describe how to implement extension grants. |
| 5 | +Create a subclass of ``AbstractGrantType`` and create methods `handle` and `saveToken` along with other required methods according to needs |
| 6 | + |
| 7 | +.. code-block:: js |
| 8 | +
|
| 9 | + const OAuth2Server = require('oauth2-server'); |
| 10 | + const AbstractGrantType = OAuth2Server.AbstractGrantType; |
| 11 | + const InvalidArgumentError = OAuth2Server.InvalidArgumentError; |
| 12 | + const InvalidRequestError = OAuth2Server.InvalidRequestError; |
| 13 | +
|
| 14 | + class MyCustomGrantType extends AbstractGrantType { |
| 15 | + constructor(opts) { |
| 16 | + super(opts); |
| 17 | + } |
| 18 | +
|
| 19 | + async handle(request, client) { |
| 20 | + if (!request) throw new InvalidArgumentError('Missing `request`'); |
| 21 | + if (!client) throw new InvalidArgumentError('Missing `client`'); |
| 22 | +
|
| 23 | + let scope = this.getScope(request); |
| 24 | + let user = await this.getUserBySomething(request); |
| 25 | +
|
| 26 | + return this.saveToken(user, client, scope); |
| 27 | + } |
| 28 | +
|
| 29 | + async saveToken(user, client, scope) { |
| 30 | + this.validateScope(user, client, scope); |
| 31 | +
|
| 32 | + let token = { |
| 33 | + accessToken: await this.generateAccessToken(client, user, scope), |
| 34 | + accessTokenExpiresAt: this.getAccessTokenExpiresAt(), |
| 35 | + refreshToken: await this.generateRefreshToken(client, user, scope), |
| 36 | + refreshTokenExpiresAt: this.getRefreshTokenExpiresAt(), |
| 37 | + scope: scope |
| 38 | + }; |
| 39 | +
|
| 40 | + return this.model.saveToken(token, client, user); |
| 41 | + } |
| 42 | +
|
| 43 | + async getUserBySomething(request) { |
| 44 | + //Get user's data by corresponding data (FB User ID, Google, etc.), etc. |
| 45 | + } |
| 46 | + } |
| 47 | +
|
| 48 | + module.exports = MyCustomGrantType; |
6 | 49 |
|
7 | 50 | Extension grants are registered through :ref:`OAuth2Server#token() <OAuth2Server#token>` (``options.extendedGrantTypes``).
|
8 | 51 |
|
| 52 | +This might require you to approve the new ``grant_type`` for a particular ``client`` if you do checks on valid grant types. |
0 commit comments