繁体   English   中英

bcrypt.compare 总是返回 false

[英]bcrypt.compare always returns false

我正在尝试登录 function 但是当我尝试将密码与散列密码进行比较时,它总是返回 false

这是我的 registerUser function 保存散列

const registerUser = async (request, response) => {
    const hashedPassword = await bcrypt.hash(request.body.password, 12)
    const user = new UserModel({
        username: request.body.username,
        password: hashedPassword
    });

    try {
        const databaseResponse = await user.save();
        response.status(201).send(databaseResponse);
    } catch (error) {
        response.status(500).send({message: error.message});
    }
};

这是保存比较的登录 function

const login = async (request, response) => {
    try{
        const user = await UserModel.findOne({username: request.body.username})
        if(!user) return response.status(403).send('no user with name ' + request.body.username + ' found');
        const isPassValidated = await bcrypt.compare(request.body.password, user.password)
        if(!isPassValidated) return response.status(403).send('wrong password');
        response.status(200).send('yay');
    } catch(error){
        response.status(500).send({message: error.message});
    }
}

当我 console.log request.body.password 和 user.password 哈希字符串等于未哈希字符串,所以它应该返回 true

截屏

哈希字符串与保存在数据库中的字符串相同

刚刚发现问题,谢谢大家帮忙。 在 userSchema 中,密码是小写:true 导致问题...

代码看起来没问题。 您的数据库中是否有多个具有相同用户名的用户? 生成的 hash 应该是: $2b$12$jgrLYOqnHnJGszlpgo26QuaT29tdxBFguyIttSNOIy/8go1viRrYC

重新创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM