1 | 'use strict';
|
2 |
|
3 | const Hoek = require('@hapi/hoek');
|
4 | const GrantParams = require('../grant-params');
|
5 | const { parseToken } = require('./token-parser');
|
6 |
|
7 | const ACCESS_TOKEN_PROPERTY_NAME = 'access_token';
|
8 | const REFRESH_TOKEN_PROPERTY_NAME = 'refresh_token';
|
9 |
|
10 | module.exports = class AccessToken {
|
11 | #config = null;
|
12 | #client = null;
|
13 |
|
14 | constructor(config, client, token) {
|
15 | Hoek.assert(config, 'Cannot create access token without client configuration');
|
16 | Hoek.assert(client, 'Cannot create access token without client instance');
|
17 | Hoek.assert(token, 'Cannot create access token without a token to parse');
|
18 |
|
19 | this.#config = config;
|
20 | this.#client = client;
|
21 | this.token = Object.freeze(parseToken(token));
|
22 | }
|
23 |
|
24 | |
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 | expired(expirationWindowSeconds = 0) {
|
31 | return this.token.expires_at - (Date.now() + expirationWindowSeconds * 1000) <= 0;
|
32 | }
|
33 |
|
34 | |
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | async refresh(params = {}) {
|
42 | const refreshParams = {
|
43 | ...params,
|
44 | refresh_token: this.token.refresh_token,
|
45 | };
|
46 |
|
47 | const parameters = GrantParams.forGrant(REFRESH_TOKEN_PROPERTY_NAME, this.#config.options, refreshParams);
|
48 | const response = await this.#client.request(this.#config.auth.tokenPath, parameters.toObject());
|
49 |
|
50 | return new AccessToken(this.#config, this.#client, response);
|
51 | }
|
52 |
|
53 | |
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 | async revoke(tokenType) {
|
60 | Hoek.assert(
|
61 | tokenType === ACCESS_TOKEN_PROPERTY_NAME || tokenType === REFRESH_TOKEN_PROPERTY_NAME,
|
62 | `Invalid token type. Only ${ACCESS_TOKEN_PROPERTY_NAME} or ${REFRESH_TOKEN_PROPERTY_NAME} are valid values`,
|
63 | );
|
64 |
|
65 | const options = {
|
66 | token: this.token[tokenType],
|
67 | token_type_hint: tokenType,
|
68 | };
|
69 |
|
70 | return this.#client.request(this.#config.auth.revokePath, options);
|
71 | }
|
72 |
|
73 | |
74 |
|
75 |
|
76 |
|
77 |
|
78 | async revokeAll() {
|
79 | await this.revoke(ACCESS_TOKEN_PROPERTY_NAME);
|
80 | await this.revoke(REFRESH_TOKEN_PROPERTY_NAME);
|
81 | }
|
82 |
|
83 | |
84 |
|
85 |
|
86 |
|
87 |
|
88 | toJSON() {
|
89 | return this.token;
|
90 | }
|
91 | };
|