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

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