Video 109: Accepting Authentication Tokens
This commit is contained in:
parent
526fc9ebdd
commit
b41ad999ee
@ -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)
|
||||||
|
21
task-manager/src/middleware/auth.js
Normal file
21
task-manager/src/middleware/auth.js
Normal 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
|
@ -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) => {
|
||||||
|
Loading…
Reference in New Issue
Block a user