Skip to content

Instantly share code, notes, and snippets.

@Echooff3
Created August 27, 2016 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Echooff3/019271c7418d20043bea6e5ab0764517 to your computer and use it in GitHub Desktop.
Save Echooff3/019271c7418d20043bea6e5ab0764517 to your computer and use it in GitHub Desktop.
/**
* Your utility library for express
*/
var basicAuth = require('basic-auth');
/**
* Simple basic auth middleware for use with Express 4.x.
*
* @example
* app.use('/api-requiring-auth', utils.basicAuth('username', 'password'));
*
* @param {string} username Expected username
* @param {string} password Expected password
* @returns {function} Express 4 middleware requiring the given credentials
*/
exports.basicAuth = function(username, password) {
return function(req, res, next) {
var user = basicAuth(req);
if (!user || user.name !== username || user.pass !== password) {
res.set('WWW-Authenticate', 'Basic realm=Authorization Required');
return res.sendStatus(401);
}
next();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment