Base API, and more solid key and check
This commit is contained in:
@ -6,10 +6,12 @@ use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
use Incoviba\Exception\MissingAuthorizationHeader;
|
||||
use Incoviba\Service;
|
||||
|
||||
class API
|
||||
{
|
||||
public function __construct(protected ResponseFactoryInterface $responseFactory, protected string $key) {}
|
||||
public function __construct(protected ResponseFactoryInterface $responseFactory, protected Service\Login $loginService,
|
||||
protected string $key) {}
|
||||
|
||||
public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
@ -18,7 +20,7 @@ class API
|
||||
} catch (MissingAuthorizationHeader $exception) {
|
||||
return $this->responseFactory->createResponse(401);
|
||||
}
|
||||
if ($this->validate($key)) {
|
||||
if ($this->validate($request, $key)) {
|
||||
return $handler->handle($request);
|
||||
}
|
||||
return $this->responseFactory->createResponse(403);
|
||||
@ -33,8 +35,26 @@ class API
|
||||
}
|
||||
throw new MissingAuthorizationHeader();
|
||||
}
|
||||
protected function validate($incoming_key): bool
|
||||
protected function validate(ServerRequestInterface $request, $incoming_key): bool
|
||||
{
|
||||
if (str_contains($incoming_key, $this->loginService->getSeparator())) {
|
||||
list($incoming_key, $selector, $token) = explode($this->loginService->getSeparator(), $incoming_key);
|
||||
if (!$this->loginService->isIn()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!$this->loginService->isIn() and !$this->validPermitted($request)) {
|
||||
return false;
|
||||
}
|
||||
return $incoming_key === md5($this->key);
|
||||
}
|
||||
protected function validPermitted(ServerRequestInterface $request): bool
|
||||
{
|
||||
$uri = $request->getUri();
|
||||
$validPaths = [
|
||||
'/api',
|
||||
'/api/'
|
||||
];
|
||||
return in_array($uri->getPath(), $validPaths);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user