ProvisioningApiMiddleware.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Provisioning_API\Middleware;
  8. use OCA\Provisioning_API\Middleware\Exceptions\NotSubAdminException;
  9. use OCP\AppFramework\Controller;
  10. use OCP\AppFramework\Http;
  11. use OCP\AppFramework\Http\Response;
  12. use OCP\AppFramework\Middleware;
  13. use OCP\AppFramework\OCS\OCSException;
  14. use OCP\AppFramework\Utility\IControllerMethodReflector;
  15. class ProvisioningApiMiddleware extends Middleware {
  16. /**
  17. * ProvisioningApiMiddleware constructor.
  18. *
  19. * @param IControllerMethodReflector $reflector
  20. * @param bool $isAdmin
  21. * @param bool $isSubAdmin
  22. */
  23. public function __construct(
  24. private IControllerMethodReflector $reflector,
  25. private bool $isAdmin,
  26. private bool $isSubAdmin,
  27. ) {
  28. }
  29. /**
  30. * @param Controller $controller
  31. * @param string $methodName
  32. *
  33. * @throws NotSubAdminException
  34. */
  35. public function beforeController($controller, $methodName) {
  36. // If AuthorizedAdminSetting, the check will be done in the SecurityMiddleware
  37. if (!$this->isAdmin && !$this->reflector->hasAnnotation('NoSubAdminRequired') && !$this->isSubAdmin && !$this->reflector->hasAnnotation('AuthorizedAdminSetting')) {
  38. throw new NotSubAdminException();
  39. }
  40. }
  41. /**
  42. * @param Controller $controller
  43. * @param string $methodName
  44. * @param \Exception $exception
  45. * @throws \Exception
  46. * @return Response
  47. */
  48. public function afterException($controller, $methodName, \Exception $exception) {
  49. if ($exception instanceof NotSubAdminException) {
  50. throw new OCSException($exception->getMessage(), Http::STATUS_FORBIDDEN);
  51. }
  52. throw $exception;
  53. }
  54. }