From c684f3535a2c8edc4f872efc71867f6c934233f4 Mon Sep 17 00:00:00 2001 From: Niklas Bittner Date: Sun, 25 Feb 2024 23:38:53 +0100 Subject: [PATCH] feat: migrate to bcrypt for passwords --- src/classes/wishthis/User.php | 48 +++++++++++++++++++++++++++++------ src/pages/login.php | 2 +- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/src/classes/wishthis/User.php b/src/classes/wishthis/User.php index cfd1b89a..e9f67eab 100644 --- a/src/classes/wishthis/User.php +++ b/src/classes/wishthis/User.php @@ -35,10 +35,16 @@ class User } public static function passwordToHash(string $plainPassword): string + { + return password_hash($plainPassword, PASSWORD_BCRYPT); + } + + public static function passwordToOldHash(string $plainPassword): string { return sha1($plainPassword); } + public static function getCurrent(): self { if (!isset($_SESSION['user'])) { @@ -363,6 +369,22 @@ class User ?: $this->email; } + public function updatePasswordHash(string $password, string $email): string { + global $database; + $passwordHash = User::passwordToHash($password); + + $database->query( + 'UPDATE `users` + SET `password` = :password_hash + WHERE `email` = :user_email', + [ + "user_email" => $email, + "password_hash" => $passwordHash + ] + ); + return $passwordHash; + } + /** * Attempts to log in the user. Return whether it was successful or not. * @@ -392,11 +414,9 @@ class User ->query( 'SELECT * FROM `users` - WHERE `email` = :user_email - AND `password` = :user_password;', + WHERE `email` = :user_email', [ - 'user_email' => $email, - 'user_password' => $password, + 'user_email' => $email ] ) ->fetch(\PDO::FETCH_ASSOC); @@ -409,6 +429,20 @@ class User return false; } + $passwordHash = User::passwordToOldHash($password); + + if ($passwordHash === $user_database_fields["password"]) { + $passwordHash = User::updatePasswordHash($password, $email); + } else { + $passwordHash = $user_database_fields["password"]; + } + + $password_matches = password_verify($password, $passwordHash); + + if(!$password_matches) { + return false; + } + /** * Update the `last_login` column. */ @@ -416,11 +450,9 @@ class User ->query( 'UPDATE `users` SET `last_login` = NOW() - WHERE `email` = :user_email - AND `password` = :user_password;', + WHERE `email` = :user_email', [ - 'user_email' => $email, - 'user_password' => $password, + 'user_email' => $email ] ); $user_database_fields['last_login'] = date('Y-m-d H:i'); diff --git a/src/pages/login.php b/src/pages/login.php index 3736a175..6040bcc7 100644 --- a/src/pages/login.php +++ b/src/pages/login.php @@ -15,7 +15,7 @@ $page = new Page(__FILE__, __('Login')); */ if (isset($_POST['login'], $_POST['email'], $_POST['password'])) { $user_email = \filter_input(\INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); - $user_password = User::passwordToHash($_POST['password']); + $user_password = $_POST['password']; $userLoginIsPersistent = isset($_POST['persistent']); $user->login($user_email, $user_password, $userLoginIsPersistent);