1
0
Fork 0

Video 115: Authenticating Task Endpoints

This commit is contained in:
JayWll 2020-07-16 11:24:18 -06:00
parent 771e9bd0d4
commit 3a9e40b2f1
1 changed files with 12 additions and 13 deletions

View File

@ -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()