Skip to content

Instantly share code, notes, and snippets.

@muddokon
Created October 2, 2019 14:50
Show Gist options
  • Save muddokon/1fa98113439079ba7419d1f0d25d10ba to your computer and use it in GitHub Desktop.
Save muddokon/1fa98113439079ba7419d1f0d25d10ba to your computer and use it in GitHub Desktop.
User Model
const mongoose = require('mongoose')
const validator = require('validator')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const userSchema = mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
unique: true,
lowercase: true,
validate: value => {
if (!validator.isEmail(value)) {
throw new Error({error: 'Email Invalido'})
}
}
},
password: {
type: String,
required: true,
minLength: 7
},
tokens: [{
token: {
type: String,
required: true
}
}]
})
userSchema.pre('save', async function (next) {
const user = this
if (user.isModified('password')) {
user.password = await bcrypt.hash(user.password, 8)
}
next()
})
userSchema.methods.generateAuthToken = async function() {
const user = this
const token = jwt.sign({_id: user._id}, process.env.JWT_KEY)
user.tokens = user.tokens.concat({token})
await user.save()
return token
}
userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email} )
if (!user) {
throw new Error({ error: 'Credenciales inválidas' })
}
const isPasswordMatch = await bcrypt.compare(password, user.password)
if (!isPasswordMatch) {
throw new Error({ error: 'Credenciales inválidas' })
}
return user
}
const User = mongoose.model('User', userSchema)
module.exports = User
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment