From 3a9e40b2f13ad7f7a0e10827b87f263b4bf0504c Mon Sep 17 00:00:00 2001 From: JayWll Date: Thu, 16 Jul 2020 11:24:18 -0600 Subject: [PATCH] Video 115: Authenticating Task Endpoints --- task-manager/src/routers/task.js | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/task-manager/src/routers/task.js b/task-manager/src/routers/task.js index d8f3896..dac94a3 100644 --- a/task-manager/src/routers/task.js +++ b/task-manager/src/routers/task.js @@ -17,20 +17,20 @@ router.post('/tasks', auth, async (req, res) => { } }) -router.get('/tasks', async (req, res) => { +router.get('/tasks', auth, async (req, res) => { try { - const tasks = await Task.find({}) - res.send(tasks) + await req.user.populate('tasks').execPopulate() + res.send(req.user.tasks) } catch (e) { res.status(500).send() } }) -router.get('/tasks/:id', async (req, res) => { +router.get('/tasks/:id', auth, async (req, res) => { const _id = req.params.id try { - const task = await Task.findById(_id) + const task = await Task.findOne({ _id, owner: req.user._id }) if (!task) { return res.status(404).send() @@ -42,7 +42,7 @@ router.get('/tasks/:id', async (req, res) => { } }) -router.patch('/tasks/:id', async (req, res) => { +router.patch('/tasks/:id', auth, async (req, res) => { const updates = Object.keys(req.body) const allowedUpdates = ['description', 'completed'] const isValidOperation = updates.every((update) => allowedUpdates.includes(update)) @@ -52,25 +52,24 @@ router.patch('/tasks/:id', async (req, res) => { } try { - const task = await Task.findById(req.params.id) - - updates.forEach((update) => task[update] = req.body[update]) - await task.save() - + const task = await Task.findOne({ _id: req.params.id, owner: req.user._id }) if (!task) { return res.status(404).send() } + updates.forEach((update) => task[update] = req.body[update]) + await task.save() + res.send(task) } catch (e) { res.status(400).send(e) } }) -router.delete('/tasks/:id', async (req, res) => { +router.delete('/tasks/:id', auth, async (req, res) => { try { - const task = await Task.findByIdAndDelete(req.params.id) + const task = await Task.findOneAndDelete({ _id: req.params.id, owner: req.user._id }) if (!task) { return res.status(404).send()