From 491ee376517cded3c9c8d2389e3f9f21daa1a407 Mon Sep 17 00:00:00 2001 From: Igor Scheller Date: Fri, 28 Dec 2018 03:28:33 +0100 Subject: Don't save sessions permanently on api and metrics paths closes #530 (Session on API calls) --- src/Middleware/RouteDispatcher.php | 4 +- src/Middleware/SessionHandler.php | 59 ++++++++++++++++++++++++ src/Middleware/SessionHandlerServiceProvider.php | 24 ++++++++++ 3 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 src/Middleware/SessionHandler.php create mode 100644 src/Middleware/SessionHandlerServiceProvider.php (limited to 'src/Middleware') diff --git a/src/Middleware/RouteDispatcher.php b/src/Middleware/RouteDispatcher.php index 24a7906d..c20eba4b 100644 --- a/src/Middleware/RouteDispatcher.php +++ b/src/Middleware/RouteDispatcher.php @@ -50,7 +50,8 @@ class RouteDispatcher implements MiddlewareInterface $path = $request->getPathInfo(); } - $route = $this->dispatcher->dispatch($request->getMethod(), urldecode($path)); + $path = urldecode($path); + $route = $this->dispatcher->dispatch($request->getMethod(), $path); $status = $route[0]; if ($status == FastRouteDispatcher::NOT_FOUND) { @@ -70,6 +71,7 @@ class RouteDispatcher implements MiddlewareInterface $routeHandler = $route[1]; $request = $request->withAttribute('route-request-handler', $routeHandler); + $request = $request->withAttribute('route-request-path', $path); $vars = $route[2]; foreach ($vars as $name => $value) { diff --git a/src/Middleware/SessionHandler.php b/src/Middleware/SessionHandler.php new file mode 100644 index 00000000..8c53b0fd --- /dev/null +++ b/src/Middleware/SessionHandler.php @@ -0,0 +1,59 @@ +paths = $paths; + $this->session = $session; + } + + /** + * @param ServerRequestInterface $request + * @param RequestHandlerInterface $handler + * @return ResponseInterface + */ + public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface + { + $return = $handler->handle($request); + + $cookies = $request->getCookieParams(); + if ( + $this->session instanceof NativeSessionStorage + && in_array($request->getAttribute('route-request-path'), $this->paths) + && !isset($cookies[$this->session->getName()]) + ) { + $this->destroyNative(); + } + + return $return; + } + + /** + * @return bool + * @codeCoverageIgnore + */ + protected function destroyNative() + { + return session_destroy(); + } +} diff --git a/src/Middleware/SessionHandlerServiceProvider.php b/src/Middleware/SessionHandlerServiceProvider.php new file mode 100644 index 00000000..aefcb674 --- /dev/null +++ b/src/Middleware/SessionHandlerServiceProvider.php @@ -0,0 +1,24 @@ +app + ->when(SessionHandler::class) + ->needs('$paths') + ->give(function () { + return [ + '/api', + '/ical', + '/metrics', + '/shifts-json-export', + '/stats', + ]; + }); + } +} -- cgit v1.2.3-54-g00ecf