I was curious when I been using Django and found that the user data and authentication credentials were in different tables. Unfortunately I never understood how this worked, but I imagine through relationships.
My database is in MySQL and I have created the users table with the user data, then I have created another table called auth with its respective field, id, salt and hash which is what I am interested in saving. I have also created a field called user_id to relate to the user in the users table with the id (I don't know if it's fine like that).
Now, I have a function in my NodeJS code that is responsible for saving the data received by the network layer:
function insert (table, data) {
return new Promise((resolve, reject) => {
connection.query(`INSERT INTO ${table} SET ?`, data, (err, data) => {
if (err) return reject(err)
resolve(data)
})
})
}
has that structure so that it is reusable at all times.
On the other hand I have the controller that handles the business logic of the data received by the network layer:
function insert (user) {
if (!user) {
throw dataMissed
}
bcrypt.genSalt(1000, function(err, salt) {
if (err) throw err
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) throw err
user = {
name: user.name,
email: user.email,
position: user.position,
hash,
salt
}
return store.insert(collection, user)
})
})
}
Unlike the function that is dedicated to saving the data in the database, this one is unique since the logic will depend on the data, obviously.
And the problem I have is that I don't know how to save the generated salt and the hash in the corresponding table. As you can see, I use the same function to save both but it gives me an error, since it is a logic that does not work.
How do I save a value that will later be referenced by another table?