Skip to content

Instantly share code, notes, and snippets.

@zenlor
Created March 21, 2012 11:45
Show Gist options
  • Select an option

  • Save zenlor/2146378 to your computer and use it in GitHub Desktop.

Select an option

Save zenlor/2146378 to your computer and use it in GitHub Desktop.
var utils = require('./utils')
, shasum = utils.shasum
, shahmac = utils.shahmac
, randuid = utils.randuid;
// ## User Schema
//
User = new Schema({
uid: String,
pwd: String,
name: String,
surname: String,
role: String
});
// custom setter
User.path('pwd').set(function(data) {
var hash, salt;
salt = randuid(5);
hash = shahmac(data, salt);
return salt + hash;
});
// static methods
User.statics.authenticate = function(uid, pwd, cb) {
return this.findOne({
uid: uid
}).run(function(err, user) {
var hash, salt;
if (err || user === null) return cb(err, false, user);
salt = user.pwd.substring(0, 5);
hash = user.pwd.substring(5);
return cb(err, shahmac(pwd, salt) === hash, user);
});
};
var crypto = require('crypto')
, connect = require('connect');
module.exports = {
// *shasum* simple and dirty sha1 hex digest for strings
shasum: function(str) {
return crypto.createHash('sha1').update(str).digest('hex');
}
// *shahmac* hmac sha256 hex digest creation from a string and a key
, shahmac: function(str, key) {
if (key == null) key = "";
return crypto.createHmac('sha256', key).update(str).digest('hex');
}
, randuid: connect.utils.uid
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment