Skip to content

Instantly share code, notes, and snippets.

@jrask
Created October 1, 2012 20:56
Show Gist options
  • Save jrask/3814353 to your computer and use it in GitHub Desktop.
Save jrask/3814353 to your computer and use it in GitHub Desktop.
auth
// Basic-auth validation and url (database) access validation
function authenticate(req, res, callback) {
// Extract authorization header and decode
var header = req.headers['authorization'] || '', // get the header
token = header.split(/\s+/).pop() || '', // and the encoded auth token
auth = new Buffer(token, 'base64').toString(), // convert from base64
parts = auth.split(/:/), // split on colon
user = parts[0],
passwd = parts[1];
// Validate the user and password
var userAcl = acl.acl[user];
if (!userAcl || userAcl.password != passwd) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm=\"quiz.jayway.com\"');
console.log("Invalid user: " + user + " or password: " + passwd)
res.write('Invalid credentials');
res.end();
callback.onError()
return
}
// Validate that the user has access to the database
if (!req.url.match(new RegExp('/' + userAcl.database + '/' + userAcl.collection + '/'))) {
res.statusCode = 401;
res.write("You do not have access to this database")
res.end();
callback.onError();
return;
}
callback.onSuccess();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment