Bcrypt error: illegal arguments String unidentified

后端 未结 8 1988
误落风尘
误落风尘 2021-01-17 10:49

here is my complete code

var express = require(\'express\'),
    app = express(),
    mongoose = require(\'mongoose\'),
    bodyParser = require(\'body-parse         


        
相关标签:
8条回答
  • 2021-01-17 11:12

    Your code is wrong in this place. You may see it.

    var validPassword = user.comparePassword(req.body.password);
    

    If you use bcryptjs thrid party plugins, like that

    let validPassword = bcrypt.compare(req.body.password, user.password);
    

    bcrypt.compare(password, hashedPassword);

    0 讨论(0)
  • 2021-01-17 11:16

    I also encountered the same error when I was using bcrypt.compareSync("input to be compared with the hash", hash).

    Later on I discovered that I was supposed to pass the actual value in the first input parameter i.e (The actual value from which the hash was generated) and the hash in the second input parameter, but I was passing hashed values in both the input parameters.

    After correcting the same it was giving me the desired output as true or false.

    You can also run and check your code here.

    0 讨论(0)
  • 2021-01-17 11:20

    In your User Schema, you are setting select to false for the password field. This means that anytime you look for a user in the schema as you're trying to do in the login request, you won't get the value of the password field or any other field that has select false defined in the schema.

    What you need to do is to specify you need the password when the user is found:

    app.post('/login', function(req, res){
      userModel.findOne({username: req.body.username}, 'password', function(err, user){
       // continue
    }
    
    

    This will return only the _id and the password from the DB. If you want to return other fields, you'd have to add them in:

    app.post('/login', function(req, res){
      userModel.findOne({username: req.body.username}, 'password firstName lastName email', function(err, user){
       // continue
    }
    
    
    0 讨论(0)
  • 2021-01-17 11:21

    You need to specify that you also want the password because you have set the select property to false on password. So when you are fetching the user, just make sure to explicitly specify that you also want the password. Add .select('+password') on the user object when you are querying a user.

    0 讨论(0)
  • 2021-01-17 11:22

    Do like this:

    UserSchema.pre('save', async function (next) {
      const hash = await bcrypt.hash(this.password, 10);
    
      this.password = hash;
      next()
    })
    
    0 讨论(0)
  • 2021-01-17 11:27

    In my particular case, I was dealing with this error, checking out all the code up and down unsuccessfully for almost two days. Finally, realized that the column PASSWORD in MariaDB was in uppercase. Theoretically that shouldn't affect at all, but I decided to rename it to lowercase and bum! problem solved.

    0 讨论(0)
提交回复
热议问题