Advertisement
Guest User

Untitled

a guest
Mar 30th, 2019
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const mongoose = require('mongoose')
  2. const validator = require('validator')
  3. const bcrypt = require('bcryptjs')
  4. const jwt = require('jsonwebtoken')
  5.  
  6. const userSchema = new mongoose.Schema({
  7.     username: {
  8.         type: String,
  9.         required: true,
  10.         trim: true
  11.     },
  12.     email: {
  13.         type: String,
  14.         unique: true,
  15.         required: true,
  16.         trim: true,
  17.         lowercase: true,
  18.         validate(value) {
  19.             if (!validator.isEmail(value)) {
  20.                 throw new Error('Email is invalid')
  21.             }
  22.         }
  23.     },
  24.     password: {
  25.         type: String,
  26.         required: true,
  27.         minlength: 4,
  28.         trim: true,
  29.     },
  30.     role: {
  31.         type: String,
  32.         required: true,
  33.     },
  34.     active: {
  35.         type: Boolean,
  36.         default: true
  37.     }
  38. })
  39.  
  40. userSchema.virtual('entries', {
  41.     ref: 'Entry',
  42.     localField: '_id',
  43.     foreignField: 'owner'
  44. })
  45.  
  46. userSchema.methods.toJSON = function () {
  47.     const user = this
  48.     const userObject = user.toObject()
  49.     delete userObject.password
  50.     return userObject
  51. }
  52.  
  53. userSchema.methods.generateAuthToken = async function () {
  54.     const user = this
  55.     const token = jwt.sign({ _id: user._id.toString() }, 'secret')
  56.     return token
  57. }
  58.  
  59. userSchema.statics.findByCredentials = async (email, password) => {
  60.     const user = await User.findOne({ email })
  61.  
  62.     if (!user) {
  63.         throw new Error('Unable to login')
  64.     }
  65.  
  66.     const isMatch = await bcrypt.compare(password, user.password)
  67.  
  68.     if (!isMatch) {
  69.         throw new Error('Unable to login')
  70.     }
  71.  
  72.     return user
  73. }
  74.  
  75. // Hash the plain text password before saving
  76. userSchema.pre('save', async function (next) {
  77.     const user = this
  78.  
  79.     if (user.isModified('password')) {
  80.         user.password = await bcrypt.hash(user.password, 8)
  81.     }
  82.  
  83.     next()
  84. })
  85.  
  86. // Delete user tasks when user is removed
  87. userSchema.pre('remove', async function (next) {
  88.     const user = this
  89.     await Task.deleteMany({ owner: user._id })
  90.     next()
  91. })
  92.  
  93. const User = mongoose.model('User', userSchema)
  94.  
  95. module.exports = User
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement