You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

UsersController.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bjoern Schiessle <bjoern@schiessle.org>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. * @author GretaD <gretadoci@gmail.com>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Roeland Jago Douma <roeland@famdouma.nl>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. // FIXME: disabled for now to be able to inject IGroupManager and also use
  31. // getSubAdmin()
  32. //declare(strict_types=1);
  33. namespace OCA\Settings\Controller;
  34. use OC\Accounts\AccountManager;
  35. use OC\AppFramework\Http;
  36. use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
  37. use OC\ForbiddenException;
  38. use OC\Group\Manager as GroupManager;
  39. use OC\L10N\Factory;
  40. use OC\Security\IdentityProof\Manager;
  41. use OC\User\Manager as UserManager;
  42. use OCA\FederatedFileSharing\FederatedShareProvider;
  43. use OCA\Settings\BackgroundJobs\VerifyUserData;
  44. use OCA\Settings\Events\BeforeTemplateRenderedEvent;
  45. use OCA\User_LDAP\User_Proxy;
  46. use OCP\App\IAppManager;
  47. use OCP\AppFramework\Controller;
  48. use OCP\AppFramework\Http\DataResponse;
  49. use OCP\AppFramework\Http\JSONResponse;
  50. use OCP\AppFramework\Http\TemplateResponse;
  51. use OCP\BackgroundJob\IJobList;
  52. use OCP\Encryption\IManager;
  53. use OCP\EventDispatcher\IEventDispatcher;
  54. use OCP\IConfig;
  55. use OCP\IGroupManager;
  56. use OCP\IL10N;
  57. use OCP\IRequest;
  58. use OCP\IUser;
  59. use OCP\IUserManager;
  60. use OCP\IUserSession;
  61. use OCP\L10N\IFactory;
  62. use OCP\Mail\IMailer;
  63. use function in_array;
  64. class UsersController extends Controller {
  65. /** @var UserManager */
  66. private $userManager;
  67. /** @var GroupManager */
  68. private $groupManager;
  69. /** @var IUserSession */
  70. private $userSession;
  71. /** @var IConfig */
  72. private $config;
  73. /** @var bool */
  74. private $isAdmin;
  75. /** @var IL10N */
  76. private $l10n;
  77. /** @var IMailer */
  78. private $mailer;
  79. /** @var Factory */
  80. private $l10nFactory;
  81. /** @var IAppManager */
  82. private $appManager;
  83. /** @var AccountManager */
  84. private $accountManager;
  85. /** @var Manager */
  86. private $keyManager;
  87. /** @var IJobList */
  88. private $jobList;
  89. /** @var IManager */
  90. private $encryptionManager;
  91. /** @var IEventDispatcher */
  92. private $dispatcher;
  93. public function __construct(
  94. string $appName,
  95. IRequest $request,
  96. IUserManager $userManager,
  97. IGroupManager $groupManager,
  98. IUserSession $userSession,
  99. IConfig $config,
  100. bool $isAdmin,
  101. IL10N $l10n,
  102. IMailer $mailer,
  103. IFactory $l10nFactory,
  104. IAppManager $appManager,
  105. AccountManager $accountManager,
  106. Manager $keyManager,
  107. IJobList $jobList,
  108. IManager $encryptionManager,
  109. IEventDispatcher $dispatcher
  110. ) {
  111. parent::__construct($appName, $request);
  112. $this->userManager = $userManager;
  113. $this->groupManager = $groupManager;
  114. $this->userSession = $userSession;
  115. $this->config = $config;
  116. $this->isAdmin = $isAdmin;
  117. $this->l10n = $l10n;
  118. $this->mailer = $mailer;
  119. $this->l10nFactory = $l10nFactory;
  120. $this->appManager = $appManager;
  121. $this->accountManager = $accountManager;
  122. $this->keyManager = $keyManager;
  123. $this->jobList = $jobList;
  124. $this->encryptionManager = $encryptionManager;
  125. $this->dispatcher = $dispatcher;
  126. }
  127. /**
  128. * @NoCSRFRequired
  129. * @NoAdminRequired
  130. *
  131. * Display users list template
  132. *
  133. * @return TemplateResponse
  134. */
  135. public function usersListByGroup() {
  136. return $this->usersList();
  137. }
  138. /**
  139. * @NoCSRFRequired
  140. * @NoAdminRequired
  141. *
  142. * Display users list template
  143. *
  144. * @return TemplateResponse
  145. */
  146. public function usersList() {
  147. $user = $this->userSession->getUser();
  148. $uid = $user->getUID();
  149. \OC::$server->getNavigationManager()->setActiveEntry('core_users');
  150. /* SORT OPTION: SORT_USERCOUNT or SORT_GROUPNAME */
  151. $sortGroupsBy = \OC\Group\MetaData::SORT_USERCOUNT;
  152. $isLDAPUsed = false;
  153. if ($this->config->getSystemValue('sort_groups_by_name', false)) {
  154. $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
  155. } else {
  156. if ($this->appManager->isEnabledForUser('user_ldap')) {
  157. $isLDAPUsed =
  158. $this->groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
  159. if ($isLDAPUsed) {
  160. // LDAP user count can be slow, so we sort by group name here
  161. $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
  162. }
  163. }
  164. }
  165. $canChangePassword = $this->canAdminChangeUserPasswords();
  166. /* GROUPS */
  167. $groupsInfo = new \OC\Group\MetaData(
  168. $uid,
  169. $this->isAdmin,
  170. $this->groupManager,
  171. $this->userSession
  172. );
  173. $groupsInfo->setSorting($sortGroupsBy);
  174. list($adminGroup, $groups) = $groupsInfo->get();
  175. if (!$isLDAPUsed && $this->appManager->isEnabledForUser('user_ldap')) {
  176. $isLDAPUsed = (bool)array_reduce($this->userManager->getBackends(), function ($ldapFound, $backend) {
  177. return $ldapFound || $backend instanceof User_Proxy;
  178. });
  179. }
  180. $disabledUsers = -1;
  181. $userCount = 0;
  182. if (!$isLDAPUsed) {
  183. if ($this->isAdmin) {
  184. $disabledUsers = $this->userManager->countDisabledUsers();
  185. $userCount = array_reduce($this->userManager->countUsers(), function ($v, $w) {
  186. return $v + (int)$w;
  187. }, 0);
  188. } else {
  189. // User is subadmin !
  190. // Map group list to names to retrieve the countDisabledUsersOfGroups
  191. $userGroups = $this->groupManager->getUserGroups($user);
  192. $groupsNames = [];
  193. foreach ($groups as $key => $group) {
  194. // $userCount += (int)$group['usercount'];
  195. array_push($groupsNames, $group['name']);
  196. // we prevent subadmins from looking up themselves
  197. // so we lower the count of the groups he belongs to
  198. if (array_key_exists($group['id'], $userGroups)) {
  199. $groups[$key]['usercount']--;
  200. $userCount -= 1; // we also lower from one the total count
  201. }
  202. }
  203. $userCount += $this->userManager->countUsersOfGroups($groupsInfo->getGroups());
  204. $disabledUsers = $this->userManager->countDisabledUsersOfGroups($groupsNames);
  205. }
  206. $userCount -= $disabledUsers;
  207. }
  208. $disabledUsersGroup = [
  209. 'id' => 'disabled',
  210. 'name' => 'Disabled users',
  211. 'usercount' => $disabledUsers
  212. ];
  213. /* QUOTAS PRESETS */
  214. $quotaPreset = $this->parseQuotaPreset($this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB'));
  215. $defaultQuota = $this->config->getAppValue('files', 'default_quota', 'none');
  216. $event = new BeforeTemplateRenderedEvent();
  217. $this->dispatcher->dispatch('OC\Settings\Users::loadAdditionalScripts', $event);
  218. $this->dispatcher->dispatchTyped($event);
  219. /* LANGUAGES */
  220. $languages = $this->l10nFactory->getLanguages();
  221. /* FINAL DATA */
  222. $serverData = [];
  223. // groups
  224. $serverData['groups'] = array_merge_recursive($adminGroup, [$disabledUsersGroup], $groups);
  225. // Various data
  226. $serverData['isAdmin'] = $this->isAdmin;
  227. $serverData['sortGroups'] = $sortGroupsBy;
  228. $serverData['quotaPreset'] = $quotaPreset;
  229. $serverData['userCount'] = $userCount;
  230. $serverData['languages'] = $languages;
  231. $serverData['defaultLanguage'] = $this->config->getSystemValue('default_language', 'en');
  232. $serverData['forceLanguage'] = $this->config->getSystemValue('force_language', false);
  233. // Settings
  234. $serverData['defaultQuota'] = $defaultQuota;
  235. $serverData['canChangePassword'] = $canChangePassword;
  236. $serverData['newUserGenerateUserID'] = $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes';
  237. $serverData['newUserRequireEmail'] = $this->config->getAppValue('core', 'newUser.requireEmail', 'no') === 'yes';
  238. $serverData['newUserSendEmail'] = $this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes';
  239. return new TemplateResponse('settings', 'settings-vue', ['serverData' => $serverData]);
  240. }
  241. /**
  242. * @param string $key
  243. * @param string $value
  244. *
  245. * @return JSONResponse
  246. */
  247. public function setPreference(string $key, string $value): JSONResponse {
  248. $allowed = ['newUser.sendEmail'];
  249. if (!in_array($key, $allowed, true)) {
  250. return new JSONResponse([], Http::STATUS_FORBIDDEN);
  251. }
  252. $this->config->setAppValue('core', $key, $value);
  253. return new JSONResponse([]);
  254. }
  255. /**
  256. * Parse the app value for quota_present
  257. *
  258. * @param string $quotaPreset
  259. * @return array
  260. */
  261. protected function parseQuotaPreset(string $quotaPreset): array {
  262. // 1 GB, 5 GB, 10 GB => [1 GB, 5 GB, 10 GB]
  263. $presets = array_filter(array_map('trim', explode(',', $quotaPreset)));
  264. // Drop default and none, Make array indexes numerically
  265. return array_values(array_diff($presets, ['default', 'none']));
  266. }
  267. /**
  268. * check if the admin can change the users password
  269. *
  270. * The admin can change the passwords if:
  271. *
  272. * - no encryption module is loaded and encryption is disabled
  273. * - encryption module is loaded but it doesn't require per user keys
  274. *
  275. * The admin can not change the passwords if:
  276. *
  277. * - an encryption module is loaded and it uses per-user keys
  278. * - encryption is enabled but no encryption modules are loaded
  279. *
  280. * @return bool
  281. */
  282. protected function canAdminChangeUserPasswords() {
  283. $isEncryptionEnabled = $this->encryptionManager->isEnabled();
  284. try {
  285. $noUserSpecificEncryptionKeys = !$this->encryptionManager->getEncryptionModule()->needDetailedAccessList();
  286. $isEncryptionModuleLoaded = true;
  287. } catch (ModuleDoesNotExistsException $e) {
  288. $noUserSpecificEncryptionKeys = true;
  289. $isEncryptionModuleLoaded = false;
  290. }
  291. $canChangePassword = ($isEncryptionEnabled && $isEncryptionModuleLoaded && $noUserSpecificEncryptionKeys)
  292. || (!$isEncryptionEnabled && !$isEncryptionModuleLoaded)
  293. || (!$isEncryptionEnabled && $isEncryptionModuleLoaded && $noUserSpecificEncryptionKeys);
  294. return $canChangePassword;
  295. }
  296. /**
  297. * @NoAdminRequired
  298. * @NoSubAdminRequired
  299. * @PasswordConfirmationRequired
  300. *
  301. * @param string $avatarScope
  302. * @param string $displayname
  303. * @param string $displaynameScope
  304. * @param string $phone
  305. * @param string $phoneScope
  306. * @param string $email
  307. * @param string $emailScope
  308. * @param string $website
  309. * @param string $websiteScope
  310. * @param string $address
  311. * @param string $addressScope
  312. * @param string $twitter
  313. * @param string $twitterScope
  314. * @return DataResponse
  315. */
  316. public function setUserSettings($avatarScope,
  317. $displayname,
  318. $displaynameScope,
  319. $phone,
  320. $phoneScope,
  321. $email,
  322. $emailScope,
  323. $website,
  324. $websiteScope,
  325. $address,
  326. $addressScope,
  327. $twitter,
  328. $twitterScope
  329. ) {
  330. $email = strtolower($email);
  331. if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
  332. return new DataResponse(
  333. [
  334. 'status' => 'error',
  335. 'data' => [
  336. 'message' => $this->l10n->t('Invalid mail address')
  337. ]
  338. ],
  339. Http::STATUS_UNPROCESSABLE_ENTITY
  340. );
  341. }
  342. $user = $this->userSession->getUser();
  343. $data = $this->accountManager->getUser($user);
  344. $data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
  345. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  346. $data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
  347. $data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
  348. }
  349. if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
  350. $shareProvider = \OC::$server->query(FederatedShareProvider::class);
  351. if ($shareProvider->isLookupServerUploadEnabled()) {
  352. $data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
  353. $data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
  354. $data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
  355. $data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
  356. }
  357. }
  358. try {
  359. $this->saveUserSettings($user, $data);
  360. return new DataResponse(
  361. [
  362. 'status' => 'success',
  363. 'data' => [
  364. 'userId' => $user->getUID(),
  365. 'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
  366. 'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
  367. 'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
  368. 'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
  369. 'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
  370. 'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
  371. 'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
  372. 'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
  373. 'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
  374. 'message' => $this->l10n->t('Settings saved')
  375. ]
  376. ],
  377. Http::STATUS_OK
  378. );
  379. } catch (ForbiddenException $e) {
  380. return new DataResponse([
  381. 'status' => 'error',
  382. 'data' => [
  383. 'message' => $e->getMessage()
  384. ],
  385. ]);
  386. }
  387. }
  388. /**
  389. * update account manager with new user data
  390. *
  391. * @param IUser $user
  392. * @param array $data
  393. * @throws ForbiddenException
  394. */
  395. protected function saveUserSettings(IUser $user, array $data) {
  396. // keep the user back-end up-to-date with the latest display name and email
  397. // address
  398. $oldDisplayName = $user->getDisplayName();
  399. $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
  400. if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
  401. && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
  402. ) {
  403. $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
  404. if ($result === false) {
  405. throw new ForbiddenException($this->l10n->t('Unable to change full name'));
  406. }
  407. }
  408. $oldEmailAddress = $user->getEMailAddress();
  409. $oldEmailAddress = is_null($oldEmailAddress) ? '' : strtolower($oldEmailAddress);
  410. if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
  411. && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
  412. ) {
  413. // this is the only permission a backend provides and is also used
  414. // for the permission of setting a email address
  415. if (!$user->canChangeDisplayName()) {
  416. throw new ForbiddenException($this->l10n->t('Unable to change email address'));
  417. }
  418. $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
  419. }
  420. $this->accountManager->updateUser($user, $data);
  421. }
  422. /**
  423. * Set the mail address of a user
  424. *
  425. * @NoAdminRequired
  426. * @NoSubAdminRequired
  427. * @PasswordConfirmationRequired
  428. *
  429. * @param string $account
  430. * @param bool $onlyVerificationCode only return verification code without updating the data
  431. * @return DataResponse
  432. */
  433. public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse {
  434. $user = $this->userSession->getUser();
  435. if ($user === null) {
  436. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  437. }
  438. $accountData = $this->accountManager->getUser($user);
  439. $cloudId = $user->getCloudId();
  440. $message = 'Use my Federated Cloud ID to share with me: ' . $cloudId;
  441. $signature = $this->signMessage($user, $message);
  442. $code = $message . ' ' . $signature;
  443. $codeMd5 = $message . ' ' . md5($signature);
  444. switch ($account) {
  445. case 'verify-twitter':
  446. $accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
  447. $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):');
  448. $code = $codeMd5;
  449. $type = AccountManager::PROPERTY_TWITTER;
  450. $data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
  451. $accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
  452. break;
  453. case 'verify-website':
  454. $accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
  455. $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):');
  456. $type = AccountManager::PROPERTY_WEBSITE;
  457. $data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
  458. $accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
  459. break;
  460. default:
  461. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  462. }
  463. if ($onlyVerificationCode === false) {
  464. $this->accountManager->updateUser($user, $accountData);
  465. $this->jobList->add(VerifyUserData::class,
  466. [
  467. 'verificationCode' => $code,
  468. 'data' => $data,
  469. 'type' => $type,
  470. 'uid' => $user->getUID(),
  471. 'try' => 0,
  472. 'lastRun' => $this->getCurrentTime()
  473. ]
  474. );
  475. }
  476. return new DataResponse(['msg' => $msg, 'code' => $code]);
  477. }
  478. /**
  479. * get current timestamp
  480. *
  481. * @return int
  482. */
  483. protected function getCurrentTime(): int {
  484. return time();
  485. }
  486. /**
  487. * sign message with users private key
  488. *
  489. * @param IUser $user
  490. * @param string $message
  491. *
  492. * @return string base64 encoded signature
  493. */
  494. protected function signMessage(IUser $user, string $message): string {
  495. $privateKey = $this->keyManager->getKey($user)->getPrivate();
  496. openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
  497. return base64_encode($signature);
  498. }
  499. }