UsersController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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\ForbiddenException;
  43. use OC\Security\IdentityProof\Manager;
  44. use OCP\App\IAppManager;
  45. use OCP\AppFramework\Controller;
  46. use OCP\AppFramework\Http\DataResponse;
  47. use OCP\AppFramework\Http\TemplateResponse;
  48. use OCP\BackgroundJob\IJobList;
  49. use OCP\Encryption\IManager;
  50. use OCP\IConfig;
  51. use OCP\IGroupManager;
  52. use OCP\IL10N;
  53. use OCP\IRequest;
  54. use OCP\IURLGenerator;
  55. use OCP\IUser;
  56. use OCP\IUserManager;
  57. use OCP\IUserSession;
  58. use OCP\L10N\IFactory;
  59. use OCP\Mail\IMailer;
  60. use OC\Settings\BackgroundJobs\VerifyUserData;
  61. /**
  62. * @package OC\Settings\Controller
  63. */
  64. class UsersController extends Controller {
  65. /** @var IUserManager */
  66. private $userManager;
  67. /** @var IGroupManager */
  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 IFactory */
  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. public function __construct(string $appName,
  92. IRequest $request,
  93. IUserManager $userManager,
  94. IGroupManager $groupManager,
  95. IUserSession $userSession,
  96. IConfig $config,
  97. bool $isAdmin,
  98. IL10N $l10n,
  99. IMailer $mailer,
  100. IFactory $l10nFactory,
  101. IAppManager $appManager,
  102. AccountManager $accountManager,
  103. Manager $keyManager,
  104. IJobList $jobList,
  105. IManager $encryptionManager) {
  106. parent::__construct($appName, $request);
  107. $this->userManager = $userManager;
  108. $this->groupManager = $groupManager;
  109. $this->userSession = $userSession;
  110. $this->config = $config;
  111. $this->isAdmin = $isAdmin;
  112. $this->l10n = $l10n;
  113. $this->mailer = $mailer;
  114. $this->l10nFactory = $l10nFactory;
  115. $this->appManager = $appManager;
  116. $this->accountManager = $accountManager;
  117. $this->keyManager = $keyManager;
  118. $this->jobList = $jobList;
  119. $this->encryptionManager = $encryptionManager;
  120. }
  121. /**
  122. * @NoCSRFRequired
  123. * @NoAdminRequired
  124. *
  125. * Display users list template
  126. *
  127. * @return TemplateResponse
  128. */
  129. public function usersListByGroup() {
  130. return $this->usersList();
  131. }
  132. /**
  133. * @NoCSRFRequired
  134. * @NoAdminRequired
  135. *
  136. * Display users list template
  137. *
  138. * @return TemplateResponse
  139. */
  140. public function usersList() {
  141. $user = $this->userSession->getUser();
  142. $uid = $user->getUID();
  143. \OC::$server->getNavigationManager()->setActiveEntry('core_users');
  144. /* SORT OPTION: SORT_USERCOUNT or SORT_GROUPNAME */
  145. $sortGroupsBy = \OC\Group\MetaData::SORT_USERCOUNT;
  146. if ($this->config->getSystemValue('sort_groups_by_name', false)) {
  147. $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
  148. } else {
  149. $isLDAPUsed = false;
  150. if ($this->appManager->isEnabledForUser('user_ldap')) {
  151. $isLDAPUsed =
  152. $this->groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
  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. /* ENCRYPTION CONFIG */
  161. $isEncryptionEnabled = $this->encryptionManager->isEnabled();
  162. $useMasterKey = $this->config->getAppValue('encryption', 'useMasterKey', true);
  163. // If masterKey enabled, then you can change password. This is to avoid data loss!
  164. $canChangePassword = ($isEncryptionEnabled && $useMasterKey) || $useMasterKey;
  165. /* GROUPS */
  166. $groupsInfo = new \OC\Group\MetaData(
  167. $uid,
  168. $this->isAdmin,
  169. $this->groupManager,
  170. $this->userSession
  171. );
  172. $groupsInfo->setSorting($sortGroupsBy);
  173. list($adminGroup, $groups) = $groupsInfo->get();
  174. if ($this->isAdmin) {
  175. $disabledUsers = $isLDAPUsed ? 0 : $this->userManager->countDisabledUsers();
  176. $userCount = array_reduce($this->userManager->countUsers(), function($v, $w) {
  177. return $v + (int)$w;
  178. }, 0);
  179. } else {
  180. // User is subadmin !
  181. // Map group list to names to retrieve the countDisabledUsersOfGroups
  182. $userGroups = $this->groupManager->getUserGroups($user);
  183. $groupsNames = [];
  184. $userCount = 0;
  185. foreach($groups as $key => $group) {
  186. // $userCount += (int)$group['usercount'];
  187. array_push($groupsNames, $group['name']);
  188. // we prevent subadmins from looking up themselves
  189. // so we lower the count of the groups he belongs to
  190. if (array_key_exists($group['id'], $userGroups)) {
  191. $groups[$key]['usercount']--;
  192. $userCount = -1; // we also lower from one the total count
  193. }
  194. };
  195. $userCount += $this->userManager->countUsersOfGroups($groupsInfo->getGroups());
  196. $disabledUsers = $isLDAPUsed ? 0 : $this->userManager->countDisabledUsersOfGroups($groupsNames);
  197. }
  198. $disabledUsersGroup = [
  199. 'id' => 'disabled',
  200. 'name' => 'Disabled users',
  201. 'usercount' => $disabledUsers
  202. ];
  203. /* QUOTAS PRESETS */
  204. $quotaPreset = $this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
  205. $quotaPreset = explode(',', $quotaPreset);
  206. foreach ($quotaPreset as &$preset) {
  207. $preset = trim($preset);
  208. }
  209. $quotaPreset = array_diff($quotaPreset, array('default', 'none'));
  210. $defaultQuota = $this->config->getAppValue('files', 'default_quota', 'none');
  211. \OC::$server->getEventDispatcher()->dispatch('OC\Settings\Users::loadAdditionalScripts');
  212. /* LANGUAGES */
  213. $languages = $this->l10nFactory->getLanguages();
  214. /* FINAL DATA */
  215. $serverData = array();
  216. // groups
  217. $serverData['groups'] = array_merge_recursive($adminGroup, [$disabledUsersGroup], $groups);
  218. // Various data
  219. $serverData['isAdmin'] = $this->isAdmin;
  220. $serverData['sortGroups'] = $sortGroupsBy;
  221. $serverData['quotaPreset'] = $quotaPreset;
  222. $serverData['userCount'] = $userCount - $disabledUsers;
  223. $serverData['languages'] = $languages;
  224. $serverData['defaultLanguage'] = $this->config->getSystemValue('default_language', 'en');
  225. // Settings
  226. $serverData['defaultQuota'] = $defaultQuota;
  227. $serverData['canChangePassword'] = $canChangePassword;
  228. return new TemplateResponse('settings', 'settings-vue', ['serverData' => $serverData]);
  229. }
  230. /**
  231. * @NoAdminRequired
  232. * @NoSubadminRequired
  233. * @PasswordConfirmationRequired
  234. *
  235. * @param string $avatarScope
  236. * @param string $displayname
  237. * @param string $displaynameScope
  238. * @param string $phone
  239. * @param string $phoneScope
  240. * @param string $email
  241. * @param string $emailScope
  242. * @param string $website
  243. * @param string $websiteScope
  244. * @param string $address
  245. * @param string $addressScope
  246. * @param string $twitter
  247. * @param string $twitterScope
  248. * @return DataResponse
  249. */
  250. public function setUserSettings($avatarScope,
  251. $displayname,
  252. $displaynameScope,
  253. $phone,
  254. $phoneScope,
  255. $email,
  256. $emailScope,
  257. $website,
  258. $websiteScope,
  259. $address,
  260. $addressScope,
  261. $twitter,
  262. $twitterScope
  263. ) {
  264. if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
  265. return new DataResponse(
  266. [
  267. 'status' => 'error',
  268. 'data' => [
  269. 'message' => $this->l10n->t('Invalid mail address')
  270. ]
  271. ],
  272. Http::STATUS_UNPROCESSABLE_ENTITY
  273. );
  274. }
  275. $user = $this->userSession->getUser();
  276. $data = $this->accountManager->getUser($user);
  277. $data[AccountManager::PROPERTY_AVATAR] = ['scope' => $avatarScope];
  278. if ($this->config->getSystemValue('allow_user_to_change_display_name', true) !== false) {
  279. $data[AccountManager::PROPERTY_DISPLAYNAME] = ['value' => $displayname, 'scope' => $displaynameScope];
  280. $data[AccountManager::PROPERTY_EMAIL] = ['value' => $email, 'scope' => $emailScope];
  281. }
  282. if ($this->appManager->isEnabledForUser('federatedfilesharing')) {
  283. $federatedFileSharing = new \OCA\FederatedFileSharing\AppInfo\Application();
  284. $shareProvider = $federatedFileSharing->getFederatedShareProvider();
  285. if ($shareProvider->isLookupServerUploadEnabled()) {
  286. $data[AccountManager::PROPERTY_WEBSITE] = ['value' => $website, 'scope' => $websiteScope];
  287. $data[AccountManager::PROPERTY_ADDRESS] = ['value' => $address, 'scope' => $addressScope];
  288. $data[AccountManager::PROPERTY_PHONE] = ['value' => $phone, 'scope' => $phoneScope];
  289. $data[AccountManager::PROPERTY_TWITTER] = ['value' => $twitter, 'scope' => $twitterScope];
  290. }
  291. }
  292. try {
  293. $this->saveUserSettings($user, $data);
  294. return new DataResponse(
  295. [
  296. 'status' => 'success',
  297. 'data' => [
  298. 'userId' => $user->getUID(),
  299. 'avatarScope' => $data[AccountManager::PROPERTY_AVATAR]['scope'],
  300. 'displayname' => $data[AccountManager::PROPERTY_DISPLAYNAME]['value'],
  301. 'displaynameScope' => $data[AccountManager::PROPERTY_DISPLAYNAME]['scope'],
  302. 'email' => $data[AccountManager::PROPERTY_EMAIL]['value'],
  303. 'emailScope' => $data[AccountManager::PROPERTY_EMAIL]['scope'],
  304. 'website' => $data[AccountManager::PROPERTY_WEBSITE]['value'],
  305. 'websiteScope' => $data[AccountManager::PROPERTY_WEBSITE]['scope'],
  306. 'address' => $data[AccountManager::PROPERTY_ADDRESS]['value'],
  307. 'addressScope' => $data[AccountManager::PROPERTY_ADDRESS]['scope'],
  308. 'message' => $this->l10n->t('Settings saved')
  309. ]
  310. ],
  311. Http::STATUS_OK
  312. );
  313. } catch (ForbiddenException $e) {
  314. return new DataResponse([
  315. 'status' => 'error',
  316. 'data' => [
  317. 'message' => $e->getMessage()
  318. ],
  319. ]);
  320. }
  321. }
  322. /**
  323. * update account manager with new user data
  324. *
  325. * @param IUser $user
  326. * @param array $data
  327. * @throws ForbiddenException
  328. */
  329. protected function saveUserSettings(IUser $user, array $data) {
  330. // keep the user back-end up-to-date with the latest display name and email
  331. // address
  332. $oldDisplayName = $user->getDisplayName();
  333. $oldDisplayName = is_null($oldDisplayName) ? '' : $oldDisplayName;
  334. if (isset($data[AccountManager::PROPERTY_DISPLAYNAME]['value'])
  335. && $oldDisplayName !== $data[AccountManager::PROPERTY_DISPLAYNAME]['value']
  336. ) {
  337. $result = $user->setDisplayName($data[AccountManager::PROPERTY_DISPLAYNAME]['value']);
  338. if ($result === false) {
  339. throw new ForbiddenException($this->l10n->t('Unable to change full name'));
  340. }
  341. }
  342. $oldEmailAddress = $user->getEMailAddress();
  343. $oldEmailAddress = is_null($oldEmailAddress) ? '' : $oldEmailAddress;
  344. if (isset($data[AccountManager::PROPERTY_EMAIL]['value'])
  345. && $oldEmailAddress !== $data[AccountManager::PROPERTY_EMAIL]['value']
  346. ) {
  347. // this is the only permission a backend provides and is also used
  348. // for the permission of setting a email address
  349. if (!$user->canChangeDisplayName()) {
  350. throw new ForbiddenException($this->l10n->t('Unable to change email address'));
  351. }
  352. $user->setEMailAddress($data[AccountManager::PROPERTY_EMAIL]['value']);
  353. }
  354. $this->accountManager->updateUser($user, $data);
  355. }
  356. /**
  357. * Set the mail address of a user
  358. *
  359. * @NoAdminRequired
  360. * @NoSubadminRequired
  361. * @PasswordConfirmationRequired
  362. *
  363. * @param string $account
  364. * @param bool $onlyVerificationCode only return verification code without updating the data
  365. * @return DataResponse
  366. */
  367. public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse {
  368. $user = $this->userSession->getUser();
  369. if ($user === null) {
  370. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  371. }
  372. $accountData = $this->accountManager->getUser($user);
  373. $cloudId = $user->getCloudId();
  374. $message = 'Use my Federated Cloud ID to share with me: ' . $cloudId;
  375. $signature = $this->signMessage($user, $message);
  376. $code = $message . ' ' . $signature;
  377. $codeMd5 = $message . ' ' . md5($signature);
  378. switch ($account) {
  379. case 'verify-twitter':
  380. $accountData[AccountManager::PROPERTY_TWITTER]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
  381. $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):');
  382. $code = $codeMd5;
  383. $type = AccountManager::PROPERTY_TWITTER;
  384. $data = $accountData[AccountManager::PROPERTY_TWITTER]['value'];
  385. $accountData[AccountManager::PROPERTY_TWITTER]['signature'] = $signature;
  386. break;
  387. case 'verify-website':
  388. $accountData[AccountManager::PROPERTY_WEBSITE]['verified'] = AccountManager::VERIFICATION_IN_PROGRESS;
  389. $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):');
  390. $type = AccountManager::PROPERTY_WEBSITE;
  391. $data = $accountData[AccountManager::PROPERTY_WEBSITE]['value'];
  392. $accountData[AccountManager::PROPERTY_WEBSITE]['signature'] = $signature;
  393. break;
  394. default:
  395. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  396. }
  397. if ($onlyVerificationCode === false) {
  398. $this->accountManager->updateUser($user, $accountData);
  399. $this->jobList->add(VerifyUserData::class,
  400. [
  401. 'verificationCode' => $code,
  402. 'data' => $data,
  403. 'type' => $type,
  404. 'uid' => $user->getUID(),
  405. 'try' => 0,
  406. 'lastRun' => $this->getCurrentTime()
  407. ]
  408. );
  409. }
  410. return new DataResponse(['msg' => $msg, 'code' => $code]);
  411. }
  412. /**
  413. * get current timestamp
  414. *
  415. * @return int
  416. */
  417. protected function getCurrentTime(): int {
  418. return time();
  419. }
  420. /**
  421. * sign message with users private key
  422. *
  423. * @param IUser $user
  424. * @param string $message
  425. *
  426. * @return string base64 encoded signature
  427. */
  428. protected function signMessage(IUser $user, string $message): string {
  429. $privateKey = $this->keyManager->getKey($user)->getPrivate();
  430. openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
  431. return base64_encode($signature);
  432. }
  433. }