Files
server/core/lib/Console/Role/RoleAssignCommand.php
T
Sebastian a723051d11 feat: console role management
Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
2026-07-24 21:58:16 -04:00

103 lines
3.3 KiB
PHP

<?php
declare(strict_types=1);
namespace KTXC\Console\Role;
use KTXC\Stores\UserAccountsStore;
use KTXC\Stores\UserRolesStore;
use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
/**
* Role Assign Command
*
* Assigns a role to a user account.
*/
#[AsCommand(
name: 'role:assign',
description: 'Assign a role to a user',
)]
class RoleAssignCommand extends Command
{
public function __construct(
private readonly UserAccountsStore $userStore,
private readonly UserRolesStore $rolesStore,
private readonly LoggerInterface $logger
) {
parent::__construct();
}
protected function configure(): void
{
$this
->addArgument('tenant', InputArgument::REQUIRED, 'Tenant identifier')
->addArgument('identity', InputArgument::REQUIRED, 'User identity (email/username)')
->addArgument('rid', InputArgument::REQUIRED, 'Role id to assign')
->setHelp('This command assigns a role to a user account.')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$tenant = $input->getArgument('tenant');
$identity = $input->getArgument('identity');
$rid = $input->getArgument('rid');
$io->title('Assign Role');
try {
$user = $this->userStore->fetchByIdentity($tenant, $identity);
if (!$user) {
$io->error("User '{$identity}' not found in tenant '{$tenant}'.");
return Command::FAILURE;
}
if (!$this->rolesStore->fetchByRid($tenant, $rid)) {
$io->error("Role '{$rid}' not found in tenant '{$tenant}'.");
return Command::FAILURE;
}
$roles = (array)($user['roles'] ?? []);
if (in_array($rid, $roles, true)) {
$io->text("User '{$identity}' already has role '{$rid}'.");
return Command::SUCCESS;
}
$roles[] = $rid;
if (!$this->userStore->updateUser($tenant, $user['uid'], ['roles' => array_values($roles)])) {
$io->error("Failed to assign role '{$rid}' to '{$identity}'.");
return Command::FAILURE;
}
$this->logger->info('Role assigned via console', [
'tenant' => $tenant,
'identity' => $identity,
'rid' => $rid,
'command' => $this->getName(),
]);
$io->success("Role '{$rid}' assigned to '{$identity}' successfully!");
return Command::SUCCESS;
} catch (\Throwable $e) {
$io->error('Failed to assign role: ' . $e->getMessage());
$this->logger->error('Role assign failed', [
'tenant' => $tenant,
'identity' => $identity,
'rid' => $rid,
'error' => $e->getMessage(),
]);
return Command::FAILURE;
}
}
}