0

I have a registration page on which users can send a request to the database. Before sending the request I modify the password with salt+hash algorithm.

EXAMPLE FROM DB:

username : aUser1234

password: password12345

hashed: $2b$13$dTbz4IeMdeXkqHwCL7Lzqe8NKNyKBvA2mQWk8gnPDLWc4O6hyvew2

I'm trying to fetch the hashed password from my database but I have three questions for my code.

  1. How to access the hashed password from the database, once verified that the username exists?
  2. How do I then use await bcrypt.compare(password, hashedPassowrd); within getConnection().query()...
  3. Does the router.post callback function needs to be async as well?
router.post('/user_login', async (req, res) => { //Does this needs to be an async callback function?

    const username = req.body.thisUsername; //aUser1234
    const password = req.body.thisPassword; //password12345

    const sqlString = "SELECT username FROM student_demographics WHERE username = ?";

    getConnection().query(sqlString, [username], async (err, results, fields) => {

        if(err){
            res.sendStatus(500);      
        }

        if(results.length){ 

            console.log("NO ERRORS HERE");   //WORKS OKAY UNTIL HERE

            //HOW TO GET HASHED PASSWORD AND STORE IT ON VARIABLE
            const isValid = await bcrypt.compare(password, hashedPassowrd); //ERROR

            if(isValid){
                //PASSWORD MATCHED
                res.redirect('/homePage.html');
                res.end();
            }else{
                //PASSWORD DIDN'T MATCH
                res.redirect('/login.html');
            }
        }else{ //THE USERNAME DOES NOT exists
            console.log("    > The username or password are invalid :(")
            res.redirect('/login.html');
            res.end();
        }
    });
});

1 Answer 1

1

You'll need to select the hashed password from the database for comparison.

Maybe something like this:

router.post("/user_login", (req, res) => {
  const username = req.body.thisUsername; //aUser1234
  const password = req.body.thisPassword; //password12345
  const sqlString = "SELECT hashed_password FROM student_demographics WHERE username = ? LIMIT 1";

  getConnection().query(sqlString, [username], async (err, results, fields) => {
    if (err) {
      console.log(err);
      res.sendStatus(500);
      return;
    }
    if (!results.length) {
      console.log("    > The username is invalid :(");
      res.redirect("/login.html");
      res.end();
      return;
    }
    const [hashedPassword] = results[0];
    const isValid = await bcrypt.compare(password, hashedPassword);
    if (isValid) {
      //PASSWORD MATCHED
      res.redirect("/homePage.html");
      res.end();
    } else {
      console.log("    > The password is invalid :(");
      res.redirect("/login.html");
      res.end();
      return;
    }
  });
});

Note you're not doing anything with the login info, though (you might want to save it in a session or cookie).

Sign up to request clarification or add additional context in comments.

4 Comments

will try that now, and let you know if worked for me. Also I'm aware for the session and planning on working on that soon. Thanks for your reply. Stay tuned :D
Looks like i do get some data back however password is not included. I tried console.log(results) and this is what is printed: [ RowDataPacket { username: 'aUser1234' } ]. results[0] will also return [ RowDataPacket { username: 'aUser1234' } ]
Did you change the query to select the password from the database?
I didn't the first time but have tried that now and get an error when passing results[0] in the comparison as it was not a type of string. This have solved the issue for me const isValid = await bcrypt.compare(password, results[0].password);. Thanks a lot @AKX, you are the best :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.