<commit_before>'use strict';

const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const debug = require('debug')('gateway:oauth2');

function createOauth2Middleware(params) {
  let jwtOptions = {
    jwtFromRequest: ExtractJwt.fromAuthHeader(),
    issuer: params.issuer,
    audience: params.audience,
    secretOrKey: params.key,
    algorithms: params.algorithms
  };

  passport.use(new JwtStrategy(jwtOptions, (jwt, done) => {
    done(null, jwt);
  }));
  return function oauth2Middleware(req, res, next) {
    debug('authenticating with JWT token');
    passport.authenticate('jwt', (err, user, info) => {
      if (err) {
        return next(err);
      }
      if (!user) {
        debug(`authentication failed: ${info.message}`);
        res.status(401).send(`Unauthorized (${info.message})`);
        return;
      }
      return next();
    })(req, res, next);
  };
}

module.exports = {
  oauth2: createOauth2Middleware
};
<commit_msg>JSON formatting for auth errors<commit_after>'use strict';

const passport = require('passport');
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const debug = require('debug')('gateway:oauth2');

function createOauth2Middleware(params) {
  let jwtOptions = {
    jwtFromRequest: ExtractJwt.fromAuthHeader(),
    issuer: params.issuer,
    audience: params.audience,
    secretOrKey: params.key,
    algorithms: params.algorithms
  };

  passport.use(new JwtStrategy(jwtOptions, (jwt, done) => {
    done(null, jwt);
  }));
  return function oauth2Middleware(req, res, next) {
    debug('authenticating with JWT token');
    passport.authenticate('jwt', (err, user, info) => {
      if (err) {
        return next(err);
      }
      if (!user) {
        debug(`authentication failed: ${info.message}`);
        res.status(401).send({
          error: {
            name: 'Unauthorized',
            message: info.message,
            status: 401,
            statusCode: 401
          }
        });
        return;
      }
      return next();
    })(req, res, next);
  };
}

module.exports = {
  oauth2: createOauth2Middleware
};

{'fraction_non_alphanumeric': 0.14534883720930233, 'fraction_numerical': 0.009838998211091235, 'mean_word_length': 3.173507462686567, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, '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': '7215336', 'n_tokens_mistral': 726, 'n_tokens_neox': 717, 'n_words': 146}