UNPKG

2.83 kBJavaScriptView Raw
1'use strict';
2
3const Hoek = require('@hapi/hoek');
4const GrantParams = require('../grant-params');
5const { parseToken } = require('./token-parser');
6
7const ACCESS_TOKEN_PROPERTY_NAME = 'access_token';
8const REFRESH_TOKEN_PROPERTY_NAME = 'refresh_token';
9
10module.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 * Determines if the current access token has already expired or if it is about to expire
26 *
27 * @param {Number} expirationWindowSeconds Window of time before the actual expiration to refresh the token
28 * @returns {Boolean}
29 */
30 expired(expirationWindowSeconds = 0) {
31 return this.token.expires_at - (Date.now() + expirationWindowSeconds * 1000) <= 0;
32 }
33
34 /**
35 * Refreshes the current access token
36 *
37 * @param {Object} params Optional argument for additional API request params.
38 * @param {String|Array<String>} [params.scope] String or array of strings representing the application privileges
39 * @returns {Promise<AccessToken>}
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 * Revokes either the access or refresh token depending on the {tokenType} value
55 *
56 * @param {String} tokenType A string containing the type of token to revoke (access_token or refresh_token)
57 * @returns {Promise}
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 * Revokes both the current access and refresh tokens
75 *
76 * @returns {Promise}
77 */
78 async revokeAll() {
79 await this.revoke(ACCESS_TOKEN_PROPERTY_NAME);
80 await this.revoke(REFRESH_TOKEN_PROPERTY_NAME);
81 }
82
83 /**
84 * Get the access token's internal JSON representation
85 *
86 * @returns {String}
87 */
88 toJSON() {
89 return this.token;
90 }
91};