UsersController.php 20 KB

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