Refactors user_ldap app commands.

To improve code readability.

Signed-off-by: Faraz Samapoor <f.samapoor@gmail.com>
Co-authored-by: Côme Chilliet <91878298+come-nc@users.noreply.github.com>
pull/39928/head
Faraz Samapoor 2024-01-24 11:08:56 +07:00 committed by Côme Chilliet
parent 5238b1c64c
commit f03781b509
12 changed files with 143 additions and 223 deletions

@ -106,20 +106,22 @@ class CheckGroup extends Command {
$this->service->handleCreatedGroups([$gid]);
}
}
return 0;
} elseif ($wasMapped) {
return self::SUCCESS;
}
if ($wasMapped) {
$output->writeln('The group does not exist on LDAP anymore.');
if ($input->getOption('update')) {
$this->backend->getLDAPAccess($gid)->connection->clearCache();
$this->service->handleRemovedGroups([$gid]);
}
return 0;
} else {
throw new \Exception('The given group is not a recognized LDAP group.');
return self::SUCCESS;
}
throw new \Exception('The given group is not a recognized LDAP group.');
} catch (\Exception $e) {
$output->writeln('<error>' . $e->getMessage(). '</error>');
return 1;
return self::FAILURE;
}
}

@ -37,23 +37,15 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class CheckUser extends Command {
/** @var User_Proxy */
protected $backend;
protected User_Proxy $backend;
/** @var Helper */
protected $helper;
/** @var DeletedUsersIndex */
protected $dui;
/** @var UserMapping */
protected $mapping;
public function __construct(User_Proxy $uBackend, Helper $helper, DeletedUsersIndex $dui, UserMapping $mapping) {
public function __construct(
User_Proxy $uBackend,
protected Helper $helper,
protected DeletedUsersIndex $dui,
protected UserMapping $mapping,
) {
$this->backend = $uBackend;
$this->helper = $helper;
$this->dui = $dui;
$this->mapping = $mapping;
parent::__construct();
}
@ -98,19 +90,21 @@ class CheckUser extends Command {
if ($input->getOption('update')) {
$this->updateUser($uid, $output);
}
return 0;
} elseif ($wasMapped) {
return self::SUCCESS;
}
if ($wasMapped) {
$this->dui->markUser($uid);
$output->writeln('The user does not exists on LDAP anymore.');
$output->writeln('Clean up the user\'s remnants by: ./occ user:delete "'
. $uid . '"');
return 0;
} else {
throw new \Exception('The given user is not a recognized LDAP user.');
return self::SUCCESS;
}
throw new \Exception('The given user is not a recognized LDAP user.');
} catch (\Exception $e) {
$output->writeln('<error>' . $e->getMessage(). '</error>');
return 1;
return self::FAILURE;
}
}

