UsersController.php 19 KB

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