From 4a2060458dec277434a5fa5b87377a0e4f0ad4ba Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Fri, 13 Sep 2024 18:48:45 +0200 Subject: [PATCH] Auth\Db: implement update_user() --- src/Auth/Db.php | 79 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/src/Auth/Db.php b/src/Auth/Db.php index a6d694e..fb6a52a 100644 --- a/src/Auth/Db.php +++ b/src/Auth/Db.php @@ -8,6 +8,8 @@ use EesyPHP\Log; use Exception; +use function EesyPHP\vardump; + class Db extends Backend { /** @@ -173,6 +175,83 @@ class Db extends Backend { return false; } + /** + * Update a user in database + * @param \EesyPHP\Auth\User $user The user object + * @param array $changes Array of changes + * @param boolean $no_change_as_success Consider no change provided as success + * (optional, default: false) + * @return boolean True if user was updated, false otherwise + */ + public static function update_user($user, $changes, $no_change_as_success=False) { + Log::debug("update_user(%s): changes=%s", $user->username, vardump($changes)); + if (!$user->username) { + Log::error("update_user(): Invalid user provided (no username)"); + return false; + } + if (!is_array($changes)) { + Log::error("update_user(%s): Invalid changes provided (not an array)", $user->username); + return false; + } + $values = []; + foreach($changes as $field => $value) { + switch ($field) { + case "username": + if ($value != $user->username) { + // Check username uniqueness + if (self :: get_user($value)) { + Log :: error( + "update_user(%s): invalid new username '%s': another user with this username already exist", + $user->username, + $value + ); + return false; + } + $values[self :: $username_field] = $value; + } + break; + case "password": + if (!password_verify($value, $user["password"])) + $values[self :: $password_field] = password_hash( + $value, + constant('PASSWORD_'.strtoupper(App::get('auth.db.password_hash_algo'))) + ); + break; + default: + if (in_array($field, App :: get('auth.db.exposed_fields'))) { + if ($value != $user[$field]) + $values[$field] = $values; + break; + } + Log :: error("update_user: unknown field %s", $field); + return false; + } + } + + if (empty($values)) { + Log::log( + $no_change_as_success?"DEBUG":"ERROR", + "update_user(%s): no change", + $user->username + ); + return $no_change_as_success; + } + + Log::debug("update_user(%s): changes=%s", $user->username, vardump($values)); + if ( + self :: $class :: update( + self :: $users_table, + $values, + [App::get('auth.db.username_field') => $user->username] + ) + ) { + Log :: info('update_user(%s): user updated', $user->username); + return true; + } + Log :: error('update_user(%s): error adding user', $user->username); + return false; + } + /** * CLI command to add user * @param array $command_args Command arguments