diff options
Diffstat (limited to 'apps/provisioning_api/lib/Controller/UsersController.php')
-rw-r--r-- | apps/provisioning_api/lib/Controller/UsersController.php | 731 |
1 files changed, 482 insertions, 249 deletions
diff --git a/apps/provisioning_api/lib/Controller/UsersController.php b/apps/provisioning_api/lib/Controller/UsersController.php index 352970faa37..513a27c7df8 100644 --- a/apps/provisioning_api/lib/Controller/UsersController.php +++ b/apps/provisioning_api/lib/Controller/UsersController.php @@ -3,66 +3,43 @@ declare(strict_types=1); /** - * @copyright Copyright (c) 2016, ownCloud, Inc. - * - * @author Arthur Schiwon <blizzz@arthur-schiwon.de> - * @author Bjoern Schiessle <bjoern@schiessle.org> - * @author Christoph Wurst <christoph@winzerhof-wurst.at> - * @author Daniel Calviño Sánchez <danxuliu@gmail.com> - * @author Daniel Kesselberg <mail@danielkesselberg.de> - * @author Joas Schilling <coding@schilljs.com> - * @author John Molakvoæ <skjnldsv@protonmail.com> - * @author Julius Härtl <jus@bitgrid.net> - * @author Lukas Reschke <lukas@statuscode.ch> - * @author michag86 <micha_g@arcor.de> - * @author Mikael Hammarin <mikael@try2.se> - * @author Morris Jobke <hey@morrisjobke.de> - * @author Robin Appelman <robin@icewind.nl> - * @author Roeland Jago Douma <roeland@famdouma.nl> - * @author Sujith Haridasan <sujith.h@gmail.com> - * @author Thomas Citharel <nextcloud@tcit.fr> - * @author Thomas Müller <thomas.mueller@tmit.eu> - * @author Tom Needham <tom@owncloud.com> - * @author Vincent Petry <vincent@nextcloud.com> - * @author Kate Döen <kate.doeen@nextcloud.com> - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License, version 3, - * along with this program. If not, see <http://www.gnu.org/licenses/> - * + * SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors + * SPDX-FileCopyrightText: 2016 ownCloud, Inc. + * SPDX-License-Identifier: AGPL-3.0-only */ namespace OCA\Provisioning_API\Controller; use InvalidArgumentException; use OC\Authentication\Token\RemoteWipe; +use OC\Group\Group; use OC\KnownUser\KnownUserService; use OC\User\Backend; use OCA\Provisioning_API\ResponseDefinitions; use OCA\Settings\Mailer\NewUserMailHelper; +use OCA\Settings\Settings\Admin\Users; use OCP\Accounts\IAccountManager; use OCP\Accounts\IAccountProperty; use OCP\Accounts\PropertyDoesNotExistException; +use OCP\App\IAppManager; use OCP\AppFramework\Http; +use OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting; +use OCP\AppFramework\Http\Attribute\NoAdminRequired; +use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired; +use OCP\AppFramework\Http\Attribute\UserRateLimit; use OCP\AppFramework\Http\DataResponse; use OCP\AppFramework\OCS\OCSException; use OCP\AppFramework\OCS\OCSForbiddenException; +use OCP\AppFramework\OCS\OCSNotFoundException; use OCP\AppFramework\OCSController; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\IRootFolder; +use OCP\Group\ISubAdmin; use OCP\HintException; use OCP\IConfig; use OCP\IGroup; use OCP\IGroupManager; +use OCP\IL10N; use OCP\IPhoneNumberUtil; use OCP\IRequest; use OCP\IURLGenerator; @@ -73,28 +50,16 @@ use OCP\L10N\IFactory; use OCP\Security\Events\GenerateSecurePasswordEvent; use OCP\Security\ISecureRandom; use OCP\User\Backend\ISetDisplayNameBackend; +use OCP\Util; use Psr\Log\LoggerInterface; /** + * @psalm-import-type Provisioning_APIGroupDetails from ResponseDefinitions * @psalm-import-type Provisioning_APIUserDetails from ResponseDefinitions */ -class UsersController extends AUserData { - /** @var IURLGenerator */ - protected $urlGenerator; - /** @var LoggerInterface */ - private $logger; - /** @var IFactory */ - protected $l10nFactory; - /** @var NewUserMailHelper */ - private $newUserMailHelper; - /** @var ISecureRandom */ - private $secureRandom; - /** @var RemoteWipe */ - private $remoteWipe; - /** @var KnownUserService */ - private $knownUserService; - /** @var IEventDispatcher */ - private $eventDispatcher; +class UsersController extends AUserDataOCSController { + + private IL10N $l10n; public function __construct( string $appName, @@ -104,15 +69,18 @@ class UsersController extends AUserData { IGroupManager $groupManager, IUserSession $userSession, IAccountManager $accountManager, - IURLGenerator $urlGenerator, - LoggerInterface $logger, + ISubAdmin $subAdminManager, IFactory $l10nFactory, - NewUserMailHelper $newUserMailHelper, - ISecureRandom $secureRandom, - RemoteWipe $remoteWipe, - KnownUserService $knownUserService, - IEventDispatcher $eventDispatcher, + IRootFolder $rootFolder, + private IURLGenerator $urlGenerator, + private LoggerInterface $logger, + private NewUserMailHelper $newUserMailHelper, + private ISecureRandom $secureRandom, + private RemoteWipe $remoteWipe, + private KnownUserService $knownUserService, + private IEventDispatcher $eventDispatcher, private IPhoneNumberUtil $phoneNumberUtil, + private IAppManager $appManager, ) { parent::__construct( $appName, @@ -122,39 +90,35 @@ class UsersController extends AUserData { $groupManager, $userSession, $accountManager, - $l10nFactory + $subAdminManager, + $l10nFactory, + $rootFolder, ); - $this->urlGenerator = $urlGenerator; - $this->logger = $logger; - $this->l10nFactory = $l10nFactory; - $this->newUserMailHelper = $newUserMailHelper; - $this->secureRandom = $secureRandom; - $this->remoteWipe = $remoteWipe; - $this->knownUserService = $knownUserService; - $this->eventDispatcher = $eventDispatcher; + $this->l10n = $l10nFactory->get($appName); } /** - * @NoAdminRequired - * * Get a list of users * * @param string $search Text to search for * @param int|null $limit Limit the amount of groups returned * @param int $offset Offset for searching for groups - * @return DataResponse<Http::STATUS_OK, array{users: string[]}, array{}> + * @return DataResponse<Http::STATUS_OK, array{users: list<string>}, array{}> * * 200: Users returned */ - public function getUsers(string $search = '', int $limit = null, int $offset = 0): DataResponse { + #[NoAdminRequired] + public function getUsers(string $search = '', ?int $limit = null, int $offset = 0): DataResponse { $user = $this->userSession->getUser(); $users = []; // Admin? Or SubAdmin? $uid = $user->getUID(); $subAdminManager = $this->groupManager->getSubAdmin(); - if ($this->groupManager->isAdmin($uid)) { + $isAdmin = $this->groupManager->isAdmin($uid); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($uid); + if ($isAdmin || $isDelegatedAdmin) { $users = $this->userManager->search($search, $limit, $offset); } elseif ($subAdminManager->isSubAdmin($user)) { $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($user); @@ -168,7 +132,7 @@ class UsersController extends AUserData { } } - /** @var string[] $users */ + /** @var list<string> $users */ $users = array_keys($users); return new DataResponse([ @@ -177,8 +141,6 @@ class UsersController extends AUserData { } /** - * @NoAdminRequired - * * Get a list of users and their details * * @param string $search Text to search for @@ -188,14 +150,17 @@ class UsersController extends AUserData { * * 200: Users details returned */ - public function getUsersDetails(string $search = '', int $limit = null, int $offset = 0): DataResponse { + #[NoAdminRequired] + public function getUsersDetails(string $search = '', ?int $limit = null, int $offset = 0): DataResponse { $currentUser = $this->userSession->getUser(); $users = []; // Admin? Or SubAdmin? $uid = $currentUser->getUID(); $subAdminManager = $this->groupManager->getSubAdmin(); - if ($this->groupManager->isAdmin($uid)) { + $isAdmin = $this->groupManager->isAdmin($uid); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($uid); + if ($isAdmin || $isDelegatedAdmin) { $users = $this->userManager->search($search, $limit, $offset); $users = array_keys($users); } elseif ($subAdminManager->isSubAdmin($currentUser)) { @@ -213,8 +178,15 @@ class UsersController extends AUserData { $usersDetails = []; foreach ($users as $userId) { - $userId = (string) $userId; - $userData = $this->getUserData($userId); + $userId = (string)$userId; + try { + $userData = $this->getUserData($userId); + } catch (OCSNotFoundException $e) { + // We still want to return all other accounts, but this one was removed from the backends + // yet they are still in our database. Might be a LDAP remnant. + $userData = null; + $this->logger->warning('Found one enabled account that is removed from its backend, but still exists in Nextcloud database', ['accountId' => $userId]); + } // Do not insert empty entry if ($userData !== null) { $usersDetails[$userId] = $userData; @@ -231,17 +203,17 @@ class UsersController extends AUserData { } /** - * @NoAdminRequired - * * Get the list of disabled users and their details * + * @param string $search Text to search for * @param ?int $limit Limit the amount of users returned * @param int $offset Offset * @return DataResponse<Http::STATUS_OK, array{users: array<string, Provisioning_APIUserDetails|array{id: string}>}, array{}> * * 200: Disabled users details returned */ - public function getDisabledUsersDetails(?int $limit = null, int $offset = 0): DataResponse { + #[NoAdminRequired] + public function getDisabledUsersDetails(string $search = '', ?int $limit = null, int $offset = 0): DataResponse { $currentUser = $this->userSession->getUser(); if ($currentUser === null) { return new DataResponse(['users' => []]); @@ -258,8 +230,10 @@ class UsersController extends AUserData { // Admin? Or SubAdmin? $uid = $currentUser->getUID(); $subAdminManager = $this->groupManager->getSubAdmin(); - if ($this->groupManager->isAdmin($uid)) { - $users = $this->userManager->getDisabledUsers($limit, $offset); + $isAdmin = $this->groupManager->isAdmin($uid); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($uid); + if ($isAdmin || $isDelegatedAdmin) { + $users = $this->userManager->getDisabledUsers($limit, $offset, $search); $users = array_map(fn (IUser $user): string => $user->getUID(), $users); } elseif ($subAdminManager->isSubAdmin($currentUser)) { $subAdminOfGroups = $subAdminManager->getSubAdminsGroups($currentUser); @@ -268,31 +242,94 @@ class UsersController extends AUserData { /* We have to handle offset ourselve for correctness */ $tempLimit = ($limit === null ? null : $limit + $offset); foreach ($subAdminOfGroups as $group) { - $users = array_merge( + $users = array_unique(array_merge( $users, array_map( fn (IUser $user): string => $user->getUID(), array_filter( - $group->searchUsers('', ($tempLimit === null ? null : $tempLimit - count($users))), - fn (IUser $user): bool => $user->isEnabled() + $group->searchUsers($search), + fn (IUser $user): bool => !$user->isEnabled() ) ) - ); + )); if (($tempLimit !== null) && (count($users) >= $tempLimit)) { break; } } - $users = array_slice($users, $offset); + $users = array_slice($users, $offset, $limit); } $usersDetails = []; foreach ($users as $userId) { - $userData = $this->getUserData($userId); + try { + $userData = $this->getUserData($userId); + } catch (OCSNotFoundException $e) { + // We still want to return all other accounts, but this one was removed from the backends + // yet they are still in our database. Might be a LDAP remnant. + $userData = null; + $this->logger->warning('Found one disabled account that was removed from its backend, but still exists in Nextcloud database', ['accountId' => $userId]); + } // Do not insert empty entry if ($userData !== null) { $usersDetails[$userId] = $userData; } else { - // Logged user does not have permissions to see this user + // Currently logged in user does not have permissions to see this user + // only showing its id + $usersDetails[$userId] = ['id' => $userId]; + } + } + + return new DataResponse([ + 'users' => $usersDetails + ]); + } + + /** + * Gets the list of users sorted by lastLogin, from most recent to least recent + * + * @param string $search Text to search for + * @param ?int $limit Limit the amount of users returned + * @param int $offset Offset + * @return DataResponse<Http::STATUS_OK, array{users: array<string, Provisioning_APIUserDetails|array{id: string}>}, array{}> + * + * 200: Users details returned based on last logged in information + */ + #[AuthorizedAdminSetting(settings:Users::class)] + public function getLastLoggedInUsers(string $search = '', + ?int $limit = null, + int $offset = 0, + ): DataResponse { + $currentUser = $this->userSession->getUser(); + if ($currentUser === null) { + return new DataResponse(['users' => []]); + } + if ($limit !== null && $limit < 0) { + throw new InvalidArgumentException("Invalid limit value: $limit"); + } + if ($offset < 0) { + throw new InvalidArgumentException("Invalid offset value: $offset"); + } + + $users = []; + + // For Admin alone user sorting based on lastLogin. For sub admin and groups this is not supported + $users = $this->userManager->getLastLoggedInUsers($limit, $offset, $search); + + $usersDetails = []; + foreach ($users as $userId) { + try { + $userData = $this->getUserData($userId); + } catch (OCSNotFoundException $e) { + // We still want to return all other accounts, but this one was removed from the backends + // yet they are still in our database. Might be a LDAP remnant. + $userData = null; + $this->logger->warning('Found one account that was removed from its backend, but still exists in Nextcloud database', ['accountId' => $userId]); + } + // Do not insert empty entry + if ($userData !== null) { + $usersDetails[$userId] = $userData; + } else { + // Currently logged-in user does not have permissions to see this user // only showing its id $usersDetails[$userId] = ['id' => $userId]; } @@ -304,19 +341,20 @@ class UsersController extends AUserData { } + /** - * @NoAdminRequired * @NoSubAdminRequired * * Search users by their phone numbers * * @param string $location Location of the phone number (for country code) - * @param array<string, string[]> $search Phone numbers to search for - * @return DataResponse<Http::STATUS_OK, array<string, string>, array{}>|DataResponse<Http::STATUS_BAD_REQUEST, array<empty>, array{}> + * @param array<string, list<string>> $search Phone numbers to search for + * @return DataResponse<Http::STATUS_OK, array<string, string>, array{}>|DataResponse<Http::STATUS_BAD_REQUEST, list<empty>, array{}> * * 200: Users returned * 400: Invalid location */ + #[NoAdminRequired] public function searchByPhoneNumbers(string $location, array $search): DataResponse { if ($this->phoneNumberUtil->getCountryCodeForRegion($location) === null) { // Not a valid region code @@ -333,7 +371,7 @@ class UsersController extends AUserData { foreach ($phoneNumbers as $phone) { $normalizedNumber = $this->phoneNumberUtil->convertToStandardFormat($phone, $location); if ($normalizedNumber !== null) { - $normalizedNumberToKey[$normalizedNumber] = (string) $key; + $normalizedNumberToKey[$normalizedNumber] = (string)$key; } if ($defaultPhoneRegion !== '' && $defaultPhoneRegion !== $location && str_starts_with($phone, '0')) { @@ -342,7 +380,7 @@ class UsersController extends AUserData { // when it's different to the user's given region. $normalizedNumber = $this->phoneNumberUtil->convertToStandardFormat($phone, $defaultPhoneRegion); if ($normalizedNumber !== null) { - $normalizedNumberToKey[$normalizedNumber] = (string) $key; + $normalizedNumberToKey[$normalizedNumber] = (string)$key; } } } @@ -392,21 +430,18 @@ class UsersController extends AUserData { } $attempts++; } while ($attempts < 10); - throw new OCSException('Could not create non-existing user id', 111); + throw new OCSException($this->l10n->t('Could not create non-existing user ID'), 111); } /** - * @PasswordConfirmationRequired - * @NoAdminRequired - * * Create a new user * * @param string $userid ID of the user * @param string $password Password of the user * @param string $displayName Display name of the user * @param string $email Email of the user - * @param string[] $groups Groups of the user - * @param string[] $subadmin Groups where the user is subadmin + * @param list<string> $groups Groups of the user + * @param list<string> $subadmin Groups where the user is subadmin * @param string $quota Quota of the user * @param string $language Language of the user * @param ?string $manager Manager of the user @@ -416,6 +451,8 @@ class UsersController extends AUserData { * * 200: User added successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] public function addUser( string $userid, string $password = '', @@ -429,6 +466,7 @@ class UsersController extends AUserData { ): DataResponse { $user = $this->userSession->getUser(); $isAdmin = $this->groupManager->isAdmin($user->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($user->getUID()); $subAdminManager = $this->groupManager->getSubAdmin(); if (empty($userid) && $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes') { @@ -437,21 +475,21 @@ class UsersController extends AUserData { if ($this->userManager->userExists($userid)) { $this->logger->error('Failed addUser attempt: User already exists.', ['app' => 'ocs_api']); - throw new OCSException($this->l10nFactory->get('provisioning_api')->t('User already exists'), 102); + throw new OCSException($this->l10n->t('User already exists'), 102); } if ($groups !== []) { foreach ($groups as $group) { if (!$this->groupManager->groupExists($group)) { - throw new OCSException('group ' . $group . ' does not exist', 104); + throw new OCSException($this->l10n->t('Group %1$s does not exist', [$group]), 104); } - if (!$isAdmin && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) { - throw new OCSException('insufficient privileges for group ' . $group, 105); + if (!$isAdmin && !($isDelegatedAdmin && $group !== 'admin') && !$subAdminManager->isSubAdminOfGroup($user, $this->groupManager->get($group))) { + throw new OCSException($this->l10n->t('Insufficient privileges for group %1$s', [$group]), 105); } } } else { - if (!$isAdmin) { - throw new OCSException('no group specified (required for subadmins)', 106); + if (!$isAdmin && !$isDelegatedAdmin) { + throw new OCSException($this->l10n->t('No group specified (required for sub-admins)'), 106); } } @@ -461,15 +499,15 @@ class UsersController extends AUserData { $group = $this->groupManager->get($groupid); // Check if group exists if ($group === null) { - throw new OCSException('Subadmin group does not exist', 102); + throw new OCSException($this->l10n->t('Sub-admin group does not exist'), 109); } // Check if trying to make subadmin of admin group if ($group->getGID() === 'admin') { - throw new OCSException('Cannot create subadmins for admin group', 103); + throw new OCSException($this->l10n->t('Cannot create sub-admins for admin group'), 103); } // Check if has permission to promote subadmins - if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin) { - throw new OCSForbiddenException('No permissions to promote subadmins'); + if (!$subAdminManager->isSubAdminOfGroup($user, $group) && !$isAdmin && !$isDelegatedAdmin) { + throw new OCSForbiddenException($this->l10n->t('No permissions to promote sub-admins')); } $subadminGroups[] = $group; } @@ -477,11 +515,11 @@ class UsersController extends AUserData { $generatePasswordResetToken = false; if (strlen($password) > IUserManager::MAX_PASSWORD_LENGTH) { - throw new OCSException('Invalid password value', 101); + throw new OCSException($this->l10n->t('Invalid password value'), 101); } if ($password === '') { if ($email === '') { - throw new OCSException('To send a password link to the user an email address is required.', 108); + throw new OCSException($this->l10n->t('An email address is required, to send a password link to the user.'), 108); } $passwordEvent = new GenerateSecurePasswordEvent(); @@ -499,14 +537,21 @@ class UsersController extends AUserData { $generatePasswordResetToken = true; } + $email = mb_strtolower(trim($email)); if ($email === '' && $this->config->getAppValue('core', 'newUser.requireEmail', 'no') === 'yes') { - throw new OCSException('Required email address was not provided', 110); + throw new OCSException($this->l10n->t('Required email address was not provided'), 110); } + // Create the user try { $newUser = $this->userManager->createUser($userid, $password); - $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']); + if (!$newUser instanceof IUser) { + // If the user is not an instance of IUser, it means the user creation failed + $this->logger->error('Failed addUser attempt: User creation failed.', ['app' => 'ocs_api']); + throw new OCSException($this->l10n->t('User creation failed'), 111); + } + $this->logger->info('Successful addUser call with userid: ' . $userid, ['app' => 'ocs_api']); foreach ($groups as $group) { $this->groupManager->get($group)->addUser($newUser); $this->logger->info('Added userid ' . $userid . ' to group ' . $group, ['app' => 'ocs_api']); @@ -545,7 +590,7 @@ class UsersController extends AUserData { // Send new user mail only if a mail is set if ($email !== '') { - $newUser->setEMailAddress($email); + $newUser->setSystemEMailAddress($email); if ($this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes') { try { $emailTemplate = $this->newUserMailHelper->generateTemplate($newUser, $generatePasswordResetToken); @@ -605,7 +650,6 @@ class UsersController extends AUserData { } /** - * @NoAdminRequired * @NoSubAdminRequired * * Get the details of a user @@ -616,6 +660,7 @@ class UsersController extends AUserData { * * 200: User returned */ + #[NoAdminRequired] public function getUser(string $userId): DataResponse { $includeScopes = false; $currentUser = $this->userSession->getUser(); @@ -632,7 +677,6 @@ class UsersController extends AUserData { } /** - * @NoAdminRequired * @NoSubAdminRequired * * Get the details of the current user @@ -642,6 +686,7 @@ class UsersController extends AUserData { * * 200: Current user returned */ + #[NoAdminRequired] public function getCurrentUser(): DataResponse { $user = $this->userSession->getUser(); if ($user) { @@ -654,16 +699,16 @@ class UsersController extends AUserData { } /** - * @NoAdminRequired * @NoSubAdminRequired * * Get a list of fields that are editable for the current user * - * @return DataResponse<Http::STATUS_OK, string[], array{}> + * @return DataResponse<Http::STATUS_OK, list<string>, array{}> * @throws OCSException * * 200: Editable fields returned */ + #[NoAdminRequired] public function getEditableFields(): DataResponse { $currentLoggedInUser = $this->userSession->getUser(); if (!$currentLoggedInUser instanceof IUser) { @@ -674,17 +719,30 @@ class UsersController extends AUserData { } /** - * @NoAdminRequired + * Get a list of enabled apps for the current user + * + * @return DataResponse<Http::STATUS_OK, array{apps: list<string>}, array{}> + * + * 200: Enabled apps returned + */ + #[NoAdminRequired] + public function getEnabledApps(): DataResponse { + $currentLoggedInUser = $this->userSession->getUser(); + return new DataResponse(['apps' => $this->appManager->getEnabledAppsForUser($currentLoggedInUser)]); + } + + /** * @NoSubAdminRequired * * Get a list of fields that are editable for a user * * @param string $userId ID of the user - * @return DataResponse<Http::STATUS_OK, string[], array{}> + * @return DataResponse<Http::STATUS_OK, list<string>, array{}> * @throws OCSException * * 200: Editable fields for user returned */ + #[NoAdminRequired] public function getEditableFieldsForUser(string $userId): DataResponse { $currentLoggedInUser = $this->userSession->getUser(); if (!$currentLoggedInUser instanceof IUser) { @@ -700,8 +758,10 @@ class UsersController extends AUserData { } $subAdminManager = $this->groupManager->getSubAdmin(); + $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()); if ( - !$this->groupManager->isAdmin($currentLoggedInUser->getUID()) + !($isAdmin || $isDelegatedAdmin) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) ) { throw new OCSException('', OCSController::RESPOND_NOT_FOUND); @@ -710,14 +770,16 @@ class UsersController extends AUserData { $targetUser = $currentLoggedInUser; } - // Editing self (display, email) - if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) { - if ( - $targetUser->getBackend() instanceof ISetDisplayNameBackend - || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME) - ) { - $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME; - } + $allowDisplayNameChange = $this->config->getSystemValue('allow_user_to_change_display_name', true); + if ($allowDisplayNameChange === true && ( + $targetUser->getBackend() instanceof ISetDisplayNameBackend + || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME) + )) { + $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME; + } + + // Fallback to display name value to avoid changing behavior with the new option. + if ($this->config->getSystemValue('allow_user_to_change_email', $allowDisplayNameChange)) { $permittedFields[] = IAccountManager::PROPERTY_EMAIL; } @@ -726,21 +788,20 @@ class UsersController extends AUserData { $permittedFields[] = IAccountManager::PROPERTY_ADDRESS; $permittedFields[] = IAccountManager::PROPERTY_WEBSITE; $permittedFields[] = IAccountManager::PROPERTY_TWITTER; + $permittedFields[] = IAccountManager::PROPERTY_BLUESKY; $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE; $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION; $permittedFields[] = IAccountManager::PROPERTY_ROLE; $permittedFields[] = IAccountManager::PROPERTY_HEADLINE; $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY; $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED; + $permittedFields[] = IAccountManager::PROPERTY_PRONOUNS; return new DataResponse($permittedFields); } /** - * @NoAdminRequired * @NoSubAdminRequired - * @PasswordConfirmationRequired - * @UserRateThrottle(limit=5, period=60) * * Update multiple values of the user's details * @@ -748,16 +809,19 @@ class UsersController extends AUserData { * @param string $collectionName Collection to update * @param string $key Key that will be updated * @param string $value New value for the key - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User values edited successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] + #[UserRateLimit(limit: 5, period: 60)] public function editUserMultiValue( string $userId, string $collectionName, string $key, - string $value + string $value, ): DataResponse { $currentLoggedInUser = $this->userSession->getUser(); if ($currentLoggedInUser === null) { @@ -770,6 +834,7 @@ class UsersController extends AUserData { } $subAdminManager = $this->groupManager->getSubAdmin(); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()); $isAdminOrSubadmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID()) || $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser); @@ -780,7 +845,7 @@ class UsersController extends AUserData { $permittedFields[] = IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX; } else { // Check if admin / subadmin - if ($isAdminOrSubadmin) { + if ($isAdminOrSubadmin || $isDelegatedAdmin && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')) { // They have permissions over the user $permittedFields[] = IAccountManager::COLLECTION_EMAIL; } else { @@ -800,6 +865,7 @@ class UsersController extends AUserData { $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL); $mailCollection->removePropertyByValue($key); if ($value !== '') { + $value = mb_strtolower(trim($value)); $mailCollection->addPropertyWithDefaults($value); $property = $mailCollection->getPropertyByValue($key); if ($isAdminOrSubadmin && $property) { @@ -808,6 +874,9 @@ class UsersController extends AUserData { } } $this->accountManager->updateAccount($userAccount); + if ($value === '' && $key === $targetUser->getPrimaryEMailAddress()) { + $targetUser->setPrimaryEMailAddress(''); + } break; case IAccountManager::COLLECTION_EMAIL . self::SCOPE_SUFFIX: @@ -839,21 +908,21 @@ class UsersController extends AUserData { } /** - * @NoAdminRequired * @NoSubAdminRequired - * @PasswordConfirmationRequired - * @UserRateThrottle(limit=50, period=600) * * Update a value of the user's details * * @param string $userId ID of the user * @param string $key Key that will be updated * @param string $value New value for the key - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User value edited successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] + #[UserRateLimit(limit: 50, period: 600)] public function editUser(string $userId, string $key, string $value): DataResponse { $currentLoggedInUser = $this->userSession->getUser(); @@ -864,15 +933,17 @@ class UsersController extends AUserData { $permittedFields = []; if ($targetUser->getUID() === $currentLoggedInUser->getUID()) { - // Editing self (display, email) - if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) { - if ( - $targetUser->getBackend() instanceof ISetDisplayNameBackend - || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME) - ) { - $permittedFields[] = self::USER_FIELD_DISPLAYNAME; - $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME; - } + $allowDisplayNameChange = $this->config->getSystemValue('allow_user_to_change_display_name', true); + if ($allowDisplayNameChange !== false && ( + $targetUser->getBackend() instanceof ISetDisplayNameBackend + || $targetUser->getBackend()->implementsActions(Backend::SET_DISPLAYNAME) + )) { + $permittedFields[] = self::USER_FIELD_DISPLAYNAME; + $permittedFields[] = IAccountManager::PROPERTY_DISPLAYNAME; + } + + // Fallback to display name value to avoid changing behavior with the new option. + if ($this->config->getSystemValue('allow_user_to_change_email', $allowDisplayNameChange)) { $permittedFields[] = IAccountManager::PROPERTY_EMAIL; } @@ -884,44 +955,55 @@ class UsersController extends AUserData { $permittedFields[] = self::USER_FIELD_PASSWORD; $permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL; if ( - $this->config->getSystemValue('force_language', false) === false || - $this->groupManager->isAdmin($currentLoggedInUser->getUID()) + $this->config->getSystemValue('force_language', false) === false + || $this->groupManager->isAdmin($currentLoggedInUser->getUID()) + || $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()) ) { $permittedFields[] = self::USER_FIELD_LANGUAGE; } if ( - $this->config->getSystemValue('force_locale', false) === false || - $this->groupManager->isAdmin($currentLoggedInUser->getUID()) + $this->config->getSystemValue('force_locale', false) === false + || $this->groupManager->isAdmin($currentLoggedInUser->getUID()) + || $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()) ) { $permittedFields[] = self::USER_FIELD_LOCALE; + $permittedFields[] = self::USER_FIELD_FIRST_DAY_OF_WEEK; } $permittedFields[] = IAccountManager::PROPERTY_PHONE; $permittedFields[] = IAccountManager::PROPERTY_ADDRESS; $permittedFields[] = IAccountManager::PROPERTY_WEBSITE; $permittedFields[] = IAccountManager::PROPERTY_TWITTER; + $permittedFields[] = IAccountManager::PROPERTY_BLUESKY; $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE; $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION; $permittedFields[] = IAccountManager::PROPERTY_ROLE; $permittedFields[] = IAccountManager::PROPERTY_HEADLINE; $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY; $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED; + $permittedFields[] = IAccountManager::PROPERTY_BIRTHDATE; + $permittedFields[] = IAccountManager::PROPERTY_PRONOUNS; + $permittedFields[] = IAccountManager::PROPERTY_PHONE . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX; + $permittedFields[] = IAccountManager::PROPERTY_BLUESKY . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX; - + $permittedFields[] = IAccountManager::PROPERTY_BIRTHDATE . self::SCOPE_SUFFIX; $permittedFields[] = IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX; + $permittedFields[] = IAccountManager::PROPERTY_PRONOUNS . self::SCOPE_SUFFIX; // If admin they can edit their own quota and manager - if ($this->groupManager->isAdmin($currentLoggedInUser->getUID())) { + $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()); + if ($isAdmin || $isDelegatedAdmin) { $permittedFields[] = self::USER_FIELD_QUOTA; $permittedFields[] = self::USER_FIELD_MANAGER; } @@ -930,6 +1012,7 @@ class UsersController extends AUserData { $subAdminManager = $this->groupManager->getSubAdmin(); if ( $this->groupManager->isAdmin($currentLoggedInUser->getUID()) + || $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()) && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin') || $subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) ) { // They have permissions over the user @@ -945,16 +1028,19 @@ class UsersController extends AUserData { $permittedFields[] = self::USER_FIELD_PASSWORD; $permittedFields[] = self::USER_FIELD_LANGUAGE; $permittedFields[] = self::USER_FIELD_LOCALE; + $permittedFields[] = self::USER_FIELD_FIRST_DAY_OF_WEEK; $permittedFields[] = IAccountManager::PROPERTY_PHONE; $permittedFields[] = IAccountManager::PROPERTY_ADDRESS; $permittedFields[] = IAccountManager::PROPERTY_WEBSITE; $permittedFields[] = IAccountManager::PROPERTY_TWITTER; + $permittedFields[] = IAccountManager::PROPERTY_BLUESKY; $permittedFields[] = IAccountManager::PROPERTY_FEDIVERSE; $permittedFields[] = IAccountManager::PROPERTY_ORGANISATION; $permittedFields[] = IAccountManager::PROPERTY_ROLE; $permittedFields[] = IAccountManager::PROPERTY_HEADLINE; $permittedFields[] = IAccountManager::PROPERTY_BIOGRAPHY; $permittedFields[] = IAccountManager::PROPERTY_PROFILE_ENABLED; + $permittedFields[] = IAccountManager::PROPERTY_PRONOUNS; $permittedFields[] = self::USER_FIELD_QUOTA; $permittedFields[] = self::USER_FIELD_NOTIFICATION_EMAIL; $permittedFields[] = self::USER_FIELD_MANAGER; @@ -965,7 +1051,7 @@ class UsersController extends AUserData { } // Check if permitted to edit this field if (!in_array($key, $permittedFields)) { - throw new OCSException('', 103); + throw new OCSException('', 113); } // Process the edit switch ($key) { @@ -981,28 +1067,28 @@ class UsersController extends AUserData { $quota = $value; if ($quota !== 'none' && $quota !== 'default') { if (is_numeric($quota)) { - $quota = (float) $quota; + $quota = (float)$quota; } else { - $quota = \OCP\Util::computerFileSize($quota); + $quota = Util::computerFileSize($quota); } if ($quota === false) { - throw new OCSException('Invalid quota value ' . $value, 102); + throw new OCSException($this->l10n->t('Invalid quota value: %1$s', [$value]), 101); } if ($quota === -1) { $quota = 'none'; } else { - $maxQuota = (int) $this->config->getAppValue('files', 'max_quota', '-1'); + $maxQuota = (int)$this->config->getAppValue('files', 'max_quota', '-1'); if ($maxQuota !== -1 && $quota > $maxQuota) { - throw new OCSException('Invalid quota value. ' . $value . ' is exceeding the maximum quota', 102); + throw new OCSException($this->l10n->t('Invalid quota value. %1$s is exceeding the maximum quota', [$value]), 101); } - $quota = \OCP\Util::humanFileSize($quota); + $quota = Util::humanFileSize($quota); } } // no else block because quota can be set to 'none' in previous if if ($quota === 'none') { $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1'; if (!$allowUnlimitedQuota) { - throw new OCSException('Unlimited quota is forbidden on this instance', 102); + throw new OCSException($this->l10n->t('Unlimited quota is forbidden on this instance'), 101); } } $targetUser->setQuota($quota); @@ -1013,29 +1099,40 @@ class UsersController extends AUserData { case self::USER_FIELD_PASSWORD: try { if (strlen($value) > IUserManager::MAX_PASSWORD_LENGTH) { - throw new OCSException('Invalid password value', 102); + throw new OCSException($this->l10n->t('Invalid password value'), 101); } if (!$targetUser->canChangePassword()) { - throw new OCSException('Setting the password is not supported by the users backend', 103); + throw new OCSException($this->l10n->t('Setting the password is not supported by the users backend'), 112); } $targetUser->setPassword($value); } catch (HintException $e) { // password policy error - throw new OCSException($e->getMessage(), 103); + throw new OCSException($e->getHint(), 107); } break; case self::USER_FIELD_LANGUAGE: $languagesCodes = $this->l10nFactory->findAvailableLanguages(); if (!in_array($value, $languagesCodes, true) && $value !== 'en') { - throw new OCSException('Invalid language', 102); + throw new OCSException($this->l10n->t('Invalid language'), 101); } $this->config->setUserValue($targetUser->getUID(), 'core', 'lang', $value); break; case self::USER_FIELD_LOCALE: if (!$this->l10nFactory->localeExists($value)) { - throw new OCSException('Invalid locale', 102); + throw new OCSException($this->l10n->t('Invalid locale'), 101); } $this->config->setUserValue($targetUser->getUID(), 'core', 'locale', $value); break; + case self::USER_FIELD_FIRST_DAY_OF_WEEK: + $intValue = (int)$value; + if ($intValue < -1 || $intValue > 6) { + throw new OCSException($this->l10n->t('Invalid first day of week'), 101); + } + if ($intValue === -1) { + $this->config->deleteUserValue($targetUser->getUID(), 'core', AUserDataOCSController::USER_FIELD_FIRST_DAY_OF_WEEK); + } else { + $this->config->setUserValue($targetUser->getUID(), 'core', AUserDataOCSController::USER_FIELD_FIRST_DAY_OF_WEEK, $value); + } + break; case self::USER_FIELD_NOTIFICATION_EMAIL: $success = false; if ($value === '' || filter_var($value, FILTER_VALIDATE_EMAIL)) { @@ -1053,40 +1150,45 @@ class UsersController extends AUserData { } } if (!$success) { - throw new OCSException('', 102); + throw new OCSException('', 101); } break; case IAccountManager::PROPERTY_EMAIL: + $value = mb_strtolower(trim($value)); if (filter_var($value, FILTER_VALIDATE_EMAIL) || $value === '') { - $targetUser->setEMailAddress($value); + $targetUser->setSystemEMailAddress($value); } else { - throw new OCSException('', 102); + throw new OCSException('', 101); } break; case IAccountManager::COLLECTION_EMAIL: + $value = mb_strtolower(trim($value)); if (filter_var($value, FILTER_VALIDATE_EMAIL) && $value !== $targetUser->getSystemEMailAddress()) { $userAccount = $this->accountManager->getAccount($targetUser); $mailCollection = $userAccount->getPropertyCollection(IAccountManager::COLLECTION_EMAIL); if ($mailCollection->getPropertyByValue($value)) { - throw new OCSException('', 102); + throw new OCSException('', 101); } $mailCollection->addPropertyWithDefaults($value); $this->accountManager->updateAccount($userAccount); } else { - throw new OCSException('', 102); + throw new OCSException('', 101); } break; case IAccountManager::PROPERTY_PHONE: case IAccountManager::PROPERTY_ADDRESS: case IAccountManager::PROPERTY_WEBSITE: case IAccountManager::PROPERTY_TWITTER: + case IAccountManager::PROPERTY_BLUESKY: case IAccountManager::PROPERTY_FEDIVERSE: case IAccountManager::PROPERTY_ORGANISATION: case IAccountManager::PROPERTY_ROLE: case IAccountManager::PROPERTY_HEADLINE: case IAccountManager::PROPERTY_BIOGRAPHY: + case IAccountManager::PROPERTY_BIRTHDATE: + case IAccountManager::PROPERTY_PRONOUNS: $userAccount = $this->accountManager->getAccount($targetUser); try { $userProperty = $userAccount->getProperty($key); @@ -1097,7 +1199,7 @@ class UsersController extends AUserData { $this->knownUserService->deleteByContactUserId($targetUser->getUID()); } } catch (InvalidArgumentException $e) { - throw new OCSException('Invalid ' . $e->getMessage(), 102); + throw new OCSException('Invalid ' . $e->getMessage(), 101); } } } catch (PropertyDoesNotExistException $e) { @@ -1106,7 +1208,7 @@ class UsersController extends AUserData { try { $this->accountManager->updateAccount($userAccount); } catch (InvalidArgumentException $e) { - throw new OCSException('Invalid ' . $e->getMessage(), 102); + throw new OCSException('Invalid ' . $e->getMessage(), 101); } break; case IAccountManager::PROPERTY_PROFILE_ENABLED: @@ -1127,13 +1229,16 @@ class UsersController extends AUserData { case IAccountManager::PROPERTY_ADDRESS . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_WEBSITE . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_TWITTER . self::SCOPE_SUFFIX: + case IAccountManager::PROPERTY_BLUESKY . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_FEDIVERSE . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_ORGANISATION . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_ROLE . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_HEADLINE . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_BIOGRAPHY . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_PROFILE_ENABLED . self::SCOPE_SUFFIX: + case IAccountManager::PROPERTY_BIRTHDATE . self::SCOPE_SUFFIX: case IAccountManager::PROPERTY_AVATAR . self::SCOPE_SUFFIX: + case IAccountManager::PROPERTY_PRONOUNS . self::SCOPE_SUFFIX: $propertyName = substr($key, 0, strlen($key) - strlen(self::SCOPE_SUFFIX)); $userAccount = $this->accountManager->getAccount($targetUser); $userProperty = $userAccount->getProperty($propertyName); @@ -1142,30 +1247,29 @@ class UsersController extends AUserData { $userProperty->setScope($value); $this->accountManager->updateAccount($userAccount); } catch (InvalidArgumentException $e) { - throw new OCSException('Invalid ' . $e->getMessage(), 102); + throw new OCSException('Invalid ' . $e->getMessage(), 101); } } break; default: - throw new OCSException('', 103); + throw new OCSException('', 113); } return new DataResponse(); } /** - * @PasswordConfirmationRequired - * @NoAdminRequired - * * Wipe all devices of a user * * @param string $userId ID of the user * - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * * @throws OCSException * * 200: Wiped all user devices successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] public function wipeUserDevices(string $userId): DataResponse { /** @var IUser $currentLoggedInUser */ $currentLoggedInUser = $this->userSession->getUser(); @@ -1182,7 +1286,9 @@ class UsersController extends AUserData { // If not permitted $subAdminManager = $this->groupManager->getSubAdmin(); - if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { + $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()); + if (!$isAdmin && !($isDelegatedAdmin && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { throw new OCSException('', OCSController::RESPOND_NOT_FOUND); } @@ -1192,17 +1298,16 @@ class UsersController extends AUserData { } /** - * @PasswordConfirmationRequired - * @NoAdminRequired - * * Delete a user * * @param string $userId ID of the user - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User deleted successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] public function deleteUser(string $userId): DataResponse { $currentLoggedInUser = $this->userSession->getUser(); @@ -1218,7 +1323,9 @@ class UsersController extends AUserData { // If not permitted $subAdminManager = $this->groupManager->getSubAdmin(); - if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { + $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()); + if (!$isAdmin && !($isDelegatedAdmin && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { throw new OCSException('', OCSController::RESPOND_NOT_FOUND); } @@ -1231,33 +1338,31 @@ class UsersController extends AUserData { } /** - * @PasswordConfirmationRequired - * @NoAdminRequired - * * Disable a user * * @param string $userId ID of the user - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User disabled successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] public function disableUser(string $userId): DataResponse { return $this->setEnabled($userId, false); } /** - * @PasswordConfirmationRequired - * @NoAdminRequired - * * Enable a user * * @param string $userId ID of the user - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User enabled successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] public function enableUser(string $userId): DataResponse { return $this->setEnabled($userId, true); } @@ -1265,7 +1370,7 @@ class UsersController extends AUserData { /** * @param string $userId * @param bool $value - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException */ private function setEnabled(string $userId, bool $value): DataResponse { @@ -1278,7 +1383,9 @@ class UsersController extends AUserData { // If not permitted $subAdminManager = $this->groupManager->getSubAdmin(); - if (!$this->groupManager->isAdmin($currentLoggedInUser->getUID()) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { + $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()); + if (!$isAdmin && !($isDelegatedAdmin && !$this->groupManager->isInGroup($targetUser->getUID(), 'admin')) && !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser)) { throw new OCSException('', OCSController::RESPOND_NOT_FOUND); } @@ -1288,17 +1395,17 @@ class UsersController extends AUserData { } /** - * @NoAdminRequired * @NoSubAdminRequired * * Get a list of groups the user belongs to * * @param string $userId ID of the user - * @return DataResponse<Http::STATUS_OK, array{groups: string[]}, array{}> + * @return DataResponse<Http::STATUS_OK, array{groups: list<string>}, array{}> * @throws OCSException * * 200: Users groups returned */ + #[NoAdminRequired] public function getUsersGroups(string $userId): DataResponse { $loggedInUser = $this->userSession->getUser(); @@ -1307,7 +1414,9 @@ class UsersController extends AUserData { throw new OCSException('', OCSController::RESPOND_NOT_FOUND); } - if ($targetUser->getUID() === $loggedInUser->getUID() || $this->groupManager->isAdmin($loggedInUser->getUID())) { + $isAdmin = $this->groupManager->isAdmin($loggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($loggedInUser->getUID()); + if ($targetUser->getUID() === $loggedInUser->getUID() || $isAdmin || $isDelegatedAdmin) { // Self lookup or admin lookup return new DataResponse([ 'groups' => $this->groupManager->getUserGroupIds($targetUser) @@ -1318,16 +1427,10 @@ class UsersController extends AUserData { // Looking up someone else if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) { // Return the group that the method caller is subadmin of for the user in question - /** @var IGroup[] $getSubAdminsGroups */ - $getSubAdminsGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); - foreach ($getSubAdminsGroups as $key => $group) { - $getSubAdminsGroups[$key] = $group->getGID(); - } - /** @var string[] $groups */ - $groups = array_intersect( - $getSubAdminsGroups, + $groups = array_values(array_intersect( + array_map(static fn (IGroup $group) => $group->getGID(), $subAdminManager->getSubAdminsGroups($loggedInUser)), $this->groupManager->getUserGroupIds($targetUser) - ); + )); return new DataResponse(['groups' => $groups]); } else { // Not permitted @@ -1337,18 +1440,138 @@ class UsersController extends AUserData { } /** - * @PasswordConfirmationRequired - * @NoAdminRequired + * @NoSubAdminRequired + * + * Get a list of groups with details * + * @param string $userId ID of the user + * @return DataResponse<Http::STATUS_OK, array{groups: list<Provisioning_APIGroupDetails>}, array{}> + * @throws OCSException + * + * 200: Users groups returned + */ + #[NoAdminRequired] + public function getUsersGroupsDetails(string $userId): DataResponse { + $loggedInUser = $this->userSession->getUser(); + + $targetUser = $this->userManager->get($userId); + if ($targetUser === null) { + throw new OCSException('', OCSController::RESPOND_NOT_FOUND); + } + + $isAdmin = $this->groupManager->isAdmin($loggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($loggedInUser->getUID()); + if ($targetUser->getUID() === $loggedInUser->getUID() || $isAdmin || $isDelegatedAdmin) { + // Self lookup or admin lookup + $groups = array_map( + function (Group $group) { + return [ + 'id' => $group->getGID(), + 'displayname' => $group->getDisplayName(), + 'usercount' => $group->count(), + 'disabled' => $group->countDisabled(), + 'canAdd' => $group->canAddUser(), + 'canRemove' => $group->canRemoveUser(), + ]; + }, + array_values($this->groupManager->getUserGroups($targetUser)), + ); + return new DataResponse([ + 'groups' => $groups, + ]); + } else { + $subAdminManager = $this->groupManager->getSubAdmin(); + + // Looking up someone else + if ($subAdminManager->isUserAccessible($loggedInUser, $targetUser)) { + // Return the group that the method caller is subadmin of for the user in question + $gids = array_values(array_intersect( + array_map( + static fn (IGroup $group) => $group->getGID(), + $subAdminManager->getSubAdminsGroups($loggedInUser), + ), + $this->groupManager->getUserGroupIds($targetUser) + )); + $groups = array_map( + function (string $gid) { + $group = $this->groupManager->get($gid); + return [ + 'id' => $group->getGID(), + 'displayname' => $group->getDisplayName(), + 'usercount' => $group->count(), + 'disabled' => $group->countDisabled(), + 'canAdd' => $group->canAddUser(), + 'canRemove' => $group->canRemoveUser(), + ]; + }, + $gids, + ); + return new DataResponse([ + 'groups' => $groups, + ]); + } else { + // Not permitted + throw new OCSException('', OCSController::RESPOND_NOT_FOUND); + } + } + } + + /** + * @NoSubAdminRequired + * + * Get a list of the groups the user is a subadmin of, with details + * + * @param string $userId ID of the user + * @return DataResponse<Http::STATUS_OK, array{groups: list<Provisioning_APIGroupDetails>}, array{}> + * @throws OCSException + * + * 200: Users subadmin groups returned + */ + #[NoAdminRequired] + public function getUserSubAdminGroupsDetails(string $userId): DataResponse { + $loggedInUser = $this->userSession->getUser(); + + $targetUser = $this->userManager->get($userId); + if ($targetUser === null) { + throw new OCSException('', OCSController::RESPOND_NOT_FOUND); + } + + $isAdmin = $this->groupManager->isAdmin($loggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($loggedInUser->getUID()); + if ($targetUser->getUID() === $loggedInUser->getUID() || $isAdmin || $isDelegatedAdmin) { + $subAdminManager = $this->groupManager->getSubAdmin(); + $groups = array_map( + function (IGroup $group) { + return [ + 'id' => $group->getGID(), + 'displayname' => $group->getDisplayName(), + 'usercount' => $group->count(), + 'disabled' => $group->countDisabled(), + 'canAdd' => $group->canAddUser(), + 'canRemove' => $group->canRemoveUser(), + ]; + }, + array_values($subAdminManager->getSubAdminsGroups($targetUser)), + ); + return new DataResponse([ + 'groups' => $groups, + ]); + } + throw new OCSException('', OCSController::RESPOND_NOT_FOUND); + } + + /** * Add a user to a group * * @param string $userId ID of the user * @param string $groupid ID of the group - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User added to group successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] public function addToGroup(string $userId, string $groupid = ''): DataResponse { if ($groupid === '') { throw new OCSException('', 101); @@ -1366,7 +1589,9 @@ class UsersController extends AUserData { // If they're not an admin, check they are a subadmin of the group in question $loggedInUser = $this->userSession->getUser(); $subAdminManager = $this->groupManager->getSubAdmin(); - if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) { + $isAdmin = $this->groupManager->isAdmin($loggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($loggedInUser->getUID()); + if (!$isAdmin && !($isDelegatedAdmin && $groupid !== 'admin') && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) { throw new OCSException('', 104); } @@ -1376,18 +1601,17 @@ class UsersController extends AUserData { } /** - * @PasswordConfirmationRequired - * @NoAdminRequired - * * Remove a user from a group * * @param string $userId ID of the user * @param string $groupid ID of the group - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User removed from group successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] public function removeFromGroup(string $userId, string $groupid): DataResponse { $loggedInUser = $this->userSession->getUser(); @@ -1407,21 +1631,23 @@ class UsersController extends AUserData { // If they're not an admin, check they are a subadmin of the group in question $subAdminManager = $this->groupManager->getSubAdmin(); - if (!$this->groupManager->isAdmin($loggedInUser->getUID()) && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) { + $isAdmin = $this->groupManager->isAdmin($loggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($loggedInUser->getUID()); + if (!$isAdmin && !($isDelegatedAdmin && $groupid !== 'admin') && !$subAdminManager->isSubAdminOfGroup($loggedInUser, $group)) { throw new OCSException('', 104); } // Check they aren't removing themselves from 'admin' or their 'subadmin; group if ($targetUser->getUID() === $loggedInUser->getUID()) { - if ($this->groupManager->isAdmin($loggedInUser->getUID())) { + if ($isAdmin || $isDelegatedAdmin) { if ($group->getGID() === 'admin') { - throw new OCSException('Cannot remove yourself from the admin group', 105); + throw new OCSException($this->l10n->t('Cannot remove yourself from the admin group'), 105); } } else { // Not an admin, so the user must be a subadmin of this group, but that is not allowed. - throw new OCSException('Cannot remove yourself from this group as you are a SubAdmin', 105); + throw new OCSException($this->l10n->t('Cannot remove yourself from this group as you are a sub-admin'), 105); } - } elseif (!$this->groupManager->isAdmin($loggedInUser->getUID())) { + } elseif (!($isAdmin || $isDelegatedAdmin)) { /** @var IGroup[] $subAdminGroups */ $subAdminGroups = $subAdminManager->getSubAdminsGroups($loggedInUser); $subAdminGroups = array_map(function (IGroup $subAdminGroup) { @@ -1432,7 +1658,7 @@ class UsersController extends AUserData { if (count($userSubAdminGroups) <= 1) { // Subadmin must not be able to remove a user from all their subadmin groups. - throw new OCSException('Not viable to remove user from the last group you are SubAdmin of', 105); + throw new OCSException($this->l10n->t('Not viable to remove user from the last group you are sub-admin of'), 105); } } @@ -1442,32 +1668,32 @@ class UsersController extends AUserData { } /** - * @PasswordConfirmationRequired - * * Make a user a subadmin of a group * * @param string $userId ID of the user * @param string $groupid ID of the group - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User added as group subadmin successfully */ + #[AuthorizedAdminSetting(settings:Users::class)] + #[PasswordConfirmationRequired] public function addSubAdmin(string $userId, string $groupid): DataResponse { $group = $this->groupManager->get($groupid); $user = $this->userManager->get($userId); // Check if the user exists if ($user === null) { - throw new OCSException('User does not exist', 101); + throw new OCSException($this->l10n->t('User does not exist'), 101); } // Check if group exists if ($group === null) { - throw new OCSException('Group does not exist', 102); + throw new OCSException($this->l10n->t('Group does not exist'), 102); } // Check if trying to make subadmin of admin group if ($group->getGID() === 'admin') { - throw new OCSException('Cannot create subadmins for admin group', 103); + throw new OCSException($this->l10n->t('Cannot create sub-admins for admin group'), 103); } $subAdminManager = $this->groupManager->getSubAdmin(); @@ -1482,17 +1708,17 @@ class UsersController extends AUserData { } /** - * @PasswordConfirmationRequired - * * Remove a user from the subadmins of a group * * @param string $userId ID of the user * @param string $groupid ID of the group - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: User removed as group subadmin successfully */ + #[AuthorizedAdminSetting(settings:Users::class)] + #[PasswordConfirmationRequired] public function removeSubAdmin(string $userId, string $groupid): DataResponse { $group = $this->groupManager->get($groupid); $user = $this->userManager->get($userId); @@ -1500,15 +1726,15 @@ class UsersController extends AUserData { // Check if the user exists if ($user === null) { - throw new OCSException('User does not exist', 101); + throw new OCSException($this->l10n->t('User does not exist'), 101); } // Check if the group exists if ($group === null) { - throw new OCSException('Group does not exist', 101); + throw new OCSException($this->l10n->t('Group does not exist'), 101); } // Check if they are a subadmin of this said group if (!$subAdminManager->isSubAdminOfGroup($user, $group)) { - throw new OCSException('User is not a subadmin of this group', 102); + throw new OCSException($this->l10n->t('User is not a sub-admin of this group'), 102); } // Go @@ -1520,28 +1746,28 @@ class UsersController extends AUserData { * Get the groups a user is a subadmin of * * @param string $userId ID if the user - * @return DataResponse<Http::STATUS_OK, string[], array{}> + * @return DataResponse<Http::STATUS_OK, list<string>, array{}> * @throws OCSException * * 200: User subadmin groups returned */ + #[AuthorizedAdminSetting(settings:Users::class)] public function getUserSubAdminGroups(string $userId): DataResponse { $groups = $this->getUserSubAdminGroupsData($userId); return new DataResponse($groups); } /** - * @NoAdminRequired - * @PasswordConfirmationRequired - * * Resend the welcome message * * @param string $userId ID if the user - * @return DataResponse<Http::STATUS_OK, array<empty>, array{}> + * @return DataResponse<Http::STATUS_OK, list<empty>, array{}> * @throws OCSException * * 200: Resent welcome message successfully */ + #[PasswordConfirmationRequired] + #[NoAdminRequired] public function resendWelcomeMessage(string $userId): DataResponse { $currentLoggedInUser = $this->userSession->getUser(); @@ -1552,9 +1778,11 @@ class UsersController extends AUserData { // Check if admin / subadmin $subAdminManager = $this->groupManager->getSubAdmin(); + $isAdmin = $this->groupManager->isAdmin($currentLoggedInUser->getUID()); + $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($currentLoggedInUser->getUID()); if ( !$subAdminManager->isUserAccessible($currentLoggedInUser, $targetUser) - && !$this->groupManager->isAdmin($currentLoggedInUser->getUID()) + && !($isAdmin || $isDelegatedAdmin) ) { // No rights throw new OCSException('', OCSController::RESPOND_NOT_FOUND); @@ -1562,11 +1790,16 @@ class UsersController extends AUserData { $email = $targetUser->getEMailAddress(); if ($email === '' || $email === null) { - throw new OCSException('Email address not available', 101); + throw new OCSException($this->l10n->t('Email address not available'), 101); } try { - $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false); + if ($this->config->getUserValue($targetUser->getUID(), 'core', 'lostpassword')) { + $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, true); + } else { + $emailTemplate = $this->newUserMailHelper->generateTemplate($targetUser, false); + } + $this->newUserMailHelper->sendMail($targetUser, $emailTemplate); } catch (\Exception $e) { $this->logger->error( @@ -1576,7 +1809,7 @@ class UsersController extends AUserData { 'exception' => $e, ] ); - throw new OCSException('Sending email failed', 102); + throw new OCSException($this->l10n->t('Sending email failed'), 102); } return new DataResponse(); |