Guest User

Untitled

a guest
Aug 15th, 2018
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. creating registration and login form in node.js and mongodb
  2. User = new Schema({
  3. 'email': { type: String, validate: [validatePresenceOf, 'an email is required'], index: { unique: true } },
  4. 'hashed_password': String,
  5. 'salt': String
  6. });
  7.  
  8. User.virtual('id')
  9. .get(function() {
  10. return this._id.toHexString();
  11. });
  12.  
  13. User.virtual('password')
  14. .set(function(password) {
  15. this._password = password;
  16. this.salt = this.makeSalt();
  17. this.hashed_password = this.encryptPassword(password);
  18. })
  19. .get(function() { return this._password; });
  20.  
  21. User.method('authenticate', function(plainText) {
  22. return this.encryptPassword(plainText) === this.hashed_password;
  23. });
  24.  
  25. User.method('makeSalt', function() {
  26. return Math.round((new Date().valueOf() * Math.random())) + '';
  27. });
  28.  
  29. User.method('encryptPassword', function(password) {
  30. return crypto.createHmac('sha1', this.salt).update(password).digest('hex');
  31. });
  32.  
  33. User.pre('save', function(next) {
  34. if (!validatePresenceOf(this.password)) {
  35. next(new Error('Invalid password'));
  36. } else {
  37. next();
  38. }
  39. });
Add Comment
Please, Sign In to add comment