0
req.body = {
  username: 1,
  password: 1
}

conn.query('INSERT INTO user SET username = ?, password = PASSWORD(?)',
  [req.body.username, req.body.password])

When using MySQL for Nodejs, we can do the above to insert an user.

However, the following is much cleaner (allows more fields to be set by adding to req.body without altering the code):

conn.query('INSERT INTO user SET ?', req.body)

But how do we solve the problem of needing to call PASSWORD() on the req.body.password field?

Avery235
  • 4,756
  • 12
  • 49
  • 83
  • conn.query('INSERT INTO user SET ?', req.body.username, PASSWORD(req.body.password)); , check if this working for you – Deep Kakkar Dec 30 '17 at 12:33
  • @Deep `PASSWORD()` is a MySQL function, not a JS function. Your code will give `PASSWORD` is undefined. – Avery235 Dec 30 '17 at 12:36
  • 2
    You should not use MySQL's PASSWORD function for your application.. MySQL's PASSWORD function is designed for the authentication system in MySQL Server read ( https://dev.mysql.com/doc/refman/5.7/en/encryption-functions.html#function_password ) ... Your better off searching for a JavaScript library that supports bcrypt.( https://www.google.nl/search?q=javascript+bcrypt ) – Raymond Nijland Dec 30 '17 at 12:48
  • @RaymondNijland didn't notice that, thanks. Seems like i can just switch to `SHA2` though https://dev.mysql.com/doc/refman/5.7/en/encryption-functions.html#function_sha2 – Avery235 Dec 30 '17 at 13:13
  • SHA2 isn't really safe without using a salt that is atleast 32 chars . There are rainbow tables containing a lot off SHA2 strings.. Besides SHA2 is a fast hashing algorithm that also runs extremely fast op GPU's (bruteforcing +200 Billion hashes per second on hardware that is over 5 years old).. Bcrypt is designed to be a slow algorithm and also it runs slow on GPU's besides Bcrypt generates hashes that are different each time even on the same data meaning the cracker/hacker can't use rainbow tables. – Raymond Nijland Dec 30 '17 at 13:23
  • @RaymondNijland why does SSL cert use SHA2 then? What's the difference between SSL cert and password hashing that makes password requiring greater security? – Avery235 Dec 30 '17 at 13:37
  • 1
    When you generate a SSL cert you generate one with a random generated salt.. some SSL program's (like PuttyGen) also use random mouse positions to use as seed for the salt.. i already said that SHA2 is safe when you use a salt doensn't matter when you hash passwords for a application or use it in a cert. – Raymond Nijland Dec 30 '17 at 13:45

1 Answers1

1

No, You can not use a MySQl function like this inside a JavaScript code.

The first approach which you are following is the only way which you have to follow.

req.body = {
  username: 1,
  password: 1
}

conn.query('INSERT INTO user SET username = ?, password = PASSWORD(?)',
  [req.body.username, req.body.password])
Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75