Authentication with Mongoose & bCrypt

This is a basic node.js implementation of username/password authentication using Mongoose and bCrypt-nodejs that I made for an assignment at Hack Reactor.

Here is the final product:

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');

var userSchema = new mongoose.Schema({
  username:{type: String, unique: true},
  password:String
});

userSchema.pre('save', function(next){
  var user = this;
  if(user.isModified('password')){
    bcrypt.hash(user.password, null, null, function(err, hash){
      if (err){
        next();
      }
      user.password = hash;
      next();
    });
  }
  next();
}

userSchema.methods.comparePassword = function(attemptedPassword, callback) {
  bcrypt.compare(attemptedPassword, this.password, function(err, isMatch) {
    callback(isMatch);
  });
};
module.exports = mongoose.model('users', userSchema);

First, we bring in the required modules:

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');

We then set up our userSchema so that each user has a unique username, and a String password.

var userSchema = new mongoose.Schema({
  username:{type: String, unique: true},
  password:String
});

Next we set our encryption function to enrypt whenever the save function of the schemais called and the password has been changed.

userSchema.pre('save', function(next){
  var user = this;
  if(user.isModified('password')){
    bcrypt.hash(user.password, null, null, function(err, hash){
      if (err){
        next();
      }
      user.password = hash;
      next();
    });
  }
  next();
}

And the encryption function is as follows:

userSchema.methods.comparePassword = function(attemptedPassword, callback) {
  bcrypt.compare(attemptedPassword, this.password, function(err, isMatch) {
    callback(isMatch);
  });
};

Lastly we export the model for some mongoosin!

    module.exports = mongoose.model('users', userSchema);

And there you have it. Please keep in mind that this is very basic, and additional security features should be added before real world application.