Advertisement
Guest User

Untitled

a guest
Apr 7th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. // file: app/models/user.js
  2.  
  3. // Get an instance of mongoose and mongoose Schema
  4. var mongoose = require('mongoose'),
  5. bcrypt = require('bcrypt'),
  6. Schema = mongoose.Schema,
  7. SALTINESS = 42;
  8.  
  9. // Create Schema
  10. var UserSchema = new Schema({
  11. name: {type: String, require: true, index: {unique: true}},
  12. password: {type: String, require: true},
  13. admin: Boolean
  14. });
  15.  
  16. // Before saving the user, salt the password
  17. UserSchema.pre('save', function(next) {
  18. var user = this;
  19. // No modification of the password, no need to hash it
  20. if (!user.isModified('password')) next();
  21.  
  22. bcrypt.genSalt(SALTINESS, function(error, salt) {
  23. // Do not continue, error raised by genSalt
  24. if (error) next(error);
  25.  
  26. // Create a bcrypt hash with the generated salt and assign it to the user object
  27. bcrypt.hash(user.password, salt, function(error, hash) {
  28. // Do not try to store the password, error raised by hash
  29. if (error) next(error);
  30.  
  31. // Replace the password with the fresh generated hash and continue operation
  32. user.password = hash;
  33. next();
  34. });
  35. });
  36. });
  37.  
  38. // Compare password method for validating a matching hash for a given password @ login
  39. UserSchema.methods.comparePassword = comparePassword;
  40.  
  41. // Define comparePassword method
  42. function comparePassword(input, callback) {
  43. bcrypt.compare(input, this.password, function(error, isMatch) {
  44. // Do not continue, error raised by bcrypt compare
  45. if (error) return callback(error);
  46. // Call the callback and return the result of bcrypt compare as data
  47. callback(null, isMatch);
  48. });
  49. }
  50.  
  51. // Expose via export
  52. module.exports = mongoose.model('User', UserSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement