1var mongoose = require('mongoose'),
2 Schema = mongoose.Schema,
3 bcrypt = require('bcrypt'),
4 SALT_WORK_FACTOR = 10;
5
6var UserSchema = new Schema({
7 username: { type: String, required: true, index: { unique: true } },
8 password: { type: String, required: true }
9});
10
11UserSchema.pre('save', function(next) {
12 var user = this;
13
14 // only hash the password if it has been modified (or is new)
15 if (!user.isModified('password')) return next();
16
17 // generate a salt
18 bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
19 if (err) return next(err);
20
21 // hash the password using our new salt
22 bcrypt.hash(user.password, salt, function(err, hash) {
23 if (err) return next(err);
24 // override the cleartext password with the hashed one
25 user.password = hash;
26 next();
27 });
28 });
29});
30
31UserSchema.methods.comparePassword = function(candidatePassword, cb) {
32 bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
33 if (err) return cb(err);
34 cb(null, isMatch);
35 });
36};
37
38module.exports = mongoose.model('User', UserSchema);
39
1var mongoose = require(mongoose),
2 User = require('./user-model');
3
4var connStr = 'mongodb://localhost:27017/mongoose-bcrypt-test';
5mongoose.connect(connStr, function(err) {
6 if (err) throw err;
7 console.log('Successfully connected to MongoDB');
8});
9
10// create a user a new user
11var testUser = new User({
12 username: 'jmar777',
13 password: 'Password123'
14});
15
16// save the user to database
17testUser.save(function(err) {
18 if (err) throw err;
19});
20
21// fetch the user and test password verification
22User.findOne({ username: 'jmar777' }, function(err, user) {
23 if (err) throw err;
24
25 // test a matching password
26 user.comparePassword('Password123', function(err, isMatch) {
27 if (err) throw err;
28 console.log('Password123:', isMatch); // -> Password123: true
29 });
30
31 // test a failing password
32 user.comparePassword('123Password', function(err, isMatch) {
33 if (err) throw err;
34 console.log('123Password:', isMatch); // -> 123Password: false
35 });
36});
37