Home > Net >  Mysql JWT reporting fails always
Mysql JWT reporting fails always

Time:04-29

i am trying to simulate login using Node.Js , JWT and mysql

i am always getting invalid user and pass, i started to wonder what i was not doing correctly.

My code:

  app.post('/api/v1/user/login', async function(req,res){

    var email = req.body.email;
    var password = req.body.password;

    var hashPass = await bcrypt.hashSync(password,12);
    const bycryptPass = bcrypt.compareSync(password,hashPass);
    dbConn.query('select * from xxxx_users where email =? and password =?',[email,bycryptPass],function(error,results,fields){
        if(results.length > 0){
            const token = jwt.sign({id:row[0].id},'the-super-strong-secrect',{ expiresIn: '1h' });
            res.send({error: false, message: 'OK', token: token})
        }else{
            res.send({error: true, message: 'Invalid User or Pass'})
        }
    })
 })

what am i not doing correctly? Why does it report that the login user and pass is always failed?

CodePudding user response:

Compare hash would give you a boolean result based on the 2 values that you passed into it.

First, you have to get the user record based on the username and then check the password or pass hashed password to the query itself.

const hashPass = await bcrypt.hashSync(password,12);
//const bycryptPass = bcrypt.compareSync(password,hashPass);
 dbConn.query('select * from xxxx_users where email =? and password =?',[email,hashPass],function(error,results,fields){
        if(results.length > 0){
            const token = jwt.sign({id:row[0].id},'the-super-strong-secrect',{ expiresIn: '1h' });
            res.send({error: false, message: 'OK', token: token})
        }else{
            res.send({error: true, message: 'Invalid User or Pass'})
        }
    })

I prefer the following

     const user = await getUserByUsername(loginRequest.userName);
     if (user && compareHash(user.password, loginRequest.password)) {
      //login success access

    }

CodePudding user response:

bcrypt will never produce the same hash for the same password. It's one of its design features.

Your general flow would work for older ways to hash passwords, like md5, sha256, but these are no longer recommended.

The general correct flow for implementing login works roughly like this:

  • Given that you have a username and password
  • Pull out the user record from the database based on the username alone (not the password)
  • Then use the compare function to see if the password the user supplied is comparable to the hash in the database.

It's impossible to select on the password hash, it will always be wrong.

  • Related