Files
grocy/middleware/SessionAuthMiddleware.php

64 lines
1.6 KiB
PHP
Raw Normal View History

2018-04-11 19:49:35 +02:00
<?php
namespace Grocy\Middleware;
2018-04-12 21:13:38 +02:00
use \Grocy\Services\SessionService;
use \Grocy\Services\LocalizationService;
2018-04-11 19:49:35 +02:00
2018-04-14 11:10:38 +02:00
class SessionAuthMiddleware extends BaseMiddleware
2018-04-11 19:49:35 +02:00
{
public function __construct(\Slim\Container $container, string $sessionCookieName)
{
parent::__construct($container);
$this->SessionCookieName = $sessionCookieName;
}
protected $SessionCookieName;
2018-04-11 19:49:35 +02:00
public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next)
{
$route = $request->getAttribute('route');
$routeName = $route->getName();
2018-07-25 19:28:15 +02:00
$sessionService = new SessionService();
2018-04-11 19:49:35 +02:00
2018-07-25 19:28:15 +02:00
if ($routeName === 'root')
2018-04-11 19:49:35 +02:00
{
2018-07-25 19:28:15 +02:00
$response = $next($request, $response);
}
elseif (GROCY_IS_DEMO_INSTALL || GROCY_IS_EMBEDDED_INSTALL)
{
$user = $sessionService->GetDefaultUser();
define('GROCY_AUTHENTICATED', true);
define('GROCY_USER_USERNAME', $user->username);
$response = $next($request, $response);
2018-04-11 19:49:35 +02:00
}
else
{
if ((!isset($_COOKIE[$this->SessionCookieName]) || !$sessionService->IsValidSession($_COOKIE[$this->SessionCookieName])) && $routeName !== 'login')
{
2018-07-24 19:41:35 +02:00
define('GROCY_AUTHENTICATED', false);
$response = $response->withRedirect($this->AppContainer->UrlManager->ConstructUrl('/login'));
}
else
{
if ($routeName !== 'login')
{
$user = $sessionService->GetUserBySessionKey($_COOKIE[$this->SessionCookieName]);
2018-07-24 19:41:35 +02:00
define('GROCY_AUTHENTICATED', true);
define('GROCY_USER_USERNAME', $user->username);
define('GROCY_USER_ID', $user->id);
}
else
{
2018-07-24 19:41:35 +02:00
define('GROCY_AUTHENTICATED', false);
}
$response = $next($request, $response);
}
2018-04-11 19:49:35 +02:00
}
return $response;
}
}