Login Post Request, unable to authenticate users with nodejs Oracledb

38 Views Asked by At

I am passing user credentials (username & password) through a login form post request and trying to check against the database (oracledb) and if the credentials match then render another page.

However i keep getting an "Authentication failed" error despite the credentials matching

 app.post("/", async function(req, res) {
   
    let connection;  
        const {username,password}=req.body;
        const sqlquery = 'SELECT COUNT(*) AS userCount FROM USERS WHERE EMAIL = :username AND PASSWORD = :password';
       connection = await oracledb.getConnection(dbConfig);

      let result = await connection.execute(
       sqlquery , {username,password} ,function(err,result){
           if (err) {
               console.error('Error executing the query:', err);
               return res.status(500).send('Internal server error');
             }
      const userCount = result.rows[0];
      console.log(userCount);
      if (userCount === 1) {
       return res.render("playercentre");
      } else {
       return res.status(401).send('Authentication failed');
      }
       }
       
      );
      
  });

The console.log(userCount) returns 1 but still i get the error instead of rendering the page. Not sure where i am missing something.

1

There are 1 best solutions below

0
Tzahi Leh On

I suggest to read this great post about loose vs strict equality.
Briefly, loose (==) checks the value, and performs type coercion if necessary.
Strict (===) checks both the value and the type

In your case, I assume result.rows[0] returned the string "1".
Although 1 == "1" results in true because the value is 1, 1 === "1" result in false because one is a number, and the second is a string.

There are other ways to fix it rather than change your condition to loose equality.
Otherwise, it might cause some unexpected bugs in the future.
Generally speaking, in case result.rows[0] returned true or the string "1", it could be something you want to detect, and maybe throw an error (for this unexpected value in the row).