Skip to content

Instantly share code, notes, and snippets.

@willmendesneto
Last active September 7, 2015 15:46
Show Gist options
  • Save willmendesneto/5af17f5ef8f1c3957a2c to your computer and use it in GitHub Desktop.
Save willmendesneto/5af17f5ef8f1c3957a2c to your computer and use it in GitHub Desktop.
Multiple credentials check with Basic Auth node package
'use strict';
/**
* Multiple credentials check with Basic Auth node package
*
* How to use (ExpresJS example):
*
* var BASIC_AUTH = [
* {
* name: process.env.BASIC_AUTH_USERNAME,
* pass: process.env.BASIC_AUTH_PASSWORD
* },
* {
* name: process.env.BASIC_AUTH_USERNAME2,
* pass: process.env.BASIC_AUTH_PASSWORD2
* }
* ];
*
* var basicAuthMultipleCredentials = require('./basic-auth-multiple-credentials');
* router.get('/multiple-credential-check', basicAuthMultipleCredentials(BASIC_AUTH), function(req, res) {
* // ... your code
* });
*
* router.get('/single-credential-check', basicAuthMultipleCredentials(BASIC_AUTH[0]), function(req, res) {
* // ... your code
* });
*/
var auth = require('basic-auth');
module.exports = function(usersAndPasswords) {
if (!(usersAndPasswords instanceof Array)) {
usersAndPasswords = [usersAndPasswords];
}
return function(req, res, next) {
var credentials = auth(req);
var authenticated = function(credentials){
return usersAndPasswords.filter(function(registeredUser) {
return credentials.name === registeredUser.name &&
credentials.pass === registeredUser.pass;
}).length === 1;
};
if (!credentials || !authenticated(credentials)) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="example"');
res.end('Access denied');
} else {
next();
}
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment