ProvisioningApiMiddleware.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. /** @var IControllerMethodReflector */
  17. private $reflector;
  18. /** @var bool */
  19. private $isAdmin;
  20. /** @var bool */
  21. private $isSubAdmin;
  22. /**
  23. * ProvisioningApiMiddleware constructor.
  24. *
  25. * @param IControllerMethodReflector $reflector
  26. * @param bool $isAdmin
  27. * @param bool $isSubAdmin
  28. */
  29. public function __construct(
  30. IControllerMethodReflector $reflector,
  31. bool $isAdmin,
  32. bool $isSubAdmin) {
  33. $this->reflector = $reflector;
  34. $this->isAdmin = $isAdmin;
  35. $this->isSubAdmin = $isSubAdmin;
  36. }
  37. /**
  38. * @param Controller $controller
  39. * @param string $methodName
  40. *
  41. * @throws NotSubAdminException
  42. */
  43. public function beforeController($controller, $methodName) {
  44. // If AuthorizedAdminSetting, the check will be done in the SecurityMiddleware
  45. if (!$this->isAdmin && !$this->reflector->hasAnnotation('NoSubAdminRequired') && !$this->isSubAdmin && !$this->reflector->hasAnnotation('AuthorizedAdminSetting')) {
  46. throw new NotSubAdminException();
  47. }
  48. }
  49. /**
  50. * @param Controller $controller
  51. * @param string $methodName
  52. * @param \Exception $exception
  53. * @throws \Exception
  54. * @return Response
  55. */
  56. public function afterException($controller, $methodName, \Exception $exception) {
  57. if ($exception instanceof NotSubAdminException) {
  58. throw new OCSException($exception->getMessage(), Http::STATUS_FORBIDDEN);
  59. }
  60. throw $exception;
  61. }
  62. }