Guest User

Untitled

a guest
Aug 24th, 2018
244
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. import mongoose from 'mongoose'
  2. import crypto from 'crypto'
  3.  
  4. const Schema = mongoose.Schema
  5.  
  6. const User = new Schema({
  7. username: {
  8. type: String
  9. },
  10. hashedPassword: {
  11. type: String,
  12. required: true
  13. },
  14. salt: {
  15. type: String,
  16. required: true
  17. }
  18. })
  19.  
  20. User.methods.encryptPassword = function(password) {
  21. return crypto.pbkdf2Sync(password, this.salt, 10000, 512, 'sha512').toString('hex')
  22. }
  23.  
  24. User.virtual('userId').get(function() {
  25. return this.id
  26. })
  27.  
  28. User.virtual('password').set(function(password) {
  29. this._plainPassword = password
  30. this.salt = crypto.randomBytes(128).toString('hex')
  31. this.hashedPassword = this.encryptPassword(password)
  32. }).get(function() {
  33. return this._plainPassword
  34. })
  35.  
  36. User.methods.checkPassword = function(password) {
  37. return this.encryptPassword(password) == this.hashedPassword
  38. }
  39.  
  40. module.exports = mongoose.model('User', User)
Add Comment
Please, Sign In to add comment