mirror of
https://github.com/grocy/grocy.git
synced 2025-04-29 17:45:39 +00:00
65 lines
1.7 KiB
PHP
65 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace Grocy\Middleware;
|
|
|
|
use \Grocy\Services\SessionService;
|
|
use \Grocy\Services\ApiKeyService;
|
|
|
|
class ApiKeyAuthMiddleware extends BaseMiddleware
|
|
{
|
|
public function __construct(\Slim\Container $container, string $sessionCookieName, string $apiKeyHeaderName)
|
|
{
|
|
parent::__construct($container);
|
|
$this->SessionCookieName = $sessionCookieName;
|
|
$this->ApiKeyHeaderName = $apiKeyHeaderName;
|
|
}
|
|
|
|
protected $SessionCookieName;
|
|
protected $ApiKeyHeaderName;
|
|
|
|
public function __invoke(\Slim\Http\Request $request, \Slim\Http\Response $response, callable $next)
|
|
{
|
|
$route = $request->getAttribute('route');
|
|
$routeName = $route->getName();
|
|
|
|
if (GROCY_IS_DEMO_INSTALL || GROCY_IS_EMBEDDED_INSTALL)
|
|
{
|
|
define('GROCY_AUTHENTICATED', true);
|
|
$response = $next($request, $response);
|
|
}
|
|
else
|
|
{
|
|
$validSession = true;
|
|
$validApiKey = true;
|
|
|
|
$sessionService = new SessionService();
|
|
if (!isset($_COOKIE[$this->SessionCookieName]) || !$sessionService->IsValidSession($_COOKIE[$this->SessionCookieName]))
|
|
{
|
|
$validSession = false;
|
|
}
|
|
|
|
$apiKeyService = new ApiKeyService();
|
|
if (!$request->hasHeader($this->ApiKeyHeaderName) || !$apiKeyService->IsValidApiKey($request->getHeaderLine($this->ApiKeyHeaderName)))
|
|
{
|
|
$validApiKey = false;
|
|
}
|
|
|
|
if (!$validSession && !$validApiKey)
|
|
{
|
|
define('GROCY_AUTHENTICATED', false);
|
|
$response = $response->withStatus(401);
|
|
}
|
|
else
|
|
{
|
|
$user = $apiKeyService->GetUserByApiKey($request->getHeaderLine($this->ApiKeyHeaderName));
|
|
define('GROCY_AUTHENTICATED', true);
|
|
define('GROCY_USER_ID', $user->id);
|
|
|
|
$response = $next($request, $response);
|
|
}
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
}
|