1
0

Video 109: Accepting Authentication Tokens

This commit is contained in:
JayWll
2020-07-15 11:11:59 -06:00
parent 526fc9ebdd
commit b41ad999ee
3 changed files with 27 additions and 10 deletions

View File

@@ -0,0 +1,21 @@
const jwt = require('jsonwebtoken')
const User = require('../models/user')
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization').replace('Bearer ', '')
const decoded = jwt.verify(token, 'thisismynewcourse')
const user = await User.findOne({ _id: decoded._id, 'tokens.token': token })
if (!user) {
throw new Error()
}
req.user = user
next()
} catch (e) {
res.status(401).send({ error: 'Please authenticate.'}).end()
}
}
module.exports = auth