Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. const mongoose = require('mongoose');
  2. const Schema = mongoose.Schema;
  3. const bcrypt = require('bcrypt-nodejs');
  4.  
  5. // Define our model
  6. const userSchema = new Schema({
  7. email: { type: String, unique: true, lowercase: true},
  8. password: String,
  9. adress: String,
  10. age: String,
  11. firstname: String,
  12. lastname: String,
  13. city: String,
  14. travel: String
  15. });
  16.  
  17. // On Save Hook, encrypt password
  18.  
  19. // Before saving a model, run this function
  20.  
  21. userSchema.pre('save', function(next){
  22.  
  23. //get acess to the user model
  24.  
  25. const user = this; // user.email, user.password
  26.  
  27.  
  28. //generate a salt then run callback
  29.  
  30. bcrypt.genSalt(10, function(err, salt) {
  31. if (err) {return next(err);}
  32.  
  33. // hash(encrypt) our password using the salt
  34. bcrypt.hash(user.password, salt, null, function(err, hash){
  35. if (err) {return next(err); }
  36.  
  37. // overwrite plain text password with encrypted password
  38. user.password = hash;
  39. next();
  40. });
  41. });
  42. });
  43.  
  44. userSchema.methods.comparePassword = function(candidatePassword, callback ){
  45. bcrypt.compare(candidatePassword, this.password, function(err, isMatch){
  46. if (err) { return callback(err); }
  47.  
  48. callback(null, isMatch);
  49. });
  50. }
  51.  
  52. // Create the model class
  53. const ModelClass = mongoose.model('user', userSchema);
  54.  
  55. // Export the model
  56. module.exports = ModelClass;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement