ProvisioningApiMiddleware.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace OCA\Provisioning_API\Middleware;
  3. use OCA\Provisioning_API\Middleware\Exceptions\NotSubAdminException;
  4. use OCP\AppFramework\Http\Response;
  5. use OCP\AppFramework\Middleware;
  6. use OCP\AppFramework\OCS\OCSException;
  7. use OCP\AppFramework\Utility\IControllerMethodReflector;
  8. class ProvisioningApiMiddleware extends Middleware {
  9. /** @var IControllerMethodReflector */
  10. private $reflector;
  11. /** @var bool */
  12. private $isAdmin;
  13. /** @var bool */
  14. private $isSubAdmin;
  15. /**
  16. * ProvisioningApiMiddleware constructor.
  17. *
  18. * @param IControllerMethodReflector $reflector
  19. * @param bool $isAdmin
  20. * @param bool $isSubAdmin
  21. */
  22. public function __construct(
  23. IControllerMethodReflector $reflector,
  24. $isAdmin,
  25. $isSubAdmin) {
  26. $this->reflector = $reflector;
  27. $this->isAdmin = $isAdmin;
  28. $this->isSubAdmin = $isSubAdmin;
  29. }
  30. /**
  31. * @param \OCP\AppFramework\Controller $controller
  32. * @param string $methodName
  33. *
  34. * @throws NotSubAdminException
  35. */
  36. public function beforeController($controller, $methodName) {
  37. if (!$this->isAdmin && !$this->reflector->hasAnnotation('NoSubAdminRequired') && !$this->isSubAdmin) {
  38. throw new NotSubAdminException();
  39. }
  40. }
  41. /**
  42. * @param \OCP\AppFramework\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(), \OCP\API::RESPOND_UNAUTHORISED);
  51. }
  52. throw $exception;
  53. }
  54. }