BearerAuth.php 1.6 KB

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