BearerAuth.php 1.6 KB

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