All files / middlewares auth.js

95% Statements 19/20
91.66% Branches 11/12
100% Functions 3/3
95% Lines 19/20

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    1x   1x   1x                                                     4x 7x 7x 2x   5x 5x 2x     3x       3x 1x       2x 1x 1x             1x       1x         1x        
'use strict';
 
const { Agent, ClientRequest, ServerResponse } = require('http');
 
const superagent = require('superagent');
 
const keepAliveAgent = new Agent({ keepAlive: true });
 
/**
 * @typedef {Object} FullTokenInfo
 * @property {string} token The access token.
 * @property {Object} info
 *   @property {string} info.userId
 *   @property {string} info.account
 *   @property {Object} info.roles <string, boolean> pairs.
 *   @property {string} info.name
 *   @property {string} info.clientId
 *   @property {string[]} info.scopes
 */
 
/**
 * Generate the Express authentication middleware.
 *
 * @param {string} authUri The authentication endpoint. For example
 *        `http://localhost:1080/auth/api/v1/auth/tokeninfo`.
 * @returns {function} The Express middleware.
 */
function authMiddleware(authUri) {
  /**
   * @param {ClientRequest} req
   * @param {ServerResponse} res
   * @param {function} next
   */
  return function (req, res, next) {
    let token = req.get('Authorization');
    if (!token) {
      return void res.status(400).json({ code: 'err_param', message: 'empty Authorization' });
    }
    token = token.trim();
    if (token.length < 8 || token.substr(0, 7).toLowerCase() !== 'bearer ') {
      return void res.status(400).json({ code: 'err_param', message: 'not bearer token' });
    }
 
    superagent
      .agent(keepAliveAgent)
      .auth(token.substr(7), { type: 'bearer' })
      .get(authUri, (err, authRes) => {
        if (!authRes) {
          return void res.status(503).json({
            code: 'err_rsc',
            message: `${err}`,
          });
        } else if (authRes.statusCode === 401) {
          return void res.status(401).json({ code: 'err_auth' });
        } else Iif (authRes.statusCode !== 200) {
          return void res.status(503).json({
            code: 'err_int_msg',
            message: `auth error with status code: ${res.statusCode}`,
          });
        }
 
        req[module.exports.TokenInfoKey] = {
          token: token.substr(7),
          info: authRes.body.data,
        };
        next();
      });
  };
}
 
module.exports = {
  TokenInfoKey: 'FullTokenInfo',
  authMiddleware,
};