From b41ad999ee5d17f4de8c3c2836791d95cef19b36 Mon Sep 17 00:00:00 2001 From: JayWll Date: Wed, 15 Jul 2020 11:11:59 -0600 Subject: [PATCH] Video 109: Accepting Authentication Tokens --- task-manager/src/index.js | 6 +++--- task-manager/src/middleware/auth.js | 21 +++++++++++++++++++++ task-manager/src/routers/user.js | 10 +++------- 3 files changed, 27 insertions(+), 10 deletions(-) create mode 100644 task-manager/src/middleware/auth.js diff --git a/task-manager/src/index.js b/task-manager/src/index.js index 6d2e729..d055de5 100644 --- a/task-manager/src/index.js +++ b/task-manager/src/index.js @@ -14,9 +14,9 @@ const port = process.env.PORT || 4200 // } // }) -app.use((req, res, next) => { - res.status(503).send('Site is in maintenance mode').end() -}) +// app.use((req, res, next) => { +// res.status(503).send('Site is in maintenance mode').end() +// }) app.use(express.json()) app.use(userRouter) diff --git a/task-manager/src/middleware/auth.js b/task-manager/src/middleware/auth.js new file mode 100644 index 0000000..9cf6862 --- /dev/null +++ b/task-manager/src/middleware/auth.js @@ -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 diff --git a/task-manager/src/routers/user.js b/task-manager/src/routers/user.js index 25c242b..464b778 100644 --- a/task-manager/src/routers/user.js +++ b/task-manager/src/routers/user.js @@ -1,5 +1,6 @@ const express = require('express') const User = require('../models/user') +const auth = require('../middleware/auth') const router = new express.Router() router.post('/users', async (req, res) => { @@ -24,13 +25,8 @@ router.post('/users/login', async (req, res) => { } }) -router.get('/users', async (req, res) => { - try { - const users = await User.find({}) - res.send(users) - } catch (e) { - res.status(500).send() - } +router.get('/users/me', auth, async (req, res) => { + res.send(req.user) }) router.get('/users/:id', async (req, res) => {