Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2016
69
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.     if (!user.isModified("password"))
  32.     {
  33.         return next();
  34.     }
  35.  
  36.     /**
  37.      * hash password
  38.      */
  39.     bcrypt.hash(user.password, null, null, (err, hash) => {
  40.         if (err)
  41.         {
  42.             return next(err);
  43.         }
  44.  
  45.         user.password = hash;
  46.         return next();
  47.     });
  48. });
  49.  
  50. // #####################################################
  51. // ERROR
  52. // user.verifyPassword(req.body.password, match => {
  53. //     ^
  54. // TypeError: user.verifyPassword is not a function
  55. // ####################################################
  56. UserSchema.methods.verifyPassword = (reqPassword, callback) => {
  57.     bcrypt.compare(reqPassword, this.password, (err, match) => {
  58.         var e = null;
  59.         var m = match;
  60.  
  61.         if (err)
  62.         {
  63.             e = err;
  64.             m = false;
  65.         }
  66.  
  67.         return callback(e, m);
  68.     });
  69. };
  70.  
  71.  
  72.  
  73. module.exports = mongoose.model("User", UserSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement