Strange nodejs behaviour when logging in a user

Viewed 32

The problem is that it shows that it is successfully logged in (201) without the redirect code, but with it, it shows a 302 error and the email_address is undefined. What could be the problem here? I still can't come to a conclusion.

The problem may be in the order of the code I guess?

const login = async (req, res, next) => {

const { email_address, password, user_email, user_password}: { email_address: string, password: string, user_email: string, user_password: string } = req.body;

try {
  const userWithDetails = 'SELECT * FROM users WHERE email_address = user_email AND password = user_password'; //w form info 
  if (userWithDetails) {
  req.session.loggedin = true; //true
  req.session.email_address = email_address; //undefined
    console.log(req.session.email_address)
  // return res.redirect('./index.html')
}
  res.status(201).send('Succesfully signed in');
    // res.status(403).send('Password is not correct');
} catch(error) {
    res.status(404).send(`User with email ${email_address} not found!`);   
}

  await next;
};

NEW CODE ***

const login = async (req, res, next) => {

const { email_address, password}: { email_address: string, password: string} = req.body;

  const userWithDetails = 'SELECT * FROM users WHERE email_address = ?';
  return con.query(userWithDetails, email_address, (err, results) => {
    if (err) {
      console.error(err);
    }
    const user = results.find(emailObj => emailObj.email_address === email_address);
      if (results && results.length && user.email_address) {
        req.session.loggedin = true;
        req.session.email_address = email_address;
        const matchPassword: boolean = bcrypt.compareSync(password, user.password);
        if (matchPassword) {
          const token = jwt.sign({ user }, 'aaaa', { expiresIn: '1h'});
          res.status(200).send({message: 'Logged in', token: token});

        } else {
          res.status(403).send('Password is not correct');
        }

      } else {
        res.status(404).send(`User with email ${email_address} not found!`);   
      } 
});
await next;

}

1 Answers

You don't execute your sql query at any point.

You just say :

query = 'select blabla'
if(query){...}

Of course this will always be true. You want to run the query on your database.

Also in your query you don't properly use the variables, see string formatting :

let my_var = `SELECT xxx from xxx where username = '${username}'`

Also please sanitize the parameters to prevent SQL Injection...

Related