如何使用 MERN 堆栈创建安全的 CRUD 操作

How can I create secure CRUD operation using MERN stack

我是 MERN 堆栈的新手,我做过 CRUD 操作。我想在创建新用户时对密码进行哈希处理,因为在创建新用户并尝试登录“无效凭据”后出现错误,因为新用户是使用密码纯文本创建的,并且我的注册比较密码用散列的

我创建新用户代码:

exports.create = (req, res) => {

if(!req.body.name || !req.body.email || !req.body.password) {
     return res.status(400).send({
         message: "Name, Email and Password can not be empty"
     });
}

const user = new User({
    name: req.body.name.trim(),
    email: req.body.email.trim(),
    password: req.body.password.trim()
});

user.save()
.then(data => {
    const user = usersSerializer(data)
    res.send(user);
}).catch(err => {
    res.status(500).send({
        message: err.message || "Some error occurred while creating the User."
    });
});

};

您必须先对用户密码进行散列处理,然后才能将其存储在数据库中。做这样的事情。

router.post(
'/register',
[
    check('email', 'Uncorrectly e-mail').isEmail(),
    check('password', 'Uncorrectly password').isLength({ min: 6 })
],
async (req, res) => {
try {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(400).json ({
            errors: errors.array(),
            message: 'Incorrect registration data'
        })
    }
    console.log(req.body)
    const { email, password, firstName, lastName } = req.body


    const candidate = await User.findOne({ email })

    if (candidate) {
        return res.status(400).json({ message: 'User already exist' })
    }


    const hashedPassword = await bcrypt.hash(password,12)
    const user = new User ({email, password: hashedPassword, firstName, lastName})
    await user.save()

    res.status(201).json({ message: 'New user created' })


} catch (error) {
    res.status(500).json ({ message: 'ERROR' })
}

})