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->getSystemValue('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 names to retrieve the countDisabledUsersOfGroups
  155. $userGroups = $this->groupManager->getUserGroups($user);
  156. $groupsNames = [];
  157. foreach ($groups as $key => $group) {
  158. // $userCount += (int)$group['usercount'];
  159. $groupsNames[] = $group['name'];
  160. // we prevent subadmins from looking up themselves
  161. // so we lower the count of the groups he belongs to
  162. if (array_key_exists($group['id'], $userGroups)) {
  163. $groups[$key]['usercount']--;
  164. $userCount -= 1; // we also lower from one the total count
  165. }
  166. }
  167. $userCount += $this->userManager->countUsersOfGroups($groupsInfo->getGroups());
  168. $disabledUsers = $this->userManager->countDisabledUsersOfGroups($groupsNames);
  169. }
  170. $userCount -= $disabledUsers;
  171. }
  172. $disabledUsersGroup = [
  173. 'id' => 'disabled',
  174. 'name' => 'Disabled accounts',
  175. 'usercount' => $disabledUsers
  176. ];
  177. /* QUOTAS PRESETS */
  178. $quotaPreset = $this->parseQuotaPreset($this->config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB'));
  179. $allowUnlimitedQuota = $this->config->getAppValue('files', 'allow_unlimited_quota', '1') === '1';
  180. if (!$allowUnlimitedQuota && count($quotaPreset) > 0) {
  181. $defaultQuota = $this->config->getAppValue('files', 'default_quota', $quotaPreset[0]);
  182. } else {
  183. $defaultQuota = $this->config->getAppValue('files', 'default_quota', 'none');
  184. }
  185. $event = new BeforeTemplateRenderedEvent();
  186. $this->dispatcher->dispatch('OC\Settings\Users::loadAdditionalScripts', $event);
  187. $this->dispatcher->dispatchTyped($event);
  188. /* LANGUAGES */
  189. $languages = $this->l10nFactory->getLanguages();
  190. /* FINAL DATA */
  191. $serverData = [];
  192. // groups
  193. $serverData['groups'] = array_merge_recursive($adminGroup, [$disabledUsersGroup], $groups);
  194. // Various data
  195. $serverData['isAdmin'] = $isAdmin;
  196. $serverData['sortGroups'] = $sortGroupsBy;
  197. $serverData['quotaPreset'] = $quotaPreset;
  198. $serverData['allowUnlimitedQuota'] = $allowUnlimitedQuota;
  199. $serverData['userCount'] = $userCount;
  200. $serverData['languages'] = $languages;
  201. $serverData['defaultLanguage'] = $this->config->getSystemValue('default_language', 'en');
  202. $serverData['forceLanguage'] = $this->config->getSystemValue('force_language', false);
  203. // Settings
  204. $serverData['defaultQuota'] = $defaultQuota;
  205. $serverData['canChangePassword'] = $canChangePassword;
  206. $serverData['newUserGenerateUserID'] = $this->config->getAppValue('core', 'newUser.generateUserID', 'no') === 'yes';
  207. $serverData['newUserRequireEmail'] = $this->config->getAppValue('core', 'newUser.requireEmail', 'no') === 'yes';
  208. $serverData['newUserSendEmail'] = $this->config->getAppValue('core', 'newUser.sendEmail', 'yes') === 'yes';
  209. $this->initialState->provideInitialState('usersSettings', $serverData);
  210. \OCP\Util::addStyle('settings', 'settings');
  211. \OCP\Util::addScript('settings', 'vue-settings-apps-users-management');
  212. return new TemplateResponse('settings', 'settings/empty', ['pageTitle' => $this->l10n->t('Settings')]);
  213. }
  214. /**
  215. * @param string $key
  216. * @param string $value
  217. *
  218. * @return JSONResponse
  219. */
  220. public function setPreference(string $key, string $value): JSONResponse {
  221. $allowed = ['newUser.sendEmail'];
  222. if (!in_array($key, $allowed, true)) {
  223. return new JSONResponse([], Http::STATUS_FORBIDDEN);
  224. }
  225. $this->config->setAppValue('core', $key, $value);
  226. return new JSONResponse([]);
  227. }
  228. /**
  229. * Parse the app value for quota_present
  230. *
  231. * @param string $quotaPreset
  232. * @return array
  233. */
  234. protected function parseQuotaPreset(string $quotaPreset): array {
  235. // 1 GB, 5 GB, 10 GB => [1 GB, 5 GB, 10 GB]
  236. $presets = array_filter(array_map('trim', explode(',', $quotaPreset)));
  237. // Drop default and none, Make array indexes numerically
  238. return array_values(array_diff($presets, ['default', 'none']));
  239. }
  240. /**
  241. * check if the admin can change the users password
  242. *
  243. * The admin can change the passwords if:
  244. *
  245. * - no encryption module is loaded and encryption is disabled
  246. * - encryption module is loaded but it doesn't require per user keys
  247. *
  248. * The admin can not change the passwords if:
  249. *
  250. * - an encryption module is loaded and it uses per-user keys
  251. * - encryption is enabled but no encryption modules are loaded
  252. *
  253. * @return bool
  254. */
  255. protected function canAdminChangeUserPasswords(): bool {
  256. $isEncryptionEnabled = $this->encryptionManager->isEnabled();
  257. try {
  258. $noUserSpecificEncryptionKeys = !$this->encryptionManager->getEncryptionModule()->needDetailedAccessList();
  259. $isEncryptionModuleLoaded = true;
  260. } catch (ModuleDoesNotExistsException $e) {
  261. $noUserSpecificEncryptionKeys = true;
  262. $isEncryptionModuleLoaded = false;
  263. }
  264. $canChangePassword = ($isEncryptionModuleLoaded && $noUserSpecificEncryptionKeys)
  265. || (!$isEncryptionModuleLoaded && !$isEncryptionEnabled);
  266. return $canChangePassword;
  267. }
  268. /**
  269. * @NoAdminRequired
  270. * @NoSubAdminRequired
  271. * @PasswordConfirmationRequired
  272. *
  273. * @param string|null $avatarScope
  274. * @param string|null $displayname
  275. * @param string|null $displaynameScope
  276. * @param string|null $phone
  277. * @param string|null $phoneScope
  278. * @param string|null $email
  279. * @param string|null $emailScope
  280. * @param string|null $website
  281. * @param string|null $websiteScope
  282. * @param string|null $address
  283. * @param string|null $addressScope
  284. * @param string|null $twitter
  285. * @param string|null $twitterScope
  286. * @param string|null $fediverse
  287. * @param string|null $fediverseScope
  288. *
  289. * @return DataResponse
  290. */
  291. public function setUserSettings(?string $avatarScope = null,
  292. ?string $displayname = null,
  293. ?string $displaynameScope = null,
  294. ?string $phone = null,
  295. ?string $phoneScope = null,
  296. ?string $email = null,
  297. ?string $emailScope = null,
  298. ?string $website = null,
  299. ?string $websiteScope = null,
  300. ?string $address = null,
  301. ?string $addressScope = null,
  302. ?string $twitter = null,
  303. ?string $twitterScope = null,
  304. ?string $fediverse = null,
  305. ?string $fediverseScope = null
  306. ) {
  307. $user = $this->userSession->getUser();
  308. if (!$user instanceof IUser) {
  309. return new DataResponse(
  310. [
  311. 'status' => 'error',
  312. 'data' => [
  313. 'message' => $this->l10n->t('Invalid account')
  314. ]
  315. ],
  316. Http::STATUS_UNAUTHORIZED
  317. );
  318. }
  319. $email = !is_null($email) ? strtolower($email) : $email;
  320. if (!empty($email) && !$this->mailer->validateMailAddress($email)) {
  321. return new DataResponse(
  322. [
  323. 'status' => 'error',
  324. 'data' => [
  325. 'message' => $this->l10n->t('Invalid mail address')
  326. ]
  327. ],
  328. Http::STATUS_UNPROCESSABLE_ENTITY
  329. );
  330. }
  331. $userAccount = $this->accountManager->getAccount($user);
  332. $oldPhoneValue = $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue();
  333. $updatable = [
  334. IAccountManager::PROPERTY_AVATAR => ['value' => null, 'scope' => $avatarScope],
  335. IAccountManager::PROPERTY_DISPLAYNAME => ['value' => $displayname, 'scope' => $displaynameScope],
  336. IAccountManager::PROPERTY_EMAIL => ['value' => $email, 'scope' => $emailScope],
  337. IAccountManager::PROPERTY_WEBSITE => ['value' => $website, 'scope' => $websiteScope],
  338. IAccountManager::PROPERTY_ADDRESS => ['value' => $address, 'scope' => $addressScope],
  339. IAccountManager::PROPERTY_PHONE => ['value' => $phone, 'scope' => $phoneScope],
  340. IAccountManager::PROPERTY_TWITTER => ['value' => $twitter, 'scope' => $twitterScope],
  341. IAccountManager::PROPERTY_FEDIVERSE => ['value' => $fediverse, 'scope' => $fediverseScope],
  342. ];
  343. $allowUserToChangeDisplayName = $this->config->getSystemValueBool('allow_user_to_change_display_name', true);
  344. foreach ($updatable as $property => $data) {
  345. if ($allowUserToChangeDisplayName === false
  346. && in_array($property, [IAccountManager::PROPERTY_DISPLAYNAME, IAccountManager::PROPERTY_EMAIL], true)) {
  347. continue;
  348. }
  349. $property = $userAccount->getProperty($property);
  350. if (null !== $data['value']) {
  351. $property->setValue($data['value']);
  352. }
  353. if (null !== $data['scope']) {
  354. $property->setScope($data['scope']);
  355. }
  356. }
  357. try {
  358. $this->saveUserSettings($userAccount);
  359. if ($oldPhoneValue !== $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue()) {
  360. $this->knownUserService->deleteByContactUserId($user->getUID());
  361. }
  362. return new DataResponse(
  363. [
  364. 'status' => 'success',
  365. 'data' => [
  366. 'userId' => $user->getUID(),
  367. 'avatarScope' => $userAccount->getProperty(IAccountManager::PROPERTY_AVATAR)->getScope(),
  368. 'displayname' => $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue(),
  369. 'displaynameScope' => $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getScope(),
  370. 'phone' => $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getValue(),
  371. 'phoneScope' => $userAccount->getProperty(IAccountManager::PROPERTY_PHONE)->getScope(),
  372. 'email' => $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue(),
  373. 'emailScope' => $userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getScope(),
  374. 'website' => $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE)->getValue(),
  375. 'websiteScope' => $userAccount->getProperty(IAccountManager::PROPERTY_WEBSITE)->getScope(),
  376. 'address' => $userAccount->getProperty(IAccountManager::PROPERTY_ADDRESS)->getValue(),
  377. 'addressScope' => $userAccount->getProperty(IAccountManager::PROPERTY_ADDRESS)->getScope(),
  378. 'twitter' => $userAccount->getProperty(IAccountManager::PROPERTY_TWITTER)->getValue(),
  379. 'twitterScope' => $userAccount->getProperty(IAccountManager::PROPERTY_TWITTER)->getScope(),
  380. 'fediverse' => $userAccount->getProperty(IAccountManager::PROPERTY_FEDIVERSE)->getValue(),
  381. 'fediverseScope' => $userAccount->getProperty(IAccountManager::PROPERTY_FEDIVERSE)->getScope(),
  382. 'message' => $this->l10n->t('Settings saved'),
  383. ],
  384. ],
  385. Http::STATUS_OK
  386. );
  387. } catch (ForbiddenException | InvalidArgumentException | PropertyDoesNotExistException $e) {
  388. return new DataResponse([
  389. 'status' => 'error',
  390. 'data' => [
  391. 'message' => $e->getMessage()
  392. ],
  393. ]);
  394. }
  395. }
  396. /**
  397. * update account manager with new user data
  398. *
  399. * @throws ForbiddenException
  400. * @throws InvalidArgumentException
  401. */
  402. protected function saveUserSettings(IAccount $userAccount): void {
  403. // keep the user back-end up-to-date with the latest display name and email
  404. // address
  405. $oldDisplayName = $userAccount->getUser()->getDisplayName();
  406. if ($oldDisplayName !== $userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue()) {
  407. $result = $userAccount->getUser()->setDisplayName($userAccount->getProperty(IAccountManager::PROPERTY_DISPLAYNAME)->getValue());
  408. if ($result === false) {
  409. throw new ForbiddenException($this->l10n->t('Unable to change full name'));
  410. }
  411. }
  412. $oldEmailAddress = $userAccount->getUser()->getSystemEMailAddress();
  413. $oldEmailAddress = strtolower((string)$oldEmailAddress);
  414. if ($oldEmailAddress !== strtolower($userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue())) {
  415. // this is the only permission a backend provides and is also used
  416. // for the permission of setting a email address
  417. if (!$userAccount->getUser()->canChangeDisplayName()) {
  418. throw new ForbiddenException($this->l10n->t('Unable to change email address'));
  419. }
  420. $userAccount->getUser()->setSystemEMailAddress($userAccount->getProperty(IAccountManager::PROPERTY_EMAIL)->getValue());
  421. }
  422. try {
  423. $this->accountManager->updateAccount($userAccount);
  424. } catch (InvalidArgumentException $e) {
  425. if ($e->getMessage() === IAccountManager::PROPERTY_PHONE) {
  426. throw new InvalidArgumentException($this->l10n->t('Unable to set invalid phone number'));
  427. }
  428. if ($e->getMessage() === IAccountManager::PROPERTY_WEBSITE) {
  429. throw new InvalidArgumentException($this->l10n->t('Unable to set invalid website'));
  430. }
  431. throw new InvalidArgumentException($this->l10n->t('Some account data was invalid'));
  432. }
  433. }
  434. /**
  435. * Set the mail address of a user
  436. *
  437. * @NoAdminRequired
  438. * @NoSubAdminRequired
  439. * @PasswordConfirmationRequired
  440. *
  441. * @param string $account
  442. * @param bool $onlyVerificationCode only return verification code without updating the data
  443. * @return DataResponse
  444. */
  445. public function getVerificationCode(string $account, bool $onlyVerificationCode): DataResponse {
  446. $user = $this->userSession->getUser();
  447. if ($user === null) {
  448. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  449. }
  450. $userAccount = $this->accountManager->getAccount($user);
  451. $cloudId = $user->getCloudId();
  452. $message = 'Use my Federated Cloud ID to share with me: ' . $cloudId;
  453. $signature = $this->signMessage($user, $message);
  454. $code = $message . ' ' . $signature;
  455. $codeMd5 = $message . ' ' . md5($signature);
  456. switch ($account) {
  457. case 'verify-twitter':
  458. $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):');
  459. $code = $codeMd5;
  460. $type = IAccountManager::PROPERTY_TWITTER;
  461. break;
  462. case 'verify-website':
  463. $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):');
  464. $type = IAccountManager::PROPERTY_WEBSITE;
  465. break;
  466. default:
  467. return new DataResponse([], Http::STATUS_BAD_REQUEST);
  468. }
  469. $userProperty = $userAccount->getProperty($type);
  470. $userProperty
  471. ->setVerified(IAccountManager::VERIFICATION_IN_PROGRESS)
  472. ->setVerificationData($signature);
  473. if ($onlyVerificationCode === false) {
  474. $this->accountManager->updateAccount($userAccount);
  475. $this->jobList->add(VerifyUserData::class,
  476. [
  477. 'verificationCode' => $code,
  478. 'data' => $userProperty->getValue(),
  479. 'type' => $type,
  480. 'uid' => $user->getUID(),
  481. 'try' => 0,
  482. 'lastRun' => $this->getCurrentTime()
  483. ]
  484. );
  485. }
  486. return new DataResponse(['msg' => $msg, 'code' => $code]);
  487. }
  488. /**
  489. * get current timestamp
  490. *
  491. * @return int
  492. */
  493. protected function getCurrentTime(): int {
  494. return time();
  495. }
  496. /**
  497. * sign message with users private key
  498. *
  499. * @param IUser $user
  500. * @param string $message
  501. *
  502. * @return string base64 encoded signature
  503. */
  504. protected function signMessage(IUser $user, string $message): string {
  505. $privateKey = $this->keyManager->getKey($user)->getPrivate();
  506. openssl_sign(json_encode($message), $signature, $privateKey, OPENSSL_ALGO_SHA512);
  507. return base64_encode($signature);
  508. }
  509. }