Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var mongoose    = require("mongoose");
  2. var Schema      = mongoose.Schema;
  3. var constants   = require("../config/constants");
  4. var bcrypt      = require("bcrypt-nodejs");
  5.  
  6.  
  7. var UserSchema = new Schema({
  8.     name: String,
  9.     email: String,
  10.     password: String,
  11.     authorization:
  12.     {
  13.         type: Number,
  14.         default: constants.authorization.default
  15.     }
  16. });
  17.  
  18. UserSchema.pre("save", (next) => {
  19.     var user = this;
  20.  
  21.     /**
  22.      * Only hash the password when it's been modified or if new.
  23.      */
  24.  
  25.     // #####################################################
  26.     // ERROR
  27.     // if (!query.isModified("password"))
  28.     //            ^
  29.     // TypeError: query.isModified is not a function
  30.     //
  31.     // user and this == {}
  32.     // ####################################################
  33.     if (!user.isModified("password"))
  34.     {
  35.         return next();
  36.     }
  37.  
  38.     /**
  39.      * hash password
  40.      */
  41.     bcrypt.hash(user.password, null, null, (err, hash) => {
  42.         if (err)
  43.         {
  44.             return next(err);
  45.         }
  46.  
  47.         user.password = hash;
  48.         return next();
  49.     });
  50. });
  51.  
  52. // #####################################################
  53. // ERROR
  54. // user.verifyPassword(req.body.password, match => {
  55. //     ^
  56. // TypeError: user.verifyPassword is not a function
  57. //
  58. // this == {}
  59. // ####################################################
  60. UserSchema.methods.verifyPassword = (reqPassword, callback) => {
  61.     bcrypt.compare(reqPassword, this.password, (err, match) => {
  62.         var e = null;
  63.         var m = match;
  64.  
  65.         if (err)
  66.         {
  67.             e = err;
  68.             m = false;
  69.         }
  70.  
  71.         return callback(e, m);
  72.     });
  73. };
  74.  
  75.  
  76.  
  77. module.exports = mongoose.model("User", UserSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement