Video 104: Securely Storing Passwords: Part 2
This commit is contained in:
parent
015ea3619f
commit
9b4115afd5
@ -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
|
||||
|
@ -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()
|
||||
|
@ -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()
|
||||
|
Loading…
Reference in New Issue
Block a user