From 9b4115afd56529cb6b3c279fa7aa1c60eaac9024 Mon Sep 17 00:00:00 2001 From: JayWll Date: Mon, 13 Apr 2020 15:26:38 -0600 Subject: [PATCH] Video 104: Securely Storing Passwords: Part 2 --- task-manager/src/models/user.js | 15 ++++++++++++++- task-manager/src/routers/task.js | 6 +++++- task-manager/src/routers/user.js | 5 ++++- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/task-manager/src/models/user.js b/task-manager/src/models/user.js index c02d3f3..28476c9 100644 --- a/task-manager/src/models/user.js +++ b/task-manager/src/models/user.js @@ -1,7 +1,8 @@ const mongoose = require('mongoose') const validator = require('validator') +const bcrypt = require('bcryptjs') -const User = mongoose.model('User', { +const userSchema = new mongoose.Schema({ name: { type: String, required: true, @@ -40,4 +41,16 @@ const User = mongoose.model('User', { } }) +userSchema.pre('save', async function(next) { + const user = this + + if (user.isModified('password')) { + user.password = await bcrypt.hash(user.password, 8) + } + + next() +}) + +const User = mongoose.model('User', userSchema) + module.exports = User diff --git a/task-manager/src/routers/task.js b/task-manager/src/routers/task.js index f914286..3fa3871 100644 --- a/task-manager/src/routers/task.js +++ b/task-manager/src/routers/task.js @@ -48,7 +48,11 @@ router.patch('/tasks/:id', async (req, res) => { } try { - const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }) + const task = await Task.findById(req.params.id) + + updates.forEach((update) => task[update] = req.body[update]) + await task.save() + if (!task) { return res.status(404).send() diff --git a/task-manager/src/routers/user.js b/task-manager/src/routers/user.js index 1d3473e..ed8ce04 100644 --- a/task-manager/src/routers/user.js +++ b/task-manager/src/routers/user.js @@ -48,7 +48,10 @@ router.patch('/users/:id', async (req, res) => { } try { - const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true }) + const user = await User.findById(req.params.id) + + updates.forEach((update) => user[update] = req.body[update]) + await user.save() if (!user) { return res.status(404).send()