简体   繁体   中英

bcrypt.compare always returns false

I am trying to get a login function going but when I try to compare password with hashed password it always returns false

This is my registerUser function that holds the hashing

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

This is the login function that holds the compare

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

When I console.log request.body.password and user.password the hashed string is equal to the unhashed string so it should return true

截屏

The hashed string is the same string that is saved in the database

I just found the issue, thank you for your help. in userSchema, password was lowercase:true which caused the issue...

The code looks alright. Do you have multiple users with the same username in your database? The generated hash should be: $2b$12$jgrLYOqnHnJGszlpgo26QuaT29tdxBFguyIttSNOIy/8go1viRrYC

重新创建

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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