1
0
Fork 0

Video 104: Securely Storing Passwords: Part 2

This commit is contained in:
JayWll 2020-04-13 15:26:38 -06:00
parent 015ea3619f
commit 9b4115afd5
3 changed files with 23 additions and 3 deletions

View File

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

View File

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

View File

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