Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. const mongoose = require('mongoose')
  2. const validator = require('validator')
  3. const bcrypt = require('bcryptjs')
  4. const jwt = require('jsonwebtoken')
  5.  
  6. const userSchema = mongoose.Schema({
  7. name: {
  8. type: String,
  9. required: true,
  10. trim: true
  11. },
  12. email: {
  13. type: String,
  14. required: true,
  15. unique: true,
  16. lowercase: true,
  17. validate: value => {
  18. if (!validator.isEmail(value)) {
  19. throw new Error({error: 'Email Invalido'})
  20. }
  21. }
  22. },
  23. password: {
  24. type: String,
  25. required: true,
  26. minLength: 7
  27. },
  28. tokens: [{
  29. token: {
  30. type: String,
  31. required: true
  32. }
  33. }]
  34. })
  35.  
  36. userSchema.pre('save', async function (next) {
  37. const user = this
  38. if (user.isModified('password')) {
  39. user.password = await bcrypt.hash(user.password, 8)
  40. }
  41. next()
  42. })
  43.  
  44. userSchema.methods.generateAuthToken = async function() {
  45. const user = this
  46. const token = jwt.sign({_id: user._id}, process.env.JWT_KEY)
  47. user.tokens = user.tokens.concat({token})
  48. await user.save()
  49. return token
  50. }
  51.  
  52. userSchema.statics.findByCredentials = async (email, password) => {
  53. const user = await User.findOne({ email} )
  54. if (!user) {
  55. throw new Error({ error: 'Credenciales inválidas' })
  56. }
  57. const isPasswordMatch = await bcrypt.compare(password, user.password)
  58. if (!isPasswordMatch) {
  59. throw new Error({ error: 'Credenciales inválidas' })
  60. }
  61. return user
  62. }
  63.  
  64. const User = mongoose.model('User', userSchema)
  65.  
  66. module.exports = User
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement