UserContext.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\Files_External\Config;
  7. use OCP\IRequest;
  8. use OCP\IUser;
  9. use OCP\IUserManager;
  10. use OCP\IUserSession;
  11. use OCP\Share\Exceptions\ShareNotFound;
  12. use OCP\Share\IManager as ShareManager;
  13. class UserContext {
  14. /** @var IUserSession */
  15. private $session;
  16. /** @var ShareManager */
  17. private $shareManager;
  18. /** @var IRequest */
  19. private $request;
  20. /** @var string */
  21. private $userId;
  22. /** @var IUserManager */
  23. private $userManager;
  24. public function __construct(IUserSession $session, ShareManager $manager, IRequest $request, IUserManager $userManager) {
  25. $this->session = $session;
  26. $this->shareManager = $manager;
  27. $this->request = $request;
  28. $this->userManager = $userManager;
  29. }
  30. public function getSession(): IUserSession {
  31. return $this->session;
  32. }
  33. public function setUserId(string $userId): void {
  34. $this->userId = $userId;
  35. }
  36. protected function getUserId(): ?string {
  37. if ($this->userId !== null) {
  38. return $this->userId;
  39. }
  40. if ($this->session && $this->session->getUser() !== null) {
  41. return $this->session->getUser()->getUID();
  42. }
  43. try {
  44. $shareToken = $this->request->getParam('token');
  45. $share = $this->shareManager->getShareByToken($shareToken);
  46. return $share->getShareOwner();
  47. } catch (ShareNotFound $e) {
  48. }
  49. return null;
  50. }
  51. protected function getUser(): ?IUser {
  52. $userId = $this->getUserId();
  53. if ($userId !== null) {
  54. return $this->userManager->get($userId);
  55. }
  56. return null;
  57. }
  58. }