SessionMiddleware.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  6. * SPDX-License-Identifier: AGPL-3.0-only
  7. */
  8. namespace OC\AppFramework\Middleware;
  9. use OC\AppFramework\Utility\ControllerMethodReflector;
  10. use OCP\AppFramework\Controller;
  11. use OCP\AppFramework\Http\Attribute\UseSession;
  12. use OCP\AppFramework\Http\Response;
  13. use OCP\AppFramework\Middleware;
  14. use OCP\ISession;
  15. use ReflectionMethod;
  16. class SessionMiddleware extends Middleware {
  17. /** @var ControllerMethodReflector */
  18. private $reflector;
  19. /** @var ISession */
  20. private $session;
  21. public function __construct(ControllerMethodReflector $reflector,
  22. ISession $session) {
  23. $this->reflector = $reflector;
  24. $this->session = $session;
  25. }
  26. /**
  27. * @param Controller $controller
  28. * @param string $methodName
  29. */
  30. public function beforeController($controller, $methodName) {
  31. /**
  32. * Annotation deprecated with Nextcloud 26
  33. */
  34. $hasAnnotation = $this->reflector->hasAnnotation('UseSession');
  35. if ($hasAnnotation) {
  36. $this->session->reopen();
  37. return;
  38. }
  39. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  40. $hasAttribute = !empty($reflectionMethod->getAttributes(UseSession::class));
  41. if ($hasAttribute) {
  42. $this->session->reopen();
  43. }
  44. }
  45. /**
  46. * @param Controller $controller
  47. * @param string $methodName
  48. * @param Response $response
  49. * @return Response
  50. */
  51. public function afterController($controller, $methodName, Response $response) {
  52. /**
  53. * Annotation deprecated with Nextcloud 26
  54. */
  55. $hasAnnotation = $this->reflector->hasAnnotation('UseSession');
  56. if ($hasAnnotation) {
  57. $this->session->close();
  58. return $response;
  59. }
  60. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  61. $hasAttribute = !empty($reflectionMethod->getAttributes(UseSession::class));
  62. if ($hasAttribute) {
  63. $this->session->close();
  64. }
  65. return $response;
  66. }
  67. }