123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604 |
- <?php
- declare(strict_types=1);
- namespace OCA\Settings\Controller;
- use InvalidArgumentException;
- use OC\AppFramework\Http;
- use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
- use OC\ForbiddenException;
- use OC\Group\Manager as GroupManager;
- use OC\KnownUser\KnownUserService;
- use OC\L10N\Factory;
- use OC\Security\IdentityProof\Manager;
- use OC\User\Manager as UserManager;
- use OCA\Settings\BackgroundJobs\VerifyUserData;
- use OCA\Settings\Events\BeforeTemplateRenderedEvent;
- use OCA\User_LDAP\User_Proxy;
- use OCP\Accounts\IAccount;
- use OCP\Accounts\IAccountManager;
- use OCP\Accounts\PropertyDoesNotExistException;
- use OCP\App\IAppManager;
- use OCP\AppFramework\Controller;
- use OCP\AppFramework\Http\Attribute\IgnoreOpenAPI;
- use OCP\AppFramework\Http\DataResponse;
- use OCP\AppFramework\Http\JSONResponse;
- use OCP\AppFramework\Http\TemplateResponse;
- use OCP\BackgroundJob\IJobList;
- use OCP\Encryption\IManager;
- use OCP\EventDispatcher\IEventDispatcher;
- use OCP\IConfig;
- use OCP\IGroupManager;
- use OCP\IL10N;
- use OCP\IRequest;
- use OCP\IUser;
- use OCP\IUserManager;
- use OCP\IUserSession;
- use OCP\L10N\IFactory;
- use OCP\Mail\IMailer;
- use function in_array;
- class UsersController extends Controller {
-
- private $userManager;
-
- private $groupManager;
-
- private $userSession;
-
- private $config;
-
- private $isAdmin;
-
- private $l10n;
-
- private $mailer;
-
- private $l10nFactory;
-
- private $appManager;
-
- private $accountManager;
-
- private $keyManager;
-
- private $jobList;
-
- private $encryptionManager;
-
- private $knownUserService;
-
- private $dispatcher;
- public function __construct(
- string $appName,
- IRequest $request,
- IUserManager $userManager,
- IGroupManager $groupManager,
- IUserSession $userSession,
- IConfig $config,
- bool $isAdmin,
- IL10N $l10n,
- IMailer $mailer,
- IFactory $l10nFactory,
- IAppManager $appManager,
- IAccountManager $accountManager,
- Manager $keyManager,
- IJobList $jobList,
- IManager $encryptionManager,
- KnownUserService $knownUserService,
- IEventDispatcher $dispatcher
- ) {
- parent::__construct($appName, $request);
- $this->userManager = $userManager;
- $this->groupManager = $groupManager;
- $this->userSession = $userSession;
- $this->config = $config;
- $this->isAdmin = $isAdmin;
- $this->l10n = $l10n;
- $this->mailer = $mailer;
- $this->l10nFactory = $l10nFactory;
- $this->appManager = $appManager;
- $this->accountManager = $accountManager;
- $this->keyManager = $keyManager;
- $this->jobList = $jobList;
- $this->encryptionManager = $encryptionManager;
- $this->knownUserService = $knownUserService;
- $this->dispatcher = $dispatcher;
- }
-
- public function usersListByGroup(): TemplateResponse {
- return $this->usersList();
- }
-
- public function usersList(): TemplateResponse {
- $user = $this->userSession->getUser();
- $uid = $user->getUID();
- \OC::$server->getNavigationManager()->setActiveEntry('core_users');
-
- $sortGroupsBy = \OC\Group\MetaData::SORT_USERCOUNT;
- $isLDAPUsed = false;
- if ($this->config->getSystemValue('sort_groups_by_name', false)) {
- $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
- } else {
- if ($this->appManager->isEnabledForUser('user_ldap')) {
- $isLDAPUsed =
- $this->groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
- if ($isLDAPUsed) {
-
- $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
- }
- }
- }
- $canChangePassword = $this->canAdminChangeUserPasswords();
-
- $groupsInfo = new \OC\Group\MetaData(
- $uid,
- $this->isAdmin,
- $this->groupManager,
- $this->userSession
- );
- $groupsInfo->setSorting($sortGroupsBy);
- [$adminGroup, $groups] = $groupsInfo->get();
- if (!$isLDAPUsed && $this->appManager->isEnabledForUser('user_ldap')) {
- $isLDAPUsed = (bool)array_reduce($this->userManager->getBackends(), function ($ldapFound, $backend) {
- return $ldapFound || $backend instanceof User_Proxy;
- });
- }
- $disabledUsers = -1;
- $userCount = 0;
- if (!$isLDAPUsed) {
- if ($this->isAdmin) {
- $disabledUsers = $this->userManager->countDisabledUsers();
- $userCount = array_reduce($this->userManager->countUsers(), function ($v, $w) {
- return $v + (int)$w;
- }, 0);
- } else {
-
-
- $userGroups = $this->groupManager->getUserGroups($user);
- $groupsNames = [];
- foreach ($groups as $key => $group) {
-
- $groupsNames[] = $group['name'];
-
-
- if (array_key_exists($group['id'], $userGroups)) {
- $groups[$key]['usercount']--;
- $userCount -= 1;
- }
- }
- $userCount += $this->userManager->countUsersOfGroups($groupsInfo->getGroups());
- $disabledUsers = $this->userManager->countDisabledUsersOfGroups($groupsNames);
- }
- $userCount -= $disabledUsers;
- }
- $disabledUsersGroup = [
- 'id' => 'disabled',
- 'name' => 'Disabled users',
- 'usercount' => $disabledUsers
- ];
-
- $quotaPreset = $this->parseQuotaPreset($this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB'));
- $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
- if (!$allowUnlimitedQuota && count($quotaPreset) > 0) {
- $defaultQuota = $this->config->getAppValue('files', 'default_quota', $quotaPreset[0]);
- } else {
- $defaultQuota = $this->config->getAppValue('files', 'default_quota', 'none');
- }
- $event = new BeforeTemplateRenderedEvent();
- $this->dispatcher->dispatch('OC\Settings\Users::loadAdditionalScripts', $event);
- $this->dispatcher->dispatchTyped($event);
-
- $languages = $this->l10nFactory->getLanguages();
-
- $serverData = [];
-
- $serverData['groups'] = array_merge_recursive($adminGroup, [$disabledUsersGroup], $groups);
-
- $serverData['isAdmin'] = $this->isAdmin;
- $serverData['sortGroups'] = $sortGroupsBy;
- $serverData['quotaPreset'] = $quotaPreset;
- $serverData['allowUnlimitedQuota'] = $allowUnlimitedQuota;
- $serverData['userCount'] = $userCount;
- $serverData['languages'] = $languages;
- $serverData['defaultLanguage'] = $this->config->getSystemValue('default_language', 'en');
- $serverData['forceLanguage'] = $this->config->getSystemValue('force_language', false);
-
- $serverData['defaultQuota'] = $defaultQuota;
- $serverData['canChangePassword'] = $canChangePassword;
- $serverData['newUserGenerateUserID'] = $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes';
- $serverData['newUserRequireEmail'] = $this->config->getAppValue('core', 'newUser.requireEmail', 'no') === 'yes';
- $serverData['newUserSendEmail'] = $this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes';
- return new TemplateResponse('settings', 'settings-vue', ['serverData' => $serverData, 'pageTitle' => $this->l10n->t('Users')]);
- }
-
- public function setPreference(string $key, string $value): JSONResponse {
- $allowed = ['newUser.sendEmail'];
- if (!in_array($key, $allowed, true)) {
- return new JSONResponse([], Http::STATUS_FORBIDDEN);
- }
- $this->config->setAppValue('core', $key, $value);
- return new JSONResponse([]);
- }
-
- protected function parseQuotaPreset(string $quotaPreset): array {
-
- $presets = array_filter(array_map('trim', explode(',', $quotaPreset)));
-
- return array_values(array_diff($presets, ['default', 'none']));
- }
-
- protected function canAdminChangeUserPasswords(): bool {
- $isEncryptionEnabled = $this->encryptionManager->isEnabled();
- try {
- $noUserSpecificEncryptionKeys = !$this->encryptionManager->getEncryptionModule()->needDetailedAccessList();
- $isEncryptionModuleLoaded = true;
- } catch (ModuleDoesNotExistsException $e) {
- $noUserSpecificEncryptionKeys = true;
- $isEncryptionModuleLoaded = false;
- }
- $canChangePassword = ($isEncryptionModuleLoaded && $noUserSpecificEncryptionKeys)
- || (!$isEncryptionModuleLoaded && !$isEncryptionEnabled);
- return $canChangePassword;
- }
-
- public function setUserSettings(?string $avatarScope = null,
- ?string $displayname = null,
- ?string $displaynameScope = null,
- ?string $phone = null,
- ?string $phoneScope = null,
- ?string $email = null,
- ?string $emailScope = null,
- ?string $website = null,
- ?string $websiteScope = null,
- ?string $address = null,
- ?string $addressScope = null,
- ?string $twitter = null,
- ?string $twitterScope = null,
- ?string $fediverse = null,
- ?string $fediverseScope = null
- ) {
- $user = $this->userSession->getUser();
- if (!$user instanceof IUser) {
- return new DataResponse(
- [
- 'status' => 'error',
- 'data' => [
- 'message' => $this->l10n->t('Invalid user')
- ]
- ],
- Http::STATUS_UNAUTHORIZED
- );
- }
- $email = !is_null($email) ? strtolower($email) : $email;
- if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
- return new DataResponse(
- [
- 'status' => 'error',
- 'data' => [
- 'message' => $this->l10n->t('Invalid mail address')
- ]
- ],
- Http::STATUS_UNPROCESSABLE_ENTITY
- );
- }
- $userAccount = $this->accountManager->getAccount($user);
- $oldPhoneValue = $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue();
- $updatable = [
- IAccountManager::PROPERTY_AVATAR => ['value' => null, 'scope' => $avatarScope],
- IAccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
- IAccountManager::PROPERTY_EMAIL => ['value' => $email, 'scope' => $emailScope],
- IAccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
- IAccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
- IAccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
- IAccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope],
- IAccountManager::PROPERTY_FEDIVERSE => ['value' => $fediverse, 'scope' => $fediverseScope],
- ];
- $allowUserToChangeDisplayName = $this->config->getSystemValueBool('allow_user_to_change_display_name', true);
- foreach ($updatable as $property => $data) {
- if ($allowUserToChangeDisplayName === false
- && in_array($property, [IAccountManager::PROPERTY_DISPLAYNAME, IAccountManager::PROPERTY_EMAIL], true)) {
- continue;
- }
- $property = $userAccount->getProperty($property);
- if (null !== $data['value']) {
- $property->setValue($data['value']);
- }
- if (null !== $data['scope']) {
- $property->setScope($data['scope']);
- }
- }
- try {
- $this->saveUserSettings($userAccount);
- if ($oldPhoneValue !== $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue()) {
- $this->knownUserService->deleteByContactUserId($user->getUID());
- }
- return new DataResponse(
- [
- 'status' => 'success',
- 'data' => [
- 'userId' => $user->getUID(),
- 'avatarScope' => $userAccount->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope(),
- 'displayname' => $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue(),
- 'displaynameScope' => $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getScope(),
- 'phone' => $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue(),
- 'phoneScope' => $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getScope(),
- 'email' => $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue(),
- 'emailScope' => $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getScope(),
- 'website' => $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE)->getValue(),
- 'websiteScope' => $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE)->getScope(),
- 'address' => $userAccount->getProperty(IAccountManager::PROPERTY_ADDRESS)->getValue(),
- 'addressScope' => $userAccount->getProperty(IAccountManager::PROPERTY_ADDRESS)->getScope(),
- 'twitter' => $userAccount->getProperty(IAccountManager::PROPERTY_TWITTER)->getValue(),
- 'twitterScope' => $userAccount->getProperty(IAccountManager::PROPERTY_TWITTER)->getScope(),
- 'fediverse' => $userAccount->getProperty(IAccountManager::PROPERTY_FEDIVERSE)->getValue(),
- 'fediverseScope' => $userAccount->getProperty(IAccountManager::PROPERTY_FEDIVERSE)->getScope(),
- 'message' => $this->l10n->t('Settings saved'),
- ],
- ],
- Http::STATUS_OK
- );
- } catch (ForbiddenException | InvalidArgumentException | PropertyDoesNotExistException $e) {
- return new DataResponse([
- 'status' => 'error',
- 'data' => [
- 'message' => $e->getMessage()
- ],
- ]);
- }
- }
-
- protected function saveUserSettings(IAccount $userAccount): void {
-
-
- $oldDisplayName = $userAccount->getUser()->getDisplayName();
- if ($oldDisplayName !== $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue()) {
- $result = $userAccount->getUser()->setDisplayName($userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue());
- if ($result === false) {
- throw new ForbiddenException($this->l10n->t('Unable to change full name'));
- }
- }
- $oldEmailAddress = $userAccount->getUser()->getSystemEMailAddress();
- $oldEmailAddress = strtolower((string)$oldEmailAddress);
- if ($oldEmailAddress !== strtolower($userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue())) {
-
-
- if (!$userAccount->getUser()->canChangeDisplayName()) {
- throw new ForbiddenException($this->l10n->t('Unable to change email address'));
- }
- $userAccount->getUser()->setSystemEMailAddress($userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue());
- }
- try {
- $this->accountManager->updateAccount($userAccount);
- } catch (InvalidArgumentException $e) {
- if ($e->getMessage() === IAccountManager::PROPERTY_PHONE) {
- throw new InvalidArgumentException($this->l10n->t('Unable to set invalid phone number'));
- }
- if ($e->getMessage() === IAccountManager::PROPERTY_WEBSITE) {
- throw new InvalidArgumentException($this->l10n->t('Unable to set invalid website'));
- }
- throw new InvalidArgumentException($this->l10n->t('Some account data was invalid'));
- }
- }
-
- public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse {
- $user = $this->userSession->getUser();
- if ($user === null) {
- return new DataResponse([], Http::STATUS_BAD_REQUEST);
- }
- $userAccount = $this->accountManager->getAccount($user);
- $cloudId = $user->getCloudId();
- $message = 'Use my Federated Cloud ID to share with me: ' . $cloudId;
- $signature = $this->signMessage($user, $message);
- $code = $message . ' ' . $signature;
- $codeMd5 = $message . ' ' . md5($signature);
- switch ($account) {
- case 'verify-twitter':
- $msg = $this->l10n->t('In order to verify your Twitter account, post the following tweet on Twitter (please make sure to post it without any line breaks):');
- $code = $codeMd5;
- $type = IAccountManager::PROPERTY_TWITTER;
- break;
- case 'verify-website':
- $msg = $this->l10n->t('In order to verify your Website, store the following content in your web-root at \'.well-known/CloudIdVerificationCode.txt\' (please make sure that the complete text is in one line):');
- $type = IAccountManager::PROPERTY_WEBSITE;
- break;
- default:
- return new DataResponse([], Http::STATUS_BAD_REQUEST);
- }
- $userProperty = $userAccount->getProperty($type);
- $userProperty
- ->setVerified(IAccountManager::VERIFICATION_IN_PROGRESS)
- ->setVerificationData($signature);
- if ($onlyVerificationCode === false) {
- $this->accountManager->updateAccount($userAccount);
- $this->jobList->add(VerifyUserData::class,
- [
- 'verificationCode' => $code,
- 'data' => $userProperty->getValue(),
- 'type' => $type,
- 'uid' => $user->getUID(),
- 'try' => 0,
- 'lastRun' => $this->getCurrentTime()
- ]
- );
- }
- return new DataResponse(['msg' => $msg, 'code' => $code]);
- }
-
- protected function getCurrentTime(): int {
- return time();
- }
-
- protected function signMessage(IUser $user, string $message): string {
- $privateKey = $this->keyManager->getKey($user)->getPrivate();
- openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
- return base64_encode($signature);
- }
- }
|