UsersController.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 names to retrieve the countDisabledUsersOfGroups
  134. $userGroups = $this->groupManager->getUserGroups($user);
  135. $groupsNames = [];
  136. foreach ($groups as $key => $group) {
  137. // $userCount += (int)$group['usercount'];
  138. $groupsNames[] = $group['name'];
  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($groupsNames);
  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. ) {
  302. $user = $this->userSession->getUser();
  303. if (!$user instanceof IUser) {
  304. return new DataResponse(
  305. [
  306. 'status' => 'error',
  307. 'data' => [
  308. 'message' => $this->l10n->t('Invalid account')
  309. ]
  310. ],
  311. Http::STATUS_UNAUTHORIZED
  312. );
  313. }
  314. $email = !is_null($email) ? strtolower($email) : $email;
  315. if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
  316. return new DataResponse(
  317. [
  318. 'status' => 'error',
  319. 'data' => [
  320. 'message' => $this->l10n->t('Invalid mail address')
  321. ]
  322. ],
  323. Http::STATUS_UNPROCESSABLE_ENTITY
  324. );
  325. }
  326. $userAccount = $this->accountManager->getAccount($user);
  327. $oldPhoneValue = $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue();
  328. $updatable = [
  329. IAccountManager::PROPERTY_AVATAR => ['value' => null, 'scope' => $avatarScope],
  330. IAccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
  331. IAccountManager::PROPERTY_EMAIL => ['value' => $email, 'scope' => $emailScope],
  332. IAccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
  333. IAccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
  334. IAccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
  335. IAccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope],
  336. IAccountManager::PROPERTY_FEDIVERSE => ['value' => $fediverse, 'scope' => $fediverseScope],
  337. IAccountManager::PROPERTY_BIRTHDATE => ['value' => $birthdate, 'scope' => $birthdateScope],
  338. ];
  339. $allowUserToChangeDisplayName = $this->config->getSystemValueBool('allow_user_to_change_display_name', true);
  340. foreach ($updatable as $property => $data) {
  341. if ($allowUserToChangeDisplayName === false
  342. && in_array($property, [IAccountManager::PROPERTY_DISPLAYNAME, IAccountManager::PROPERTY_EMAIL], true)) {
  343. continue;
  344. }
  345. $property = $userAccount->getProperty($property);
  346. if ($data['value'] !== null) {
  347. $property->setValue($data['value']);
  348. }
  349. if ($data['scope'] !== null) {
  350. $property->setScope($data['scope']);
  351. }
  352. }
  353. try {
  354. $this->saveUserSettings($userAccount);
  355. if ($oldPhoneValue !== $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue()) {
  356. $this->knownUserService->deleteByContactUserId($user->getUID());
  357. }
  358. return new DataResponse(
  359. [
  360. 'status' => 'success',
  361. 'data' => [
  362. 'userId' => $user->getUID(),
  363. 'avatarScope' => $userAccount->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope(),
  364. 'displayname' => $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue(),
  365. 'displaynameScope' => $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getScope(),
  366. 'phone' => $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue(),
  367. 'phoneScope' => $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getScope(),
  368. 'email' => $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue(),
  369. 'emailScope' => $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getScope(),
  370. 'website' => $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE)->getValue(),
  371. 'websiteScope' => $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE)->getScope(),
  372. 'address' => $userAccount->getProperty(IAccountManager::PROPERTY_ADDRESS)->getValue(),
  373. 'addressScope' => $userAccount->getProperty(IAccountManager::PROPERTY_ADDRESS)->getScope(),
  374. 'twitter' => $userAccount->getProperty(IAccountManager::PROPERTY_TWITTER)->getValue(),
  375. 'twitterScope' => $userAccount->getProperty(IAccountManager::PROPERTY_TWITTER)->getScope(),
  376. 'fediverse' => $userAccount->getProperty(IAccountManager::PROPERTY_FEDIVERSE)->getValue(),
  377. 'fediverseScope' => $userAccount->getProperty(IAccountManager::PROPERTY_FEDIVERSE)->getScope(),
  378. 'birthdate' => $userAccount->getProperty(IAccountManager::PROPERTY_BIRTHDATE)->getValue(),
  379. 'birthdateScope' => $userAccount->getProperty(IAccountManager::PROPERTY_BIRTHDATE)->getScope(),
  380. 'message' => $this->l10n->t('Settings saved'),
  381. ],
  382. ],
  383. Http::STATUS_OK
  384. );
  385. } catch (ForbiddenException | InvalidArgumentException | PropertyDoesNotExistException $e) {
  386. return new DataResponse([
  387. 'status' => 'error',
  388. 'data' => [
  389. 'message' => $e->getMessage()
  390. ],
  391. ]);
  392. }
  393. }
  394. /**
  395. * update account manager with new user data
  396. *
  397. * @throws ForbiddenException
  398. * @throws InvalidArgumentException
  399. */
  400. protected function saveUserSettings(IAccount $userAccount): void {
  401. // keep the user back-end up-to-date with the latest display name and email
  402. // address
  403. $oldDisplayName = $userAccount->getUser()->getDisplayName();
  404. if ($oldDisplayName !== $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue()) {
  405. $result = $userAccount->getUser()->setDisplayName($userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue());
  406. if ($result === false) {
  407. throw new ForbiddenException($this->l10n->t('Unable to change full name'));
  408. }
  409. }
  410. $oldEmailAddress = $userAccount->getUser()->getSystemEMailAddress();
  411. $oldEmailAddress = strtolower((string)$oldEmailAddress);
  412. if ($oldEmailAddress !== strtolower($userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue())) {
  413. // this is the only permission a backend provides and is also used
  414. // for the permission of setting a email address
  415. if (!$userAccount->getUser()->canChangeDisplayName()) {
  416. throw new ForbiddenException($this->l10n->t('Unable to change email address'));
  417. }
  418. $userAccount->getUser()->setSystemEMailAddress($userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue());
  419. }
  420. try {
  421. $this->accountManager->updateAccount($userAccount);
  422. } catch (InvalidArgumentException $e) {
  423. if ($e->getMessage() === IAccountManager::PROPERTY_PHONE) {
  424. throw new InvalidArgumentException($this->l10n->t('Unable to set invalid phone number'));
  425. }
  426. if ($e->getMessage() === IAccountManager::PROPERTY_WEBSITE) {
  427. throw new InvalidArgumentException($this->l10n->t('Unable to set invalid website'));
  428. }
  429. throw new InvalidArgumentException($this->l10n->t('Some account data was invalid'));
  430. }
  431. }
  432. /**
  433. * Set the mail address of a user
  434. *
  435. * @NoSubAdminRequired
  436. *
  437. * @param string $account
  438. * @param bool $onlyVerificationCode only return verification code without updating the data
  439. * @return DataResponse
  440. */
  441. #[NoAdminRequired]
  442. #[PasswordConfirmationRequired]
  443. public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse {
  444. $user = $this->userSession->getUser();
  445. if ($user === null) {
  446. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  447. }
  448. $userAccount = $this->accountManager->getAccount($user);
  449. $cloudId = $user->getCloudId();
  450. $message = 'Use my Federated Cloud ID to share with me: ' . $cloudId;
  451. $signature = $this->signMessage($user, $message);
  452. $code = $message . ' ' . $signature;
  453. $codeMd5 = $message . ' ' . md5($signature);
  454. switch ($account) {
  455. case 'verify-twitter':
  456. $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):');
  457. $code = $codeMd5;
  458. $type = IAccountManager::PROPERTY_TWITTER;
  459. break;
  460. case 'verify-website':
  461. $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):');
  462. $type = IAccountManager::PROPERTY_WEBSITE;
  463. break;
  464. default:
  465. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  466. }
  467. $userProperty = $userAccount->getProperty($type);
  468. $userProperty
  469. ->setVerified(IAccountManager::VERIFICATION_IN_PROGRESS)
  470. ->setVerificationData($signature);
  471. if ($onlyVerificationCode === false) {
  472. $this->accountManager->updateAccount($userAccount);
  473. $this->jobList->add(VerifyUserData::class,
  474. [
  475. 'verificationCode' => $code,
  476. 'data' => $userProperty->getValue(),
  477. 'type' => $type,
  478. 'uid' => $user->getUID(),
  479. 'try' => 0,
  480. 'lastRun' => $this->getCurrentTime()
  481. ]
  482. );
  483. }
  484. return new DataResponse(['msg' => $msg, 'code' => $code]);
  485. }
  486. /**
  487. * get current timestamp
  488. *
  489. * @return int
  490. */
  491. protected function getCurrentTime(): int {
  492. return time();
  493. }
  494. /**
  495. * sign message with users private key
  496. *
  497. * @param IUser $user
  498. * @param string $message
  499. *
  500. * @return string base64 encoded signature
  501. */
  502. protected function signMessage(IUser $user, string $message): string {
  503. $privateKey = $this->keyManager->getKey($user)->getPrivate();
  504. openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
  505. return base64_encode($signature);
  506. }
  507. }