Video 107: Generating Authentication Tokens
This commit is contained in:
parent
fed44eda88
commit
d4dac9c676
@ -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 })
|
||||
|
||||
|
@ -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()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user