-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Created a user model that handles secure credential storage
- Loading branch information
lmarkus
committed
Dec 31, 2013
1 parent
d59b0f9
commit 0bb85e5
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |