All files / simple-oauth2/lib/access-token index.js

100% Statements 17/17
100% Branches 2/2
100% Functions 7/7
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    1x 1x 1x         1x 23x       19x             3x               3x         3x   3x                 6x 6x         6x             2x 1x                   16x     23x        
'use strict';
 
const isAfter = require('date-fns/is_after');
const parseToken = require('./parse-token');
const coreModule = require('./../core');
 
/**
 * Wrapper for the Access Token Object
 */
module.exports = (config) => {
  const core = coreModule(config);
 
  class AccessToken {
    constructor(token) {
      this.token = parseToken(token);
    }
 
    /**
    * Check if the access token is expired or not
    */
    expired() {
      return isAfter(new Date(), this.token.expires_at);
    }
 
    /**
    * Refresh the access token
    * @param  {Object} params An optional argument for additional API request params.
    */
    async refresh(params) {
      const options = Object.assign({}, params, {
        grant_type: 'refresh_token',
        refresh_token: this.token.refresh_token,
      });
 
      const response = await core.request(config.auth.tokenPath, options);
 
      return new AccessToken(response);
    }
 
    /**
    * Revoke access or refresh token
    * @param  {String} tokenType A string containing the type of token to revoke.
    *                              Should be either "access_token" or "refresh_token"
    */
    async revoke(tokenType) {
      const token = tokenType === 'access_token' ? this.token.access_token : this.token.refresh_token;
      const options = {
        token,
        token_type_hint: tokenType,
      };
 
      return core.request(config.auth.revokePath, options);
    }
 
    /**
     * Revoke both the existing access and refresh tokens
    */
    async revokeAll() {
      await this.revoke('access_token');
      await this.revoke('refresh_token');
    }
  }
 
  /**
   * Creates an OAuth2.AccessToken instance
   * @param  {Object} token An object containing the token object returned from the OAuth2 server.
   * @returns {AccessToken}
   */
  function createAccessToken(token) {
    return new AccessToken(token);
  }
 
  return {
    create: createAccessToken,
  };
};