text: /*
   * Author: Alton Lau
   * Date: February 4, 2017
   * File: user_model.js
   * Description: User model
   */
  
  var bcrypt = require('bcrypt');
  var mongoose = require('mongoose');
  var Schema = mongoose.Schema;
  
  var userSchema = new Schema({
    name: {
      type: String,
      unique: true,
      required: true
    },
    password: {
      type: String,
      required: true
    },
    firstName: {
      type: String
    },
    lastName: {
      type: String
    },
    createdAt: {
      type: Date,
      default: Date.now
    }
  });
  
  userSchema.pre('save', function (next) {
    var user = this;
    if (user.isModified('password') || user.isNew) {
      bcrypt.genSalt(10, function (err, salt) {
        if (err) {
          return next(err);
        }
        bcrypt.hash(user.password, salt, function (err, hash) {
          if (err) {
            return next(err);
          }
          user.password = hash;
          next();
        });
      });
    } else {
      return next();
    }
  });
  
  userSchema.methods.comparePassword = function (passw, cb) {
    bcrypt.compare(passw, this.password, function (err, isMatch) {
      if (err) {
        return cb(err);
      }
      cb(null, isMatch);
    });
  };
  
  module.exports = mongoose.model('User', userSchema);
  