1
0
Fork 0

Video 107: Generating Authentication Tokens

This commit is contained in:
JayWll 2020-04-13 16:26:04 -06:00
parent fed44eda88
commit d4dac9c676
2 changed files with 22 additions and 3 deletions

View File

@ -1,6 +1,7 @@
const mongoose = require('mongoose')
const validator = require('validator')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const userSchema = new mongoose.Schema({
name: {
@ -39,9 +40,25 @@ const userSchema = new mongoose.Schema({
throw new Error('Age must be a positive number')
}
}
}
},
tokens: [{
token: {
type: String,
required: true
}
}]
})
userSchema.methods.generateAuthToken = async function () {
const user = this
const token = jwt.sign({ _id: user._id.toString() }, 'thisismynewcourse')
user.tokens = user.tokens.concat({ token })
await user.save()
return token
}
userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email })

View File

@ -7,7 +7,8 @@ router.post('/users', async (req, res) => {
try {
await user.save()
res.status(201).send(user)
const token = await user.generateAuthToken()
res.status(201).send({ user, token })
} catch (e) {
res.status(400).send(e)
}
@ -16,7 +17,8 @@ router.post('/users', async (req, res) => {
router.post('/users/login', async (req, res) => {
try {
const user = await User.findByCredentials(req.body.email, req.body.password)
res.send(user)
const token = await user.generateAuthToken()
res.send({ user, token })
} catch (e) {
res.status(400).send()
}