SubadminMiddleware.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors/**
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Settings\Middleware;
  8. use OC\AppFramework\Http;
  9. use OC\AppFramework\Middleware\Security\Exceptions\NotAdminException;
  10. use OC\AppFramework\Utility\ControllerMethodReflector;
  11. use OCP\AppFramework\Controller;
  12. use OCP\AppFramework\Http\TemplateResponse;
  13. use OCP\AppFramework\Middleware;
  14. use OCP\IL10N;
  15. /**
  16. * Verifies whether an user has at least subadmin rights.
  17. * To bypass use the `@NoSubAdminRequired` annotation
  18. */
  19. class SubadminMiddleware extends Middleware {
  20. /** @var ControllerMethodReflector */
  21. protected $reflector;
  22. /**
  23. * @param ControllerMethodReflector $reflector
  24. * @param bool $isSubAdmin
  25. * @param IL10N $l10n
  26. */
  27. public function __construct(
  28. ControllerMethodReflector $reflector,
  29. protected $isSubAdmin,
  30. private IL10N $l10n,
  31. ) {
  32. $this->reflector = $reflector;
  33. }
  34. /**
  35. * Check if sharing is enabled before the controllers is executed
  36. * @param Controller $controller
  37. * @param string $methodName
  38. * @throws \Exception
  39. */
  40. public function beforeController($controller, $methodName) {
  41. if (!$this->reflector->hasAnnotation('NoSubAdminRequired') && !$this->reflector->hasAnnotation('AuthorizedAdminSetting')) {
  42. if (!$this->isSubAdmin) {
  43. throw new NotAdminException($this->l10n->t('Logged in account must be a subadmin'));
  44. }
  45. }
  46. }
  47. /**
  48. * Return 403 page in case of an exception
  49. * @param Controller $controller
  50. * @param string $methodName
  51. * @param \Exception $exception
  52. * @return TemplateResponse
  53. * @throws \Exception
  54. */
  55. public function afterException($controller, $methodName, \Exception $exception) {
  56. if ($exception instanceof NotAdminException) {
  57. $response = new TemplateResponse('core', '403', [], 'guest');
  58. $response->setStatus(Http::STATUS_FORBIDDEN);
  59. return $response;
  60. }
  61. throw $exception;
  62. }
  63. }