All files / simple-oauth2/lib core.js

100% Statements 28/28
100% Branches 6/6
100% Functions 2/2
100% Lines 28/28

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    1x 1x 1x 1x   1x       1x 92x         92x     23x 23x         23x 17x         17x   17x   6x   6x           23x 20x       20x 20x   3x       3x 3x     23x 23x   23x   20x     92x        
'use strict';
 
const Wreck = require('wreck');
const querystring = require('querystring');
const debug = require('debug')('simple-oauth2:index');
const encoding = require('./encoding');
 
const defaultHeaders = {
  Accept: 'application/json',
};
 
module.exports = (config) => {
  const httpOptions = Object.assign({}, config.http, {
    baseUrl: config.auth.tokenHost,
    headers: Object.assign({}, defaultHeaders, (config.http && config.http.headers)),
  });
 
  const wreck = Wreck.defaults(httpOptions);
 
  async function request(url, params) {
    let payload = params;
    const options = {
      json: true,
      headers: {},
    };
 
    if (config.options.authorizationMethod === 'header') {
      const basicHeader = encoding.getAuthorizationHeaderToken(
        config.client.id,
        config.client.secret
      );
 
      debug('Using header authentication. Authorization header set to %s', basicHeader);
 
      options.headers.Authorization = `Basic ${basicHeader}`;
    } else {
      debug('Using body authentication');
 
      payload = Object.assign({}, payload, {
        [config.client.idParamName]: config.client.id,
        [config.client.secretParamName]: config.client.secret,
      });
    }
 
    if (config.options.bodyFormat === 'form') {
      debug('Using form request format');
 
      // An example using `form` authorization params in the body is the
      // GitHub API.
      options.payload = querystring.stringify(payload);
      options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    } else {
      debug('Using json request format');
 
      // An example using `json` authorization params in the body is the
      // Amazon Developer Publishing API.
      options.payload = payload;
      options.headers['Content-Type'] = 'application/json';
    }
 
    debug('Creating request to: (POST) %s', url);
    debug('Using options: %j', options);
 
    const result = await wreck.post(url, options);
 
    return result.payload;
  }
 
  return {
    request,
  };
};