Home > Software engineering >  How do I get the value of an Array without knowing the name of the Array
How do I get the value of an Array without knowing the name of the Array

Time:07-04

im currently working on a user authentication system using expressJS. Therefore to encrypt my data I am using bcrypt. Then I save the encrypted data to a MySQL Database. Then when logging in I get the saved password using SELECT password FROM USERS WHERE email=${emailUserEntered}. Well that works but it gives me this output:

[
  {
    password: '$2b$10$MyvQenconTHygpwbY/1ExampleHashYju2i8Bq'
  }
]

My code:

  let userPassword = await db.promise().query(`SELECT password FROM USERS WHERE email='${req.body.email}';`);
  const data = userPassword[0].password;
  console.log(data)


  var result = bcrypt.compareSync(req.body.password, data);
  if (result) {
    res.send('SUCCESS!');
  } else {
    res.send('WRONG!');
  }

How can only get the actual hash as a String and not the brackets and all that?
Thanks in advance, have a nice day

CodePudding user response:

I suspect your library's query() might be returning a [rows, fields] array.
mysql2's query() does, at least.

Maybe the below?:

  let [rows, fields] = await db.promise().query(`SELECT password FROM USERS WHERE email='${req.body.email}';`);
  const password = rows[0].password;
  console.log(password)

Warning: also, the above code may potentially lead to a frightful SQL injection depending on what may hide under the req.body.email. Please take a look at the Prepared Statements to mitigate this. More info: How can prepared statements protect from SQL injection attacks?.

CodePudding user response:

I guess you are using JavaScript, so you can do something like that

const {password} = JSON.parse(JSON.stringify(SQL_QUERY_RES).then(items=>items[0])

or

const data = JSON.parse(JSON.stringify(SQL_QUERY_RES))[0].password
  • Related