Skip to content

Commit

Permalink
Merge pull request #9606 from JakubOnderka/cli-role-change
Browse files Browse the repository at this point in the history
new: [CLI] New command to change user role
  • Loading branch information
JakubOnderka committed Mar 4, 2024
2 parents 7d71963 + 6140f8a commit 14f8a71
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions app/Console/Command/UserShell.php
Expand Up @@ -16,7 +16,7 @@ public function getOptionParser()
'help' => __('Get list of user accounts.'),
'parser' => [
'arguments' => [
'userId' => ['help' => __('User ID or e-mail address.'), 'required' => true],
'userId' => ['help' => __('User ID or e-mail address to filter.'), 'required' => false],
],
'options' => [
'json' => ['help' => __('Output as JSON.'), 'boolean' => true],
Expand Down Expand Up @@ -82,6 +82,15 @@ public function getOptionParser()
],
],
]);
$parser->addSubcommand('change_role', [
'help' => __('Change user role.'),
'parser' => [
'arguments' => [
'userId' => ['help' => __('User ID or e-mail address.'), 'required' => true],
'new_role' => ['help' => __('Role ID or Role name.'), 'required' => true],
]
],
]);
$parser->addSubcommand('change_authkey', [
'help' => __('Change authkey. When advanced authkeys are enabled, old authkeys will be disabled.'),
'parser' => [
Expand Down Expand Up @@ -443,6 +452,35 @@ public function change_authkey()
}
}

public function change_role()
{
list($userId, $newRole) = $this->args;
$user = $this->getUser($userId);

if (is_numeric($newRole)) {
$conditions = ['Role.id' => $newRole];
} else {
$conditions = ['Role.name' => $newRole];
}

$newRoleFromDb = $this->User->Role->find('first', [
'conditions' => $conditions,
'fields' => ['Role.id'],
]);

if (empty($newRoleFromDb)) {
$this->error("Role `$newRole` not found.");
}

if ($newRoleFromDb['Role']['id'] == $user['role_id']) {
$this->error("Role `$newRole` is already assigned to {$user['email']}.");
}

$this->User->updateField($user, 'role_id', $newRoleFromDb['Role']['id']);

$this->out("Role changed from `{$user['role_id']}` to `{$newRoleFromDb['Role']['id']}`.");
}

public function user_ips()
{
list($userId) = $this->args;
Expand Down Expand Up @@ -575,7 +613,7 @@ public function expire_authkeys_without_ip_allowlist()
}

/**
* @param string|int $userId
* @param string|int $userId User ID or User e-mail
* @return array
*/
private function getUser($userId)
Expand Down

0 comments on commit 14f8a71

Please sign in to comment.