Skip to content

Commit

Permalink
Created a user model that handles secure credential storage
Browse files Browse the repository at this point in the history
  • Loading branch information
lmarkus committed Dec 31, 2013
1 parent d59b0f9 commit 0bb85e5
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions models/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* A model for our user
*/
'use strict';
var mongoose = require('mongoose'),
bcrypt = require('bcrypt'),
nconf = require('nconf'),
DIFFICULTY = (nconf.get('auth') && nconf.get('bcrypt').difficulty) || 8; //Retrieve the desired difficulty from the configuration. (Default = 8)


var userModel = function () {

var userSchema = mongoose.Schema({
name: String,
login: { type: String, unique: true }, //Ensure logins are unique.
password: String, //We'll store bCrypt hashed passwords. Just say no to plaintext!
role: String
});

/**
* Helper function that hooks into the 'save' method, and replaces plaintext passwords with a hashed version.
*/
userSchema.pre('save', function (next) {
var user = this;

//If the password has not been modified in this save operation, leave it alone (So we don't double hash it)
if (!user.isModified('password')) {
next();
return;
}

//Encrypt it using bCrypt. Using the Sync method instead of Async to keep the code simple.
var hashedPwd = bcrypt.hashSync(user.password, DIFFICULTY);

//Replace the plaintext pw with the Hash+Salted pw;
user.password = hashedPwd;

//Continue with the save operation
next();
});

/**
* Helper function that takes a plaintext password and compares it against the user's hashed password.
* @param plainText
* @returns true/false
*/
userSchema.methods.passwordMatches = function (plainText) {
var user = this;
return bcrypt.compareSync(plainText, user.password);
}


return mongoose.model('User', userSchema);
};

module.exports = new userModel();

0 comments on commit 0bb85e5

Please sign in to comment.