Is this approach safe to SQL Injections?

I have the following code to retrieve data from my database in Express.js with MySQL queries. I used to develop on vanilla HTML, JS, PHP… Now I’m using React and Express.js for the Back End and these two languages are a new world to me. What I want to know is if making queries like this are a thing safe to do.

Much appreciated, thanks for the help.

const db = mysql.createConnection({
  host: process.env.DATABASE_HOST,
  user: process.env.DATABASE_USER,
  password: process.env.DATABASE_PASSWORD,
  database: process.env.DATABASE_NAME
});

exports.sesion = async (req, res) => {

  console.log(req.body);

  try {   
    const { email, password } = req.body[0];

    if(!email || !password) {
      res.json({
        message: 'Por favor introduzca su email y contraseña'
      })
    }

    db.query('SELECT * FROM usuarios WHERE email = ?', [email], async (error, filas, fields) => {
      
      if(filas.length === 0) {
        res.json([
          {message: 'Los datos ingresados son incorrectos'}
        ])
      }
      else if(filas && !(await bcrypt.compare(password, filas[0].password))) {
        res.json([
          {message: 'Los datos ingresados son incorrectos'}
        ])
      }
      else {
        res.json([
          {message: 'Inicio de sesión correcto'}
        ])
      }
    })

  }
  catch (error) {
    console.log(error);
  }
  
}

Answer

Yes this is safe. You parameterized the user’s input, so it’s safe against SQL injection.

For even more safety you could validate the email from the user with one of those vast regexes designed for the purpose, like this one. https://emailregex.com/

Leave a Reply

Your email address will not be published. Required fields are marked *