{"size": 1631, "ext": "js", "max_stars_repo_path": "lib/control/v1/authenticate.js", "max_stars_repo_name": "rapid7/warden", "max_stars_repo_stars_event_min_datetime": "2016-05-02T19:21:12.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-16T05:58:44.000Z", "max_issues_repo_path": "lib/control/v1/authenticate.js", "max_issues_repo_name": "rapid7/warden", "max_issues_repo_issues_event_min_datetime": "2016-04-12T19:16:10.000Z", "max_issues_repo_issues_event_max_datetime": "2017-08-21T20:40:42.000Z", "max_forks_repo_path": "lib/control/v1/authenticate.js", "max_forks_repo_name": "rapid7/warden", "max_forks_repo_forks_event_min_datetime": "2017-05-06T22:13:17.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-26T10:06:44.000Z"}
{"max_stars_count": 7, "max_issues_count": 70, "max_forks_count": 2, "avg_line_length": 26.737704918, "max_line_length": 76, "alphanum_fraction": 0.6431637032}
'use strict';

const validate = require('../validation/valid');
const signature = require('../validation/signature');
const content = require('../validation/content');
const fetch = require('../validation/fetch');
const token = require('../validation/token');
const reject = require('../validation/methodNotAllowed');
const bad = require('../validation/badRequest');

const bodyParser = require('body-parser');

const HTTP_OK = 200;
const BAD_REQUEST = 400;

/**
 * Authenticate middleware
 * @param {Express} app
 * @param {Server} server
 * @constructor
 */
function Authenticate(app, server) {
  app.use(bodyParser.json());

  app.post('/v1/authenticate', (req, res, next) => {
    Log.log('DEBUG', 'authenticate request received');
    if (!Config.get('vault:token')) {
      return bad.request(res, ['Vault is sealed! Use the /v1/unseal API.']);
    }
    next();
  },
  validate.request,
  (req, res, next) => {
    signature.signatureValidate(req, res, next, server);
  },
  content.document,
  fetch.metadata,
  (req, res, next) => {
    token.create(req, res, next, Config.get('vault'));
  },
  (req, res, next) => { // eslint-disable-line no-unused-vars
    Log.log('DEBUG', 'Sending token data');
    res.status(HTTP_OK);
    res.send(req.auth);
  },
  (err, req, res, next) => { // eslint-disable-line no-unused-vars
    res.status(BAD_REQUEST);
    res.json({
      code: BAD_REQUEST,
      error: err,
      stack: err.stack,
      message: err.message
    });
  });

  // Reject anything else e.g. DELETE, TRACE, etc.
  app.all('/v1/authenticate', reject.methodNotAllowed('POST'));
}

exports.attach = Authenticate;
