不幸的是,比较函数的结果总是错误的?即使发布了正确的数据.你认为这可能与bcrypt的compare函数有关吗?

注册

 module.exports.signupPost = async (req, res) => {
        const { email, password } = req.body;
    //create a user with hashed password
            try {
        const newUser = await User.create({ email, password });
        newUser.password = await bcrypt.hash(newUser.password, 12);
        newUser.save();
        res.status(200).json({ user: newUser._id });
    } catch (err) {
        errors = handlerErr(err);
        res.status(400).json({ errors });
    }
    };

登录

    module.exports.loginPost = async (req, res) => {
        const { email, password } = req.body;
        try {
            const user = await User.findOne({ email });
            if (!user) {
                res.status(404).json({ email: "No user found" });
            }
//if user exist check password is a match
        const user = await User.findOne({ email });
    if (!user) {
        return res.status(404).json({ email: "No user found" });
    }
    try {
        const match = await bcrypt.compare(
            password.toString(),
            user.password,
            function (err, res) {
                console.log(res);// returns false
            }
        );
    } catch (err) {}
    };
    
user schema

数据库用户架构

    const userSchema = new mongoose.Schema({
        email: {
            type: String,
            required: [true, "Please enter a  email"],
            unique: true,
            lowercase: true,
            
        },
        password: {
            type: String,
            required: [true, "Please enter a password"],
            lowercase: true,
        },
    });


推荐答案

从密码模式中删除lowercase: true.

在散列之前和保存散列时,都要将密码转换为小写.


您应该通过删除mongoose"密码"模式中的lowercase: true来允许密码大写.此设置使所有字符串在存储到数据库中之前都转换为小写.

当前实现有2个错误:

  1. 当您保存newUser时,输入密码在数据库中被转换为小写,然后用它生成哈希.
  2. 将哈希密码保存到数据库时,会丢失大小写,因此哈希不再准确.

Javascript相关问答推荐

我试图实现用户验证的reduxstore 和操作中出了什么问题?

如何用显示网格平滑地将元素从一个地方移动到另一个地方?

togglePopover()不打开但不关闭原生HTML popover'

如何找出摆线表面上y与x相交的地方?

TypeScript索引签名模板限制

setcallback是什么时候放到macrotask队列上的?

如何在JavaScript文件中使用Json文件

rxjs插入延迟数据

更改预请求脚本中重用的JSON主体变量- Postman

在HTML语言中调用外部JavaScript文件中的函数

如何将未排序的元素追加到数组的末尾?

在开发期间,Web浏览器如何运行&qot;.jsx&qot;文件?

使用NextJS+MongoDB+Prisma ORM获取无效请求正文,无法发布错误

如何在Java脚本中对列表中的特定元素进行排序?

使用RxJS from Event和@ViewChild vs KeyUp事件和RxJS主题更改输入字段值

如何修复错误&语法错误:不能在纯react 项目中JEST引发的模块&之外使用导入语句?

Reaction useState和useLoaderData的组合使用引发无限循环错误

我在哪里添加过滤器值到这个函数?

如何缩小函数中联合返回类型的范围

如何从嵌套的json中获取最大值