Auth\Db: implement update_user()

This commit is contained in:
Benjamin Renard 2024-09-13 18:48:45 +02:00
parent d42a864901
commit 0b84060f2c
Signed by: bn8
GPG key ID: 3E2E1CE1907115BC

View file

@ -8,6 +8,8 @@ use EesyPHP\Log;
use Exception; use Exception;
use function EesyPHP\vardump;
class Db extends Backend { class Db extends Backend {
/** /**
@ -173,6 +175,83 @@ class Db extends Backend {
return false; return false;
} }
/**
* Update a user in database
* @param \EesyPHP\Auth\User $user The user object
* @param array<string,mixed> $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 (!self::check_password($user, $value))
$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] = $value;
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 * CLI command to add user
* @param array $command_args Command arguments * @param array $command_args Command arguments