SubadminMiddleware.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 bool */
  21. protected $isSubAdmin;
  22. /** @var ControllerMethodReflector */
  23. protected $reflector;
  24. /** @var IL10N */
  25. private $l10n;
  26. /**
  27. * @param ControllerMethodReflector $reflector
  28. * @param bool $isSubAdmin
  29. * @param IL10N $l10n
  30. */
  31. public function __construct(ControllerMethodReflector $reflector,
  32. $isSubAdmin,
  33. IL10N $l10n) {
  34. $this->reflector = $reflector;
  35. $this->isSubAdmin = $isSubAdmin;
  36. $this->l10n = $l10n;
  37. }
  38. /**
  39. * Check if sharing is enabled before the controllers is executed
  40. * @param Controller $controller
  41. * @param string $methodName
  42. * @throws \Exception
  43. */
  44. public function beforeController($controller, $methodName) {
  45. if (!$this->reflector->hasAnnotation('NoSubAdminRequired') && !$this->reflector->hasAnnotation('AuthorizedAdminSetting')) {
  46. if (!$this->isSubAdmin) {
  47. throw new NotAdminException($this->l10n->t('Logged in account must be a subadmin'));
  48. }
  49. }
  50. }
  51. /**
  52. * Return 403 page in case of an exception
  53. * @param Controller $controller
  54. * @param string $methodName
  55. * @param \Exception $exception
  56. * @return TemplateResponse
  57. * @throws \Exception
  58. */
  59. public function afterException($controller, $methodName, \Exception $exception) {
  60. if ($exception instanceof NotAdminException) {
  61. $response = new TemplateResponse('core', '403', [], 'guest');
  62. $response->setStatus(Http::STATUS_FORBIDDEN);
  63. return $response;
  64. }
  65. throw $exception;
  66. }
  67. }