1
0

BearerAuth.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\DAV\Connector\Sabre;
  7. use OCP\IRequest;
  8. use OCP\ISession;
  9. use OCP\IUserSession;
  10. use Sabre\DAV\Auth\Backend\AbstractBearer;
  11. use Sabre\HTTP\RequestInterface;
  12. use Sabre\HTTP\ResponseInterface;
  13. class BearerAuth extends AbstractBearer {
  14. private IUserSession $userSession;
  15. private ISession $session;
  16. private IRequest $request;
  17. private string $principalPrefix;
  18. public function __construct(IUserSession $userSession,
  19. ISession $session,
  20. IRequest $request,
  21. $principalPrefix = 'principals/users/') {
  22. $this->userSession = $userSession;
  23. $this->session = $session;
  24. $this->request = $request;
  25. $this->principalPrefix = $principalPrefix;
  26. // setup realm
  27. $defaults = new \OCP\Defaults();
  28. $this->realm = $defaults->getName() ?: 'Nextcloud';
  29. }
  30. private function setupUserFs($userId) {
  31. \OC_Util::setupFS($userId);
  32. $this->session->close();
  33. return $this->principalPrefix . $userId;
  34. }
  35. /**
  36. * {@inheritdoc}
  37. */
  38. public function validateBearerToken($bearerToken) {
  39. \OC_Util::setupFS();
  40. if (!$this->userSession->isLoggedIn()) {
  41. $this->userSession->tryTokenLogin($this->request);
  42. }
  43. if ($this->userSession->isLoggedIn()) {
  44. return $this->setupUserFs($this->userSession->getUser()->getUID());
  45. }
  46. return false;
  47. }
  48. /**
  49. * \Sabre\DAV\Auth\Backend\AbstractBearer::challenge sets an WWW-Authenticate
  50. * header which some DAV clients can't handle. Thus we override this function
  51. * and make it simply return a 401.
  52. *
  53. * @param RequestInterface $request
  54. * @param ResponseInterface $response
  55. */
  56. public function challenge(RequestInterface $request, ResponseInterface $response): void {
  57. $response->setStatus(401);
  58. }
  59. }