Adding Salt to Authorization
Now we need to change the authorization. The changes here will be more significant.
It will no longer be possible to check the correctness of the login-password pair immediately with a single query. Why: because to check the password, we need to get its salted hash, and the salt is stored in the database and is unique for each login.
We will have to first get the record only by the login, read the salt, salt the entered password, compare it with the salted password from the database, and only if they match, authorize the user.
Please note that it might be the case that the login was entered incorrectly. In this case, there is no need to check the password, and we can immediately output that authorization is not possible - the data is incorrect:
<?php
$login = $_POST['login'];
$query = "SELECT * FROM users WHERE login='$login'";
$res = mysqli_query($link, $query);
$user = mysqli_fetch_assoc($res);
if (!empty($user)) {
// there is a user with this login, now we need to check the password...
} else {
// there is no user with this login, output a message
}
?>
Let's add the password check:
<?php
$login = $_POST['login'];
$query = "SELECT * FROM users WHERE login='$login'";
$res = mysqli_query($link, $query);
$user = mysqli_fetch_assoc($res);
if (!empty($user)) {
$salt = $user['salt']; // salt from the DB
$hash = $user['password']; // salted password from the DB
$password = md5($salt . $_POST['password']); // salted password from the user
// Compare the salted hashes
if ($password == $hash) {
// everything is ok, authorize...
} else {
// the password didn't match, output a message
}
} else {
// there is no user with this login, output a message
}
?>
For security reasons, the user is usually not told what exactly was wrong - the login or the password - to make it harder for hackers to guess login-password pairs. Simply output a message that the login-password pair is incorrect or something along those lines.
Implement the salted password authorization described above. Try to register, log in, make sure everything works.