UsersController.php 19 KB

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