All files / simple-oauth2/lib/client auth-code.js

100% Statements 16/16
100% Branches 1/1
100% Functions 3/3
100% Lines 16/16

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    6x 6x 6x 6x         6x 56x 56x                         8x         8x 8x   8x                       11x       11x 11x   11x     56x          
'use strict';
 
const { URL } = require('url');
const qs = require('querystring');
const coreModule = require('./../core');
const encoding = require('./../encoding');
 
/**
 * Authorization Code flow implementation
 */
module.exports = (config) => {
  const core = coreModule(config);
  const authorizeUrl = new URL(config.auth.authorizePath, config.auth.authorizeHost);
 
  /**
   * Redirect the user to the autorization page
   * @param {String} params.redirectURI A string that represents the registered application URI
   *                                     where the user is redirected after authentication
   * @param {String|Array<String>} params.scope A String or array of strings
   *                                     that represents the application privileges
   * @param {String} params.state A String that represents an option opaque value used by the client
   *                              to main the state between the request and the callback
   * @return {String} the absolute authorization url
   */
  function authorizeURL(params = {}) {
    const baseParams = {
      response_type: 'code',
      [config.client.idParamName]: config.client.id,
    };
 
    const scopeParams = encoding.getScopeParam(params.scope);
    const options = Object.assign(baseParams, params, scopeParams);
 
    return `${authorizeUrl}?${qs.stringify(options)}`;
  }
 
  /**
   * Returns the Access Token Object
   * @param {String} params.code Authorization code (from previous step)
   * @param {String} params.redirecURI A string that represents the callback uri
   * @param {String|Array<String>} params.scope A String or array of strings
   *                                     that represents the application privileges
   * @return {Promise}
   */
  async function getToken(params) {
    const baseParams = {
      grant_type: 'authorization_code',
    };
 
    const scopeParams = encoding.getScopeParam(params.scope);
    const options = Object.assign(baseParams, params, scopeParams);
 
    return core.request(config.auth.tokenPath, options);
  }
 
  return {
    authorizeURL,
    getToken,
  };
};