节点 Bcrypt 比较总是 returns 成功

node Bcrypt compare always returns success

总是当我尝试比较 newUser.password 和 profile.password 时,即使我输入了错误的密码,它也会让我成功

这是我的代码

    const bcrypt = require('bcrypt')

const router = require('express').Router()
// const jwt = require('jsonwebtoken')
let User = require('../models/user.model')

 router.route('/login').post(async(req, res) => {
    var newUser = {};
    newUser.email = req.body.email;

    newUser.password = req.body.password;
    console.log(newUser.password)
     User.findOne({ email: newUser.email })
      .then(profile => {
        if (!profile) {
          res.send("User not exist");

在这里它将为我比较散列通行证和客户提供的通行证

        }else if(bcrypt.compare(newUser.password, profile.password)){
            res.send("success");

到此为止

        }
        else if((newUser.password !== profile.password)){
          res.send("wrong");
          }
      })
      .catch(err => res.status(400).json('Erorr: ' + err))
        
})

router.route('/add').post(async(req, res) => {
  const hashedPassword = await bcrypt.hash(req.body.password, 10)

    const username = req.body.username
    const email = req.body.email
    const password = hashedPassword
    const firstname = req.body.firstname
    const lastname = req.body.lastname

    const newUser = new User({username, email, password, firstname, lastname})
    
    // const accessToken = jwt.sign(password, process.env.ACCESS_TOKEN_SECRET)
    // res.json({ accessToken: accessToken })

    newUser.save()
    .then(() => res.json('User added!'))
    .catch(err => res.status(400).json('Erorr: ' + err))
})

// function authToken(req, res, next){
//     const authHeader = req.headers['authorization']
//     const token = authHeader && authHeader.split(' ')[1]
//     if (token == null ) return res.sendStatus(401)

//     jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, password) => {
//         if (err) return res.sendStatus(403)
//         req.password = password
//         next()
//     })
// }

module.exports = router

可能您正在使用比较和散列的异步您应该使用 then 或 async await 链接 这是您的代码和 运行 mongodb 和节点 user.js

的简短形式
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

let UserSchema = new mongoose.Schema({
    email: String,
    password: String,
});

run().catch((err) => console.log(err));

async function run() {
    await mongoose.connect('mongodb://localhost:27017/test', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    await mongoose.connection.dropDatabase();

    const UserModel = mongoose.model('user', UserSchema);
    const newUser = { email: 'test@test.com', password: 'Alexa123' };
    const hasPassword = bcrypt.hashSync(newUser.password, 10);
    const user = new UserModel({ email: newUser.email, password: hasPassword });
    await user.save();

    const getUser = await UserModel.findOne({ email: 'test@test.com' }).exec();
    console.log(getUser);
    // put password wrong here you will get result as expected
    if (bcrypt.compareSync('Alexa123', getUser.password)) {
        console.log('password matched');
    } else {
        console.log('password is wrong');
    }
}

bcrypt.compare 是异步的,所以使用 asyncawait 关键字。试试这个,

newUser.password = req.body.password;
console.log(newUser.password)
 User.findOne({ email: newUser.email })
  //async keyword below
  .then(async profile => {
    if (!profile) {
      res.send("User not exist");

  //await keyword below
}else if(await bcrypt.compare(newUser.password, profile.password)){
        res.send("success");