Files
2026-07-20 23:53:40 -04:00

103 lines
3.5 KiB
PHP

<?php
declare(strict_types=1);
namespace KTXM\AuthenticationProviderPassword\Console;
use KTXC\Service\TenantService;
use KTXC\Stores\UserAccountsStore;
use KTXM\AuthenticationProviderPassword\Provider;
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;
/**
* User Password Command
*
* Sets or updates the password credential for a user account.
*/
#[AsCommand(
name: 'user:password',
description: 'Set or update the password credential for a user',
)]
class UserPasswordCommand extends Command
{
public function __construct(
private readonly Provider $provider,
private readonly TenantService $tenantService,
private readonly UserAccountsStore $userStore,
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('password', InputArgument::OPTIONAL, 'Password (prompted for interactively when omitted)')
->setHelp('This command sets or updates the password credential for a user account. Omit the password argument to be prompted securely.')
;
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$tenant = $input->getArgument('tenant');
$identity = $input->getArgument('identity');
$password = $input->getArgument('password');
$io->title('Set User Password');
try {
if (!$this->tenantService->fetchById($tenant)) {
$io->error("Tenant '{$tenant}' not found.");
return Command::FAILURE;
}
if (!$this->userStore->fetchByIdentity($tenant, $identity)) {
$io->error("User '{$identity}' not found in tenant '{$tenant}'.");
return Command::FAILURE;
}
if ($password === null) {
$password = $io->askHidden('Password');
}
if (empty($password)) {
$io->error('Password cannot be empty.');
return Command::FAILURE;
}
if (!$this->provider->setCredential($tenant, $identity, $password)) {
$io->error("Failed to store password credential for '{$identity}'.");
return Command::FAILURE;
}
$this->logger->info('User password credential set via console', [
'tenant' => $tenant,
'identity' => $identity,
'command' => $this->getName(),
]);
$io->success("Password credential for '{$identity}' stored successfully!");
return Command::SUCCESS;
} catch (\Throwable $e) {
$io->error('Failed to set password: ' . $e->getMessage());
$this->logger->error('User password set failed', [
'tenant' => $tenant,
'identity' => $identity,
'error' => $e->getMessage(),
]);
return Command::FAILURE;
}
}
}