Video 107: Generating Authentication Tokens
This commit is contained in:
parent
fed44eda88
commit
d4dac9c676
@ -1,6 +1,7 @@
|
|||||||
const mongoose = require('mongoose')
|
const mongoose = require('mongoose')
|
||||||
const validator = require('validator')
|
const validator = require('validator')
|
||||||
const bcrypt = require('bcryptjs')
|
const bcrypt = require('bcryptjs')
|
||||||
|
const jwt = require('jsonwebtoken')
|
||||||
|
|
||||||
const userSchema = new mongoose.Schema({
|
const userSchema = new mongoose.Schema({
|
||||||
name: {
|
name: {
|
||||||
@ -39,9 +40,25 @@ const userSchema = new mongoose.Schema({
|
|||||||
throw new Error('Age must be a positive number')
|
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) => {
|
userSchema.statics.findByCredentials = async (email, password) => {
|
||||||
const user = await User.findOne({ email })
|
const user = await User.findOne({ email })
|
||||||
|
|
||||||
|
@ -7,7 +7,8 @@ router.post('/users', async (req, res) => {
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
await user.save()
|
await user.save()
|
||||||
res.status(201).send(user)
|
const token = await user.generateAuthToken()
|
||||||
|
res.status(201).send({ user, token })
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.status(400).send(e)
|
res.status(400).send(e)
|
||||||
}
|
}
|
||||||
@ -16,7 +17,8 @@ router.post('/users', async (req, res) => {
|
|||||||
router.post('/users/login', async (req, res) => {
|
router.post('/users/login', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const user = await User.findByCredentials(req.body.email, req.body.password)
|
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) {
|
} catch (e) {
|
||||||
res.status(400).send()
|
res.status(400).send()
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user