简体   繁体   English

Bcrypt 比较方法返回 false

[英]Bcrypt compare method returning false

I have read other post in StackOverflow about Bcrypt compare method returning false always.我已经阅读了 StackOverflow 中关于 Bcrypt compare 方法总是返回 false 的其他帖子。 But I can not solve mine with the suggested answers.但我无法用建议的答案解决我的问题。 I am about to give up using Bcrypt.我即将放弃使用 Bcrypt。 Could someone please point out what is wrong in my code.有人可以指出我的代码有什么问题吗? I am simply storing registration data with encrypted password in users array and after login attempt I am trying to compare the user-input password with the saved one in users array.我只是将带有加密密码的注册数据存储在用户数组中,在尝试登录后,我试图将用户输入的密码与保存在用户数组中的密码进行比较。 No matter what I am doing the compare() method is returning false.无论我在做什么, compare()方法都会返回 false。 PLease point out my mistake.请指出我的错误。 I am providing the server.js file and passport.js file here.我在这里提供了server.js文件和passport.js文件。

The server.js -->服务器.js -->

const express = require("express")
const bcrypt = require("bcrypt")
const initializePassport = require("./passport.js")
const flash = require("express-flash")
const session = require("express-session")
const { application } = require("express")
const passport = require("passport")
const server = express()

const users = []
const salt = bcrypt.genSaltSync(10);
initializePassport(
    passport,
    email => users.find(u => u.email === email),
    id => users.find(u => u.id === id)
)

// below line of code is to get the form data in req.body
server.use(express.urlencoded({ extended: false }))
server.use(flash())
server.use(session({
    secret: "1234",
    resave: false, // we want to resave the session variable if nothing is changed
    saveUninitialized: false
}))
server.use(passport.initialize())
server.use(passport.session())


async function main() {
    const PORT = 8080

    server.listen(PORT, function() {
        console.log(`Server started on port ${PORT}...`)
    })
}

server.get('/', async(req, res) => {
    res.render("index.ejs")
})

server.get('/login', (req, res) => {
    res.render('login.ejs')
})
server.post('/login', passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/login",
    failureFlash: true
}))
server.get('/registration', (req, res) => {
    res.render('registration.ejs')
})

server.post('/registration', async(req, res) => {
    const { firstName, lastName, email, password } = req.body
    await bcrypt.hash(password.toString(), salt)
        .then((hashedPassword) => {
            // Store the hashed password in the users array
            users.push({
                id: Date.now().toString(),
                email: email,
                password: hashedPassword,
                firstName: firstName,
                lastName: lastName
            })
            console.log(users)
            res.redirect("/login")
        })
        .catch((error) => {
            console.log(error);
        });
})

main();

The passport.js file --> passport.js文件 -->

const LocalStrategy = require("passport-local").Strategy
const bcrypt = require("bcrypt")


function initialize(passport, getUserByEmail, getUserById) {
    // Function to authenticate users
    const authenticateUsers = async(email, password, done) => {
        // Get users by email
        const user = await getUserByEmail(email)
        console.log("THE Password BEFORE COMPARISON --> " + password)
        console.log(user)
        if (user == null) {
            console.log("user null;;;lllll")
            return done(null, false, { message: "User is not registered" })
        }
        bcrypt.compare(password.toString().trim(), user.password, function(err, result) {
            console.log("THE PASSWORD AFTER COMPARISON --> " + password)
            console.log(user)
            if (err) {
                console.log(err)
            }
            if (result == true) {
                console.log("PASSWORD MATCHES")
            } else {
                console.log("DOESNOT MATCH")
            }
        })
    }

    passport.use(new LocalStrategy({ usernameField: 'email' }, authenticateUsers))
    passport.serializeUser((user, done) => {
        console.log(`---------------> Serialize User`)
        console.log(user)
        done(null, user.id)
    })
    passport.deserializeUser((id, done) => {
        console.log("---------> Deserialize Id")
        console.log(id)
        return done(null, getUserById(id))
    })
}

module.exports = initialize

And here is the registration view这是注册视图

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Registration</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
        <style>
            .main {
                background-color: #EAF7FF;
                width: 100%;
                height: 100vh;
                margin: auto;
            }
            
            .form-container {
                background-color: rgb(255, 255, 255);
                max-width: 500px;
                margin: 0 auto;
                padding: 30px;
                border: 1px solid #ccc;
                border-radius: 10px;
                box-shadow: 0 0 10px #ccc;
            }
            
            .btn {
                background-color: #4F95FF;
                border-radius: 14px;
            }
        </style>
    </head>

    <body>
        <div class="main">
            <div class="form-container">
                <form action="/registration" method="POST">
                    <% if(messages.error) { %>
                        <div class="alert alert-danger" role="alert">
                            <strong><%= messages.error %></strong>
                        </div>
                        <% } %>
                            <h2 class="text-center">Register</h2>
                            <div class="form-group">
                                <input type="text" name="firstName" class="form-control" id="firstName" placeholder="First name">
                            </div>
                            <div class="form-group">
                                <input type="text" name="lastName" class="form-control" id="lastName" placeholder="Last name">
                            </div>
                            <div class="form-group">
                                <input type="email" name="email" class="form-control" id="email" placeholder="Email">
                            </div>
                            <div class="form-group">
                                <input type="password" name="password" class="form-control" id="password" placeholder="Password">
                            </div>
                            <div class="form-group">
                                <input type="password" name="password" class="form-control" id="password" placeholder="Confirm Password">
                            </div>
                            <div class="text-center">
                                <button type="submit" class="btn btn-primary btn-rounded btn-lg">Create Account</button>
                            </div>
                            <div class="text-center">
                                <p>Already have an account?
                                    <a href="login">Login</p>
                </div>
            </form>
        </div>
        </div>
    </body>

</html>

Actually I found the issue.其实我发现了问题。 Its in frontend.它在前端。 I used same "name" and "id" attribute for password and confirmPassword field.我对密码和 confirmPassword 字段使用了相同的“name”和“id”属性。 So req.body.password was appending password from both field.所以 req.body.password 是从两个字段附加密码。

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

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