armsultan
4/6/2016 - 12:42 PM

NodeJS Mongoose User Schema to be used within a default NodeJS application structure

NodeJS Mongoose User Schema to be used within a default NodeJS application structure

// file: app/models/user.js

// Get an instance of mongoose and mongoose Schema
var mongoose = require('mongoose'),
    bcrypt = require('bcrypt'),
    Schema = mongoose.Schema,
    SALTINESS = 42;

// Create Schema
var UserSchema = new Schema({
  name: {type: String, require: true, index: {unique: true}},
  password: {type: String, require: true},
  admin: Boolean
});

// Before saving the user, salt the password
UserSchema.pre('save', function(next) {
   var user = this;
   // No modification of the password, no need to hash it
   if (!user.isModified('password')) next();
   
   bcrypt.genSalt(SALTINESS, function(error, salt) {
       // Do not continue, error raised by genSalt
       if (error) next(error);
       
       // Create a bcrypt hash with the generated salt and assign it to the user object
       bcrypt.hash(user.password, salt, function(error, hash) {
            // Do not try to store the password, error raised by hash
            if (error) next(error);
            
            // Replace the password with the fresh generated hash and continue operation
            user.password = hash;
            next();
       });
   });
});

// Compare password method for validating a matching hash for a given password @ login
UserSchema.methods.comparePassword = comparePassword;

// Define comparePassword method
function comparePassword(input, callback) {
    bcrypt.compare(input, this.password, function(error, isMatch) {
        // Do not continue, error raised by bcrypt compare
        if (error) return callback(error); 
        // Call the callback and return the result of bcrypt compare as data
        callback(null, isMatch);
    });
}

// Expose via export
module.exports = mongoose.model('User', UserSchema);