为什么即使我输入了正确的密码,bcrypt 的比较方法也返回 false?

编程入门 行业动态 更新时间:2024-10-04 19:22:50

为什么即<a href=https://www.elefans.com/category/jswz/34/1771288.html style=使我输入了正确的密码,bcrypt 的比较方法也返回 false?"/>

为什么即使我输入了正确的密码,bcrypt 的比较方法也返回 false?

我正在使用 Postman 来测试登录 API。注册 API 工作正常并在将密码保存到数据库之前对密码进行哈希处理。但是当我尝试使用相同的凭据登录时,它说密码不匹配。

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const Schema = mongoose.Schema;
const userSchema = new Schema({
    username: {
        type: String, 
        required: true, 
        unique: true,
        trim: true,
        minlength: 5
    },
    email: {
        type:String, 
        required: true, 
        unique: true, 
        trim: true
    },
    password: {
        type: String, 
        required: true,
        trim: true, 
        lowercase: true,
        minlength: 6
    }
});

这是加密密码的中间件

userSchema.pre("save", async function (next) {

    try{
        const user = this;
        if (!user.isModified("password")) {
          return next();
        }
        const salt = await bcrypt.genSalt(10);
        const hash = await bcrypt.hash(user.password, salt);
        user.password = hash;
        next();
    }
    catch (error) {
        throw new Error(error);
    }

  });

这是登录功能。每当我输入正确的用户名和密码时,它都会说密码错误。

try{
        const {username, password} = req.body;
        const { error } = loginValidation.validate(req.body);
    
        if (error) {
            return res.status(400).json({ message: error.details[0].message, type: "error"});
        }
    
        const existingUser = await User.findOne({ username });
        
        if (!existingUser){
            return res.status(401).json({message:"Invalid username", type:"error"});
        }

        const passwordMatch = await bcryptpare(password, existingUser.password);
        if(!passwordMatch){
            return res.status(401).json({message:"Invalid password", type:"error"});
        }

        res.status(200).json({message: "Login successful", type:"success"});

    }catch(error){
        console.log(error.message + "Error from controllers/auth.js");
        res.status(500).json({message:"Error authenticating user", type:"error"});
    }
}```
回答如下:

看起来您正在将模式中的密码转换为小写。删除密码字段中的

lowercase: true
,然后重试。

更多推荐

为什么即使我输入了正确的密码,bcrypt 的比较方法也返回 false?

本文发布于:2024-05-31 01:40:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771142.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:使我   正确   密码   方法   false

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!