1
0

UsersController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OCA\Settings\Controller;
  9. use InvalidArgumentException;
  10. use OC\AppFramework\Http;
  11. use OC\Encryption\Exceptions\ModuleDoesNotExistsException;
  12. use OC\ForbiddenException;
  13. use OC\KnownUser\KnownUserService;
  14. use OC\Security\IdentityProof\Manager;
  15. use OC\User\Manager as UserManager;
  16. use OCA\Settings\BackgroundJobs\VerifyUserData;
  17. use OCA\Settings\Events\BeforeTemplateRenderedEvent;
  18. use OCA\Settings\Settings\Admin\Users;
  19. use OCA\User_LDAP\User_Proxy;
  20. use OCP\Accounts\IAccount;
  21. use OCP\Accounts\IAccountManager;
  22. use OCP\Accounts\PropertyDoesNotExistException;
  23. use OCP\App\IAppManager;
  24. use OCP\AppFramework\Controller;
  25. use OCP\AppFramework\Http\Attribute\AuthorizedAdminSetting;
  26. use OCP\AppFramework\Http\Attribute\NoAdminRequired;
  27. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  28. use OCP\AppFramework\Http\Attribute\OpenAPI;
  29. use OCP\AppFramework\Http\Attribute\PasswordConfirmationRequired;
  30. use OCP\AppFramework\Http\DataResponse;
  31. use OCP\AppFramework\Http\JSONResponse;
  32. use OCP\AppFramework\Http\TemplateResponse;
  33. use OCP\AppFramework\Services\IInitialState;
  34. use OCP\BackgroundJob\IJobList;
  35. use OCP\Encryption\IManager;
  36. use OCP\EventDispatcher\IEventDispatcher;
  37. use OCP\IConfig;
  38. use OCP\IGroupManager;
  39. use OCP\IL10N;
  40. use OCP\IRequest;
  41. use OCP\IUser;
  42. use OCP\IUserSession;
  43. use OCP\L10N\IFactory;
  44. use OCP\Mail\IMailer;
  45. use function in_array;
  46. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  47. class UsersController extends Controller {
  48. public function __construct(
  49. string $appName,
  50. IRequest $request,
  51. private UserManager $userManager,
  52. private IGroupManager $groupManager,
  53. private IUserSession $userSession,
  54. private IConfig $config,
  55. private IL10N $l10n,
  56. private IMailer $mailer,
  57. private IFactory $l10nFactory,
  58. private IAppManager $appManager,
  59. private IAccountManager $accountManager,
  60. private Manager $keyManager,
  61. private IJobList $jobList,
  62. private IManager $encryptionManager,
  63. private KnownUserService $knownUserService,
  64. private IEventDispatcher $dispatcher,
  65. private IInitialState $initialState,
  66. ) {
  67. parent::__construct($appName, $request);
  68. }
  69. /**
  70. * Display users list template
  71. *
  72. * @return TemplateResponse
  73. */
  74. #[NoAdminRequired]
  75. #[NoCSRFRequired]
  76. public function usersListByGroup(): TemplateResponse {
  77. return $this->usersList();
  78. }
  79. /**
  80. * Display users list template
  81. *
  82. * @return TemplateResponse
  83. */
  84. #[NoAdminRequired]
  85. #[NoCSRFRequired]
  86. public function usersList(): TemplateResponse {
  87. $user = $this->userSession->getUser();
  88. $uid = $user->getUID();
  89. $isAdmin = $this->groupManager->isAdmin($uid);
  90. $isDelegatedAdmin = $this->groupManager->isDelegatedAdmin($uid);
  91. \OC::$server->getNavigationManager()->setActiveEntry('core_users');
  92. /* SORT OPTION: SORT_USERCOUNT or SORT_GROUPNAME */
  93. $sortGroupsBy = \OC\Group\MetaData::SORT_USERCOUNT;
  94. $isLDAPUsed = false;
  95. if ($this->config->getSystemValueBool('sort_groups_by_name', false)) {
  96. $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
  97. } else {
  98. if ($this->appManager->isEnabledForUser('user_ldap')) {
  99. $isLDAPUsed =
  100. $this->groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
  101. if ($isLDAPUsed) {
  102. // LDAP user count can be slow, so we sort by group name here
  103. $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
  104. }
  105. }
  106. }
  107. $canChangePassword = $this->canAdminChangeUserPasswords();
  108. /* GROUPS */
  109. $groupsInfo = new \OC\Group\MetaData(
  110. $uid,
  111. $isAdmin,
  112. $isDelegatedAdmin,
  113. $this->groupManager,
  114. $this->userSession
  115. );
  116. $groupsInfo->setSorting($sortGroupsBy);
  117. [$adminGroup, $groups] = $groupsInfo->get();
  118. if (!$isLDAPUsed && $this->appManager->isEnabledForUser('user_ldap')) {
  119. $isLDAPUsed = (bool)array_reduce($this->userManager->getBackends(), function ($ldapFound, $backend) {
  120. return $ldapFound || $backend instanceof User_Proxy;
  121. });
  122. }
  123. $disabledUsers = -1;
  124. $userCount = 0;
  125. if (!$isLDAPUsed) {
  126. if ($isAdmin || $isDelegatedAdmin) {
  127. $disabledUsers = $this->userManager->countDisabledUsers();
  128. $userCount = array_reduce($this->userManager->countUsers(), function ($v, $w) {
  129. return $v + (int)$w;
  130. }, 0);
  131. } else {
  132. // User is subadmin !
  133. // Map group list to ids to retrieve the countDisabledUsersOfGroups
  134. $userGroups = $this->groupManager->getUserGroups($user);
  135. $groupsIds = [];
  136. foreach ($groups as $key => $group) {
  137. // $userCount += (int)$group['usercount'];
  138. $groupsIds[] = $group['id'];
  139. // we prevent subadmins from looking up themselves
  140. // so we lower the count of the groups he belongs to
  141. if (array_key_exists($group['id'], $userGroups)) {
  142. $groups[$key]['usercount']--;
  143. $userCount -= 1; // we also lower from one the total count
  144. }
  145. }
  146. $userCount += $this->userManager->countUsersOfGroups($groupsInfo->getGroups());
  147. $disabledUsers = $this->userManager->countDisabledUsersOfGroups($groupsIds);
  148. }
  149. $userCount -= $disabledUsers;
  150. }
  151. $recentUsersGroup = [
  152. 'id' => '__nc_internal_recent',
  153. 'name' => $this->l10n->t('Recently active'),
  154. 'usercount' => $userCount,
  155. ];
  156. $disabledUsersGroup = [
  157. 'id' => 'disabled',
  158. 'name' => $this->l10n->t('Disabled accounts'),
  159. 'usercount' => $disabledUsers
  160. ];
  161. /* QUOTAS PRESETS */
  162. $quotaPreset = $this->parseQuotaPreset($this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB'));
  163. $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
  164. if (!$allowUnlimitedQuota && count($quotaPreset) > 0) {
  165. $defaultQuota = $this->config->getAppValue('files', 'default_quota', $quotaPreset[0]);
  166. } else {
  167. $defaultQuota = $this->config->getAppValue('files', 'default_quota', 'none');
  168. }
  169. $event = new BeforeTemplateRenderedEvent();
  170. $this->dispatcher->dispatch('OC\Settings\Users::loadAdditionalScripts', $event);
  171. $this->dispatcher->dispatchTyped($event);
  172. /* LANGUAGES */
  173. $languages = $this->l10nFactory->getLanguages();
  174. /** Using LDAP or admins (system config) can enfore sorting by group name, in this case the frontend setting is overwritten */
  175. $forceSortGroupByName = $sortGroupsBy === \OC\Group\MetaData::SORT_GROUPNAME;
  176. /* FINAL DATA */
  177. $serverData = [];
  178. // groups
  179. $serverData['groups'] = array_merge_recursive($adminGroup, [$recentUsersGroup, $disabledUsersGroup], $groups);
  180. // Various data
  181. $serverData['isAdmin'] = $isAdmin;
  182. $serverData['isDelegatedAdmin'] = $isDelegatedAdmin;
  183. $serverData['sortGroups'] = $forceSortGroupByName
  184. ? \OC\Group\MetaData::SORT_GROUPNAME
  185. : (int)$this->config->getAppValue('core', 'group.sortBy', (string)\OC\Group\MetaData::SORT_USERCOUNT);
  186. $serverData['forceSortGroupByName'] = $forceSortGroupByName;
  187. $serverData['quotaPreset'] = $quotaPreset;
  188. $serverData['allowUnlimitedQuota'] = $allowUnlimitedQuota;
  189. $serverData['userCount'] = $userCount;
  190. $serverData['languages'] = $languages;
  191. $serverData['defaultLanguage'] = $this->config->getSystemValue('default_language', 'en');
  192. $serverData['forceLanguage'] = $this->config->getSystemValue('force_language', false);
  193. // Settings
  194. $serverData['defaultQuota'] = $defaultQuota;
  195. $serverData['canChangePassword'] = $canChangePassword;
  196. $serverData['newUserGenerateUserID'] = $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes';
  197. $serverData['newUserRequireEmail'] = $this->config->getAppValue('core', 'newUser.requireEmail', 'no') === 'yes';
  198. $serverData['newUserSendEmail'] = $this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes';
  199. $this->initialState->provideInitialState('usersSettings', $serverData);
  200. \OCP\Util::addStyle('settings', 'settings');
  201. \OCP\Util::addScript('settings', 'vue-settings-apps-users-management');
  202. return new TemplateResponse('settings', 'settings/empty', ['pageTitle' => $this->l10n->t('Settings')]);
  203. }
  204. /**
  205. * @param string $key
  206. * @param string $value
  207. *
  208. * @return JSONResponse
  209. */
  210. #[AuthorizedAdminSetting(settings:Users::class)]
  211. public function setPreference(string $key, string $value): JSONResponse {
  212. $allowed = ['newUser.sendEmail', 'group.sortBy'];
  213. if (!in_array($key, $allowed, true)) {
  214. return new JSONResponse([], Http::STATUS_FORBIDDEN);
  215. }
  216. $this->config->setAppValue('core', $key, $value);
  217. return new JSONResponse([]);
  218. }
  219. /**
  220. * Parse the app value for quota_present
  221. *
  222. * @param string $quotaPreset
  223. * @return array
  224. */
  225. protected function parseQuotaPreset(string $quotaPreset): array {
  226. // 1 GB, 5 GB, 10 GB => [1 GB, 5 GB, 10 GB]
  227. $presets = array_filter(array_map('trim', explode(',', $quotaPreset)));
  228. // Drop default and none, Make array indexes numerically
  229. return array_values(array_diff($presets, ['default', 'none']));
  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(): bool {
  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 = ($isEncryptionModuleLoaded && $noUserSpecificEncryptionKeys)
  256. || (!$isEncryptionModuleLoaded && !$isEncryptionEnabled);
  257. return $canChangePassword;
  258. }
  259. /**
  260. * @NoSubAdminRequired
  261. *
  262. * @param string|null $avatarScope
  263. * @param string|null $displayname
  264. * @param string|null $displaynameScope
  265. * @param string|null $phone
  266. * @param string|null $phoneScope
  267. * @param string|null $email
  268. * @param string|null $emailScope
  269. * @param string|null $website
  270. * @param string|null $websiteScope
  271. * @param string|null $address
  272. * @param string|null $addressScope
  273. * @param string|null $twitter
  274. * @param string|null $twitterScope
  275. * @param string|null $fediverse
  276. * @param string|null $fediverseScope
  277. * @param string|null $birthdate
  278. * @param string|null $birthdateScope
  279. *
  280. * @return DataResponse
  281. */
  282. #[NoAdminRequired]
  283. #[PasswordConfirmationRequired]
  284. public function setUserSettings(?string $avatarScope = null,
  285. ?string $displayname = null,
  286. ?string $displaynameScope = null,
  287. ?string $phone = null,
  288. ?string $phoneScope = null,
  289. ?string $email = null,
  290. ?string $emailScope = null,
  291. ?string $website = null,
  292. ?string $websiteScope = null,
  293. ?string $address = null,
  294. ?string $addressScope = null,
  295. ?string $twitter = null,
  296. ?string $twitterScope = null,
  297. ?string $fediverse = null,
  298. ?string $fediverseScope = null,
  299. ?string $birthdate = null,
  300. ?string $birthdateScope = null,
  301. ?string $pronouns = null,
  302. ?string $pronounsScope = null,
  303. ) {
  304. $user = $this->userSession->getUser();
  305. if (!$user instanceof IUser) {
  306. return new DataResponse(
  307. [
  308. 'status' => 'error',
  309. 'data' => [
  310. 'message' => $this->l10n->t('Invalid account')
  311. ]
  312. ],
  313. Http::STATUS_UNAUTHORIZED
  314. );
  315. }
  316. $email = !is_null($email) ? strtolower($email) : $email;
  317. if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
  318. return new DataResponse(
  319. [
  320. 'status' => 'error',
  321. 'data' => [
  322. 'message' => $this->l10n->t('Invalid mail address')
  323. ]
  324. ],
  325. Http::STATUS_UNPROCESSABLE_ENTITY
  326. );
  327. }
  328. $userAccount = $this->accountManager->getAccount($user);
  329. $oldPhoneValue = $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue();
  330. $updatable = [
  331. IAccountManager::PROPERTY_AVATAR => ['value' => null, 'scope' => $avatarScope],
  332. IAccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
  333. IAccountManager::PROPERTY_EMAIL => ['value' => $email, 'scope' => $emailScope],
  334. IAccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
  335. IAccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
  336. IAccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
  337. IAccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope],
  338. IAccountManager::PROPERTY_FEDIVERSE => ['value' => $fediverse, 'scope' => $fediverseScope],
  339. IAccountManager::PROPERTY_BIRTHDATE => ['value' => $birthdate, 'scope' => $birthdateScope],
  340. IAccountManager::PROPERTY_PRONOUNS => ['value' => $pronouns, 'scope' => $pronounsScope],
  341. ];
  342. $allowUserToChangeDisplayName = $this->config->getSystemValueBool('allow_user_to_change_display_name', true);
  343. foreach ($updatable as $property => $data) {
  344. if ($allowUserToChangeDisplayName === false
  345. && in_array($property, [IAccountManager::PROPERTY_DISPLAYNAME, IAccountManager::PROPERTY_EMAIL], true)) {
  346. continue;
  347. }
  348. $property = $userAccount->getProperty($property);
  349. if ($data['value'] !== null) {
  350. $property->setValue($data['value']);
  351. }
  352. if ($data['scope'] !== null) {
  353. $property->setScope($data['scope']);
  354. }
  355. }
  356. try {
  357. $this->saveUserSettings($userAccount);
  358. if ($oldPhoneValue !== $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue()) {
  359. $this->knownUserService->deleteByContactUserId($user->getUID());
  360. }
  361. return new DataResponse(
  362. [
  363. 'status' => 'success',
  364. 'data' => [
  365. 'userId' => $user->getUID(),
  366. 'avatarScope' => $userAccount->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope(),
  367. 'displayname' => $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue(),
  368. 'displaynameScope' => $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getScope(),
  369. 'phone' => $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue(),
  370. 'phoneScope' => $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getScope(),
  371. 'email' => $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue(),
  372. 'emailScope' => $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getScope(),
  373. 'website' => $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE)->getValue(),
  374. 'websiteScope' => $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE)->getScope(),
  375. 'address' => $userAccount->getProperty(IAccountManager::PROPERTY_ADDRESS)->getValue(),
  376. 'addressScope' => $userAccount->getProperty(IAccountManager::PROPERTY_ADDRESS)->getScope(),
  377. 'twitter' => $userAccount->getProperty(IAccountManager::PROPERTY_TWITTER)->getValue(),
  378. 'twitterScope' => $userAccount->getProperty(IAccountManager::PROPERTY_TWITTER)->getScope(),
  379. 'fediverse' => $userAccount->getProperty(IAccountManager::PROPERTY_FEDIVERSE)->getValue(),
  380. 'fediverseScope' => $userAccount->getProperty(IAccountManager::PROPERTY_FEDIVERSE)->getScope(),
  381. 'birthdate' => $userAccount->getProperty(IAccountManager::PROPERTY_BIRTHDATE)->getValue(),
  382. 'birthdateScope' => $userAccount->getProperty(IAccountManager::PROPERTY_BIRTHDATE)->getScope(),
  383. 'pronouns' => $userAccount->getProperty(IAccountManager::PROPERTY_PRONOUNS)->getValue(),
  384. 'pronounsScope' => $userAccount->getProperty(IAccountManager::PROPERTY_PRONOUNS)->getScope(),
  385. 'message' => $this->l10n->t('Settings saved'),
  386. ],
  387. ],
  388. Http::STATUS_OK
  389. );
  390. } catch (ForbiddenException|InvalidArgumentException|PropertyDoesNotExistException $e) {
  391. return new DataResponse([
  392. 'status' => 'error',
  393. 'data' => [
  394. 'message' => $e->getMessage()
  395. ],
  396. ]);
  397. }
  398. }
  399. /**
  400. * update account manager with new user data
  401. *
  402. * @throws ForbiddenException
  403. * @throws InvalidArgumentException
  404. */
  405. protected function saveUserSettings(IAccount $userAccount): void {
  406. // keep the user back-end up-to-date with the latest display name and email
  407. // address
  408. $oldDisplayName = $userAccount->getUser()->getDisplayName();
  409. if ($oldDisplayName !== $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue()) {
  410. $result = $userAccount->getUser()->setDisplayName($userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue());
  411. if ($result === false) {
  412. throw new ForbiddenException($this->l10n->t('Unable to change full name'));
  413. }
  414. }
  415. $oldEmailAddress = $userAccount->getUser()->getSystemEMailAddress();
  416. $oldEmailAddress = strtolower((string)$oldEmailAddress);
  417. if ($oldEmailAddress !== strtolower($userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue())) {
  418. // this is the only permission a backend provides and is also used
  419. // for the permission of setting a email address
  420. if (!$userAccount->getUser()->canChangeDisplayName()) {
  421. throw new ForbiddenException($this->l10n->t('Unable to change email address'));
  422. }
  423. $userAccount->getUser()->setSystemEMailAddress($userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue());
  424. }
  425. try {
  426. $this->accountManager->updateAccount($userAccount);
  427. } catch (InvalidArgumentException $e) {
  428. if ($e->getMessage() === IAccountManager::PROPERTY_PHONE) {
  429. throw new InvalidArgumentException($this->l10n->t('Unable to set invalid phone number'));
  430. }
  431. if ($e->getMessage() === IAccountManager::PROPERTY_WEBSITE) {
  432. throw new InvalidArgumentException($this->l10n->t('Unable to set invalid website'));
  433. }
  434. throw new InvalidArgumentException($this->l10n->t('Some account data was invalid'));
  435. }
  436. }
  437. /**
  438. * Set the mail address of a user
  439. *
  440. * @NoSubAdminRequired
  441. *
  442. * @param string $account
  443. * @param bool $onlyVerificationCode only return verification code without updating the data
  444. * @return DataResponse
  445. */
  446. #[NoAdminRequired]
  447. #[PasswordConfirmationRequired]
  448. public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse {
  449. $user = $this->userSession->getUser();
  450. if ($user === null) {
  451. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  452. }
  453. $userAccount = $this->accountManager->getAccount($user);
  454. $cloudId = $user->getCloudId();
  455. $message = 'Use my Federated Cloud ID to share with me: ' . $cloudId;
  456. $signature = $this->signMessage($user, $message);
  457. $code = $message . ' ' . $signature;
  458. $codeMd5 = $message . ' ' . md5($signature);
  459. switch ($account) {
  460. case 'verify-twitter':
  461. $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):');
  462. $code = $codeMd5;
  463. $type = IAccountManager::PROPERTY_TWITTER;
  464. break;
  465. case 'verify-website':
  466. $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):');
  467. $type = IAccountManager::PROPERTY_WEBSITE;
  468. break;
  469. default:
  470. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  471. }
  472. $userProperty = $userAccount->getProperty($type);
  473. $userProperty
  474. ->setVerified(IAccountManager::VERIFICATION_IN_PROGRESS)
  475. ->setVerificationData($signature);
  476. if ($onlyVerificationCode === false) {
  477. $this->accountManager->updateAccount($userAccount);
  478. $this->jobList->add(VerifyUserData::class,
  479. [
  480. 'verificationCode' => $code,
  481. 'data' => $userProperty->getValue(),
  482. 'type' => $type,
  483. 'uid' => $user->getUID(),
  484. 'try' => 0,
  485. 'lastRun' => $this->getCurrentTime()
  486. ]
  487. );
  488. }
  489. return new DataResponse(['msg' => $msg, 'code' => $code]);
  490. }
  491. /**
  492. * get current timestamp
  493. *
  494. * @return int
  495. */
  496. protected function getCurrentTime(): int {
  497. return time();
  498. }
  499. /**
  500. * sign message with users private key
  501. *
  502. * @param IUser $user
  503. * @param string $message
  504. *
  505. * @return string base64 encoded signature
  506. */
  507. protected function signMessage(IUser $user, string $message): string {
  508. $privateKey = $this->keyManager->getKey($user)->getPrivate();
  509. openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
  510. return base64_encode($signature);
  511. }
  512. }