@ -32,18 +32,13 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class CreateEmptyConfig extends Command {
/** @var \OCA\User_LDAP\Helper */
protected $helper;
/**
* @param Helper $helper
*/
public function __construct(Helper $helper) {
$this->helper = $helper;
public function __construct(
protected Helper $helper,
) {
parent::__construct();
}
protected function configure() {
protected function configure(): void {
$this
->setName('ldap:create-empty-config')
->setDescription('creates an empty LDAP configuration')
@ -67,6 +62,6 @@ class CreateEmptyConfig extends Command {
$prose = 'Created new configuration with configID ';
}
$output->writeln($prose . "{$configPrefix}");
return 0;
return self::SUCCESS;
}
}

@ -31,18 +31,13 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DeleteConfig extends Command {
/** @var \OCA\User_LDAP\Helper */
protected $helper;
/**
* @param Helper $helper
*/
public function __construct(Helper $helper) {
$this->helper = $helper;
public function __construct(
protected Helper $helper,
) {
parent::__construct();
}
protected function configure() {
protected function configure(): void {
$this
->setName('ldap:delete-config')
->setDescription('deletes an existing LDAP configuration')
@ -54,18 +49,17 @@ class DeleteConfig extends Command {
;
}
protected function execute(InputInterface $input, OutputInterface $output): int {
$configPrefix = $input->getArgument('configID');
$success = $this->helper->deleteServerConfiguration($configPrefix);
if ($success) {
$output->writeln("Deleted configuration with configID '{$configPrefix}'");
return 0;
} else {
if (!$success) {
$output->writeln("Cannot delete configuration with configID '{$configPrefix}'");
return 1;
return self::FAILURE;
}
$output->writeln("Deleted configuration with configID '{$configPrefix}'");
return self::SUCCESS;
}
}

@ -36,18 +36,11 @@ use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
class ResetGroup extends Command {
private IGroupManager $groupManager;
private GroupPluginManager $pluginManager;
private Group_Proxy $backend;
public function __construct(
IGroupManager $groupManager,
GroupPluginManager $pluginManager,
Group_Proxy $backend
private IGroupManager $groupManager,
private GroupPluginManager $pluginManager,
private Group_Proxy $backend,
) {
$this->groupManager = $groupManager;
$this->pluginManager = $pluginManager;
$this->backend = $backend;
parent::__construct();
}
@ -96,16 +89,16 @@ class ResetGroup extends Command {
echo "calling delete $gid\n";
if ($group->delete()) {
$this->pluginManager->setSuppressDeletion($pluginManagerSuppressed);
return 0;
return self::SUCCESS;
}
} catch (\Throwable $e) {
if (isset($pluginManagerSuppressed)) {
$this->pluginManager->setSuppressDeletion($pluginManagerSuppressed);
}
$output->writeln('<error>' . $e->getMessage() . '</error>');
return 1;
return self::FAILURE;
}
$output->writeln('<error>Error while resetting group</error>');
return 2;
return self::INVALID;
}
}

@ -36,25 +36,15 @@ use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
class ResetUser extends Command {
/** @var DeletedUsersIndex */
protected $dui;
/** @var IUserManager */
private $userManager;
/** @var UserPluginManager */
private $pluginManager;
public function __construct(
DeletedUsersIndex $dui,
IUserManager $userManager,
UserPluginManager $pluginManager
protected DeletedUsersIndex $dui,
private IUserManager $userManager,
private UserPluginManager $pluginManager,
) {
$this->dui = $dui;
$this->userManager = $userManager;
$this->pluginManager = $pluginManager;
parent::__construct();
}
protected function configure() {
protected function configure(): void {
$this
->setName('ldap:reset-user')
->setDescription('deletes an LDAP user independent of the user state')
@ -96,16 +86,16 @@ class ResetUser extends Command {
$pluginManagerSuppressed = $this->pluginManager->setSuppressDeletion(true);
if ($user->delete()) {
$this->pluginManager->setSuppressDeletion($pluginManagerSuppressed);
return 0;
return self::SUCCESS;
}
} catch (\Throwable $e) {
if (isset($pluginManagerSuppressed)) {
$this->pluginManager->setSuppressDeletion($pluginManagerSuppressed);
}
$output->writeln('<error>' . $e->getMessage() . '</error>');
return 1;
return self::FAILURE;
}
$output->writeln('<error>Error while resetting user</error>');
return 2;
return self::INVALID;
}
}

@ -39,21 +39,15 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class Search extends Command {
/** @var \OCP\IConfig */
protected $ocConfig;
/** @var User_Proxy */
private $userProxy;
/** @var Group_Proxy */
private $groupProxy;
public function __construct(IConfig $ocConfig, User_Proxy $userProxy, Group_Proxy $groupProxy) {
public function __construct(
protected IConfig $ocConfig,
private User_Proxy $userProxy,
private Group_Proxy $groupProxy,
) {
parent::__construct();
$this->ocConfig = $ocConfig;
$this->userProxy = $userProxy;
$this->groupProxy = $groupProxy;
}
protected function configure() {
protected function configure(): void {
$this
->setName('ldap:search')
->setDescription('executes a user or group search')
@ -87,11 +81,10 @@ class Search extends Command {
/**
* Tests whether the offset and limit options are valid
* @param int $offset
* @param int $limit
*
* @throws \InvalidArgumentException
*/
protected function validateOffsetAndLimit($offset, $limit) {
protected function validateOffsetAndLimit($offset, $limit): void {
if ($limit < 0) {
throw new \InvalidArgumentException('limit must be 0 or greater');
}
@ -135,6 +128,6 @@ class Search extends Command {
$line = $name . ($printID ? ' ('.$id.')' : '');
$output->writeln($line);
}
return 0;
return self::SUCCESS;
}
}

@ -35,7 +35,7 @@ use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class SetConfig extends Command {
protected function configure() {
protected function configure(): void {
$this
->setName('ldap:set-config')
->setDescription('modifies an LDAP configuration')
@ -63,7 +63,7 @@ class SetConfig extends Command {
$configID = $input->getArgument('configID');
if (!in_array($configID, $availableConfigs)) {
$output->writeln("Invalid configID");
return 1;
return self::FAILURE;
}
$this->setValue(
@ -71,16 +71,13 @@ class SetConfig extends Command {
$input->getArgument('configKey'),
$input->getArgument('configValue')
);
return 0;
return self::SUCCESS;
}
/**
* save the configuration value as provided
* @param string $configID
* @param string $configKey
* @param string $configValue
*/
protected function setValue($configID, $key, $value) {
protected function setValue(string $configID, string $key, string $value): void {
$configHolder = new Configuration($configID);
$configHolder->$key = $value;
$configHolder->saveConfiguration();

@ -36,18 +36,13 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ShowConfig extends Base {
/** @var \OCA\User_LDAP\Helper */
protected $helper;
/**
* @param Helper $helper
*/
public function __construct(Helper $helper) {
$this->helper = $helper;
public function __construct(
protected Helper $helper,
) {
parent::__construct();
}
protected function configure() {
protected function configure(): void {
$this
->setName('ldap:show-config')
->setDescription('shows the LDAP configuration')
@ -79,23 +74,26 @@ class ShowConfig extends Base {
$configIDs[] = $configID;
if (!in_array($configIDs[0], $availableConfigs)) {
$output->writeln("Invalid configID");
return 1;
return self::FAILURE;
}
} else {
$configIDs = $availableConfigs;
}
$this->renderConfigs($configIDs, $input, $output);
return 0;
return self::SUCCESS;
}
/**
* prints the LDAP configuration(s)
* @param string[] configID(s)
* @param InputInterface $input
* @param OutputInterface $output
*
* @param string[] $configIDs
*/
protected function renderConfigs($configIDs, $input, $output) {
protected function renderConfigs(
array $configIDs,
InputInterface $input,
OutputInterface $output,
): void {
$renderTable = $input->getOption('output') === 'table' or $input->getOption('output') === null;
$showPassword = $input->getOption('show-password');
@ -121,16 +119,17 @@ class ShowConfig extends Base {
$table->setHeaders(['Configuration', $id]);
$table->setRows($rows);
$table->render();
} else {
foreach ($configuration as $key => $value) {
if ($key === 'ldapAgentPassword' && !$showPassword) {
$rows[$key] = '***';
} else {
$rows[$key] = $value;
}
continue;
}
foreach ($configuration as $key => $value) {
if ($key === 'ldapAgentPassword' && !$showPassword) {
$rows[$key] = '***';
} else {
$rows[$key] = $value;
}
$configs[$id] = $rows;
}
$configs[$id] = $rows;
}
if (!$renderTable) {
$this->writeArrayInOutputFormat($input, $output, $configs);

@ -36,23 +36,14 @@ use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class ShowRemnants extends Command {
/** @var \OCA\User_LDAP\User\DeletedUsersIndex */
protected $dui;
/** @var \OCP\IDateTimeFormatter */
protected $dateFormatter;
/**
* @param DeletedUsersIndex $dui
* @param IDateTimeFormatter $dateFormatter
*/
public function __construct(DeletedUsersIndex $dui, IDateTimeFormatter $dateFormatter) {
$this->dui = $dui;
$this->dateFormatter = $dateFormatter;
public function __construct(
protected DeletedUsersIndex $dui,
protected IDateTimeFormatter $dateFormatter,
) {
parent::__construct();
}
protected function configure() {
protected function configure(): void {
$this
->setName('ldap:show-remnants')
->setDescription('shows which users are not available on LDAP anymore, but have remnants in Nextcloud.')
@ -60,7 +51,7 @@ class ShowRemnants extends Command {
->addOption('short-date', null, InputOption::VALUE_NONE, 'show dates in Y-m-d format');
}
protected function formatDate(int $timestamp, string $default, bool $showShortDate) {
protected function formatDate(int $timestamp, string $default, bool $showShortDate): string {
if (!($timestamp > 0)) {
return $default;
}
@ -103,6 +94,6 @@ class ShowRemnants extends Command {
$table->setRows($rows);
$table->render();
}
return 0;
return self::SUCCESS;
}
}

@ -41,18 +41,11 @@ class TestConfig extends Command {
protected const BINDFAILURE = 2;
protected const SEARCHFAILURE = 3;
protected AccessFactory $accessFactory;
protected Helper $helper;
protected ILDAPWrapper $ldap;
public function __construct(
AccessFactory $accessFactory,
Helper $helper,
ILDAPWrapper $ldap
protected AccessFactory $accessFactory,
protected Helper $helper,
protected ILDAPWrapper $ldap,
) {
$this->accessFactory = $accessFactory;
$this->helper = $helper;
$this->ldap = $ldap;
parent::__construct();
}
@ -73,28 +66,24 @@ class TestConfig extends Command {
$configID = $input->getArgument('configID');
if (!in_array($configID, $availableConfigs)) {
$output->writeln('Invalid configID');
return 1;
return self::FAILURE;
}
$result = $this->testConfig($configID);
switch ($result) {
case static::ESTABLISHED:
$output->writeln('The configuration is valid and the connection could be established!');
return 0;
case static::CONF_INVALID:
$output->writeln('The configuration is invalid. Please have a look at the logs for further details.');
break;
case static::BINDFAILURE:
$output->writeln('The configuration is valid, but the bind failed. Please check the server settings and credentials.');
break;
case static::SEARCHFAILURE:
$output->writeln('The configuration is valid and the bind passed, but a simple search on the base fails. Please check the server base setting.');
break;
default:
$output->writeln('Your LDAP server was kidnapped by aliens.');
break;
}
return 1;
$message = match ($result) {
static::ESTABLISHED => 'The configuration is valid and the connection could be established!',
static::CONF_INVALID => 'The configuration is invalid. Please have a look at the logs for further details.',
static::BINDFAILURE => 'The configuration is valid, but the bind failed. Please check the server settings and credentials.',
static::SEARCHFAILURE => 'The configuration is valid and the bind passed, but a simple search on the base fails. Please check the server base setting.',
default => 'Your LDAP server was kidnapped by aliens.',
};
$output->writeln($message);
return $result === static::ESTABLISHED
? self::SUCCESS
: self::FAILURE;
}
/**

@ -49,45 +49,29 @@ class UuidUpdateReport {
public const UNWRITABLE = 4;
public const UNMAPPED = 5;
public $id = '';
public $dn = '';
public $isUser = true;
public $state = self::UNCHANGED;
public $oldUuid = '';
public $newUuid = '';
public function __construct(string $id, string $dn, bool $isUser, int $state, string $oldUuid = '', string $newUuid = '') {
$this->id = $id;
$this->dn = $dn;
$this->isUser = $isUser;
$this->state = $state;
$this->oldUuid = $oldUuid;
$this->newUuid = $newUuid;
public function __construct(
public string $id,
public string $dn,
public bool $isUser,
public int $state,
public string $oldUuid = '',
public string $newUuid = '',
) {
}
}
class UpdateUUID extends Command {
/** @var UserMapping */
private $userMapping;
/** @var GroupMapping */
private $groupMapping;
/** @var User_Proxy */
private $userProxy;
/** @var Group_Proxy */
private $groupProxy;
/** @var array<UuidUpdateReport[]> */
protected $reports = [];
/** @var LoggerInterface */
private $logger;
/** @var bool */
private $dryRun = false;
protected array $reports = [];
private bool $dryRun = false;
public function __construct(UserMapping $userMapping, GroupMapping $groupMapping, User_Proxy $userProxy, Group_Proxy $groupProxy, LoggerInterface $logger) {
$this->userMapping = $userMapping;
$this->groupMapping = $groupMapping;
$this->userProxy = $userProxy;
$this->groupProxy = $groupProxy;
$this->logger = $logger;
public function __construct(
private UserMapping $userMapping,
private GroupMapping $groupMapping,
private User_Proxy $userProxy,
private Group_Proxy $groupProxy,
private LoggerInterface $logger,
) {
$this->reports = [
UuidUpdateReport::UPDATED => [],
UuidUpdateReport::UNKNOWN => [],
@ -140,7 +124,7 @@ class UpdateUUID extends Command {
$entriesToUpdate = $this->estimateNumberOfUpdates($input);
$progress = new ProgressBar($output);
$progress->start($entriesToUpdate);
foreach($this->handleUpdates($input) as $_) {
foreach ($this->handleUpdates($input) as $_) {
$progress->advance();
}
$progress->finish();
@ -149,8 +133,8 @@ class UpdateUUID extends Command {
return count($this->reports[UuidUpdateReport::UNMAPPED]) === 0
&& count($this->reports[UuidUpdateReport::UNREADABLE]) === 0
&& count($this->reports[UuidUpdateReport::UNWRITABLE]) === 0
? 0
: 1;
? self::SUCCESS
: self::FAILURE;
}
protected function printReport(OutputInterface $output): void {
@ -219,37 +203,37 @@ class UpdateUUID extends Command {
protected function handleUpdates(InputInterface $input): \Generator {
if ($input->getOption('all')) {
foreach($this->handleMappingBasedUpdates(false) as $_) {
foreach ($this->handleMappingBasedUpdates(false) as $_) {
yield;
}
} elseif ($input->getOption('userId')
|| $input->getOption('groupId')
|| $input->getOption('dn')
) {
foreach($this->handleUpdatesByUserId($input->getOption('userId')) as $_) {
foreach ($this->handleUpdatesByUserId($input->getOption('userId')) as $_) {
yield;
}
foreach($this->handleUpdatesByGroupId($input->getOption('groupId')) as $_) {
foreach ($this->handleUpdatesByGroupId($input->getOption('groupId')) as $_) {
yield;
}
foreach($this->handleUpdatesByDN($input->getOption('dn')) as $_) {
foreach ($this->handleUpdatesByDN($input->getOption('dn')) as $_) {
yield;
}
} else {
foreach($this->handleMappingBasedUpdates(true) as $_) {
foreach ($this->handleMappingBasedUpdates(true) as $_) {
yield;
}
}
}
protected function handleUpdatesByUserId(array $userIds): \Generator {
foreach($this->handleUpdatesByEntryId($userIds, $this->userMapping) as $_) {
foreach ($this->handleUpdatesByEntryId($userIds, $this->userMapping) as $_) {
yield;
}
}
protected function handleUpdatesByGroupId(array $groupIds): \Generator {
foreach($this->handleUpdatesByEntryId($groupIds, $this->groupMapping) as $_) {
foreach ($this->handleUpdatesByEntryId($groupIds, $this->groupMapping) as $_) {
yield;
}
}
@ -272,10 +256,10 @@ class UpdateUUID extends Command {
$this->reports[UuidUpdateReport::UNMAPPED][] = new UuidUpdateReport('', $dn, true, UuidUpdateReport::UNMAPPED);
yield;
}
foreach($this->handleUpdatesByList($this->userMapping, $userList) as $_) {
foreach ($this->handleUpdatesByList($this->userMapping, $userList) as $_) {
yield;
}
foreach($this->handleUpdatesByList($this->groupMapping, $groupList) as $_) {
foreach ($this->handleUpdatesByList($this->groupMapping, $groupList) as $_) {
yield;
}
}
@ -284,7 +268,7 @@ class UpdateUUID extends Command {
$isUser = $mapping instanceof UserMapping;
$list = [];
while ($id = array_pop($ids)) {
if(!$dn = $mapping->getDNByName($id)) {
if (!$dn = $mapping->getDNByName($id)) {
$this->reports[UuidUpdateReport::UNMAPPED][] = new UuidUpdateReport($id, '', $isUser, UuidUpdateReport::UNMAPPED);
yield;
continue;
@ -293,7 +277,7 @@ class UpdateUUID extends Command {
$uuid = $mapping->getUUIDByDN($dn);
$list[] = ['name' => $id, 'uuid' => $uuid];
}
foreach($this->handleUpdatesByList($mapping, $list) as $_) {
foreach ($this->handleUpdatesByList($mapping, $list) as $_) {
yield;
}
}
@ -301,13 +285,13 @@ class UpdateUUID extends Command {
protected function handleMappingBasedUpdates(bool $invalidatedOnly): \Generator {
$limit = 1000;
/** @var AbstractMapping $mapping*/
foreach([$this->userMapping, $this->groupMapping] as $mapping) {
foreach ([$this->userMapping, $this->groupMapping] as $mapping) {
$offset = 0;
do {
$list = $mapping->getList($offset, $limit, $invalidatedOnly);
$offset += $limit;
foreach($this->handleUpdatesByList($mapping, $list) as $tick) {
foreach ($this->handleUpdatesByList($mapping, $list) as $tick) {
yield; // null, for it only advances progress counter
}
} while (count($list) === $limit);
@ -369,5 +353,4 @@ class UpdateUUID extends Command {
return $this->userMapping->countInvalidated() + $this->groupMapping->countInvalidated();
}
}
}