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

@ -14,9 +14,9 @@ const port = process.env.PORT || 4200
// } // }
// }) // })
app.use((req, res, next) => { // app.use((req, res, next) => {
res.status(503).send('Site is in maintenance mode').end() // res.status(503).send('Site is in maintenance mode').end()
}) // })
app.use(express.json()) app.use(express.json())
app.use(userRouter) app.use(userRouter)

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

View File

@ -1,5 +1,6 @@
const express = require('express') const express = require('express')
const User = require('../models/user') const User = require('../models/user')
const auth = require('../middleware/auth')
const router = new express.Router() const router = new express.Router()
router.post('/users', async (req, res) => { router.post('/users', async (req, res) => {
@ -24,13 +25,8 @@ router.post('/users/login', async (req, res) => {
} }
}) })
router.get('/users', async (req, res) => { router.get('/users/me', auth, async (req, res) => {
try { res.send(req.user)
const users = await User.find({})
res.send(users)
} catch (e) {
res.status(500).send()
}
}) })
router.get('/users/:id', async (req, res) => { router.get('/users/:id', async (req, res) => {