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 16KB

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