【问题标题】:How can I create secure CRUD operation using MERN stack如何使用 MERN 堆栈创建安全的 CRUD 操作
【发布时间】:2022-01-05 10:24:13
【问题描述】:

我是 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."
    });
});

};

【问题讨论】:

    标签: node.js reactjs mongodb hash mern


    【解决方案1】:

    在将用户密码存储到数据库之前,您必须对其进行哈希处理。做这样的事情。

    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' })
    }
    

    })

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-05
      • 2014-02-05
      • 2020-08-20
      • 2019-02-07
      • 2021-12-19
      • 1970-01-01
      • 2022-08-07
      • 1970-01-01
      相关资源
      最近更新 更多