/* * auth.js * * authentication * */ /* helpful links: * http://stackoverflow.com/questions/7990890/how-to-implement-login-auth-in-node-js/8003291#8003291 * */ var util = require('util'); var crypto = require('crypto'); var db = require('./mydb.js'); var len = 128; var iterations = 12000; /** * Hashes a password with optional `salt`, otherwise * generate a salt for `pass` and invoke `fn(err, salt, hash)`. * * @param {String} password to hash * @param {String} optional salt * @param {Function} callback * @api public */ function hash(pwd, salt, fn) { if (3 == arguments.length) { crypto.pbkdf2(pwd, salt, iterations, len, fn); } else { fn = salt; crypto.randomBytes(len, function(err, salt) { if (err) return fn(err); salt = salt.toString('base64'); crypto.pbkdf2(pwd, salt, iterations, len, function(err, hash) { if (err) return fn(err); fn(null, salt, hash); }); }); } }; /* pull out a user record from db along with http status code */ function auth_user(tag, id, fn) { db.users.find({tag: tag}, function(err, user_record) { if (err) { fn(err, null, -1); } else if (!user_record || user_record.length == 0) { fn(null, null, 403); } else { /* util.log('[auth] retrived user: ' + util.inspect(user_record)); */ hash(id, user_record[0].salt, function(err, hash) { if (err) return fn(err, null, -1); if (hash == user_record[0].hash) return fn(null, user_record[0], 200); /* granted */ fn(null, null, 401); }); } }); } exports.hash = hash; exports.auth_user = auth_user;