<commit_before>'use strict';

const User = require('../model/user.js');

module.exports = (req, res, next) => {
  const {authorization} = req.headers;
  // console.log('header', authorization);
  if(!authorization)
    return next(new Error('unauthorized no authorization provided'));

  let encoded = authorization.split('Basic')[1];
  /* istanbul ignore next */
  if(!encoded)
    return next(new Error('unauthorized no basic auth provided'));

  let decoded = new Buffer(encoded, 'base64').toString();
  let [username, password] = decoded.split(':');

  if(!username || !password)
    return next(new Error('unauthorized username or password was missing'));

  User.findOne({username})
    .then(user => {
    /* istanbul ignore next */
      if(!user)
        return next(new Error('unauthorized user does not exist'));
      return user.passwordHashCompare(password);
    })
    .then(user => {
      req.user = user;
      next();
    })
    .catch(() => {
      /* istanbul ignore next */
      next(new Error('unauthorized find one failed in basic auth middleware'));
    });
};<commit_msg>refactor basic auth middleware<commit_after>'use strict';

const User = require('../model/user');

module.exports = (req, res, next) => {
  const { authorization } = req.headers;

  // console.log('header', authorization);
  if (!authorization) return next(new Error('unauthorized no authorization provided'));

  const encoded = authorization.split('Basic')[1];

  /* istanbul ignore next */
  if (!encoded) return next(new Error('unauthorized no basic auth provided'));

  const decoded = new Buffer(encoded, 'base64').toString();
  const [username, password] = decoded.split(':');

  if (!username || !password) return next(new Error('unauthorized username or password was missing'));

  User.findOne({username})
    .then(user => user ? user.passwordHashCompare(password) : next(new Error('unauthorized user does not exist')))
    .then(user => {
      req.user = user;
      next();
    })
    /* istanbul ignore next */
    .catch(() => next(new Error('unauthorized find one failed in basic auth middleware')));
};
{'fraction_non_alphanumeric': 0.15722379603399433, 'fraction_numerical': 0.0028328611898017, 'mean_word_length': 3.804988662131519, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '333016', 'n_tokens_mistral': 608, 'n_tokens_neox': 584, 'n_words': 173}