- Added a new CSRF token verification Middleware.
- Added a new ActionLog middleware to catch every modifying request and save the changes made and the user who did. - Added a new RequestLog to catch every request made whenever required.
This commit is contained in:
1 parent
9571c6a462
commit
4b86ac9e82
42 files changed
+1331
-148
No files matched your search
@@ -51,21 +51,15 @@ return [
|
|||||||
],
|
],
|
||||||
],
|
],
|
||||||
|
|
||||||
'lean.api:storage' => function($c) {
|
|
||||||
$adapter = new ConnectionAdapter('lean.api', $c->get('config')['ulmus'], false);
|
|
||||||
$adapter->resolveConfiguration();
|
|
||||||
|
|
||||||
return $adapter;
|
|
||||||
},
|
|
||||||
|
|
||||||
'app.middlewares' => \DI\add([
|
'app.middlewares' => \DI\add([
|
||||||
Lean\Api\Middleware\CORS::class,
|
# Lean\Api\Middleware\Security\CORSMiddleware::class,
|
||||||
|
# Lean\Api\Middleware\Security\RequestLogMiddleware::class,
|
||||||
]),
|
]),
|
||||||
|
|
||||||
Lean\Api\Lib\RenderCORS::class => DI\create(Lean\Api\Lib\RenderCORS::class)->constructor(get(\Psr\Http\Message\ServerRequestInterface::class), env('LEAN_API_CORS_ORIGIN', '*')),
|
|
||||||
Lean\ApplicationStrategy\NotFoundDecoratorInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\NotFoundDecorator::class),
|
Lean\ApplicationStrategy\NotFoundDecoratorInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\NotFoundDecorator::class),
|
||||||
Lean\ApplicationStrategy\MethodNotAllowedInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\MethodNotAllowedDecorator::class),
|
Lean\ApplicationStrategy\MethodNotAllowedInterface::class => DI\autowire(Lean\Api\ApplicationStrategy\MethodNotAllowedDecorator::class),
|
||||||
Lean\Api\Factory\MessageFactoryInterface::class => DI\autowire(Lean\Api\Lib\Message::class),
|
Lean\Api\Factory\MessageFactoryInterface::class => DI\autowire(Lean\Api\Lib\Message::class),
|
||||||
Lean\Api\Factory\DebugFormFactoryInterface::class => DI\autowire(Lean\Api\Factory\DebugFormFactory::class),
|
Lean\Api\Factory\LeanApiFormFactoryInterface::class => DI\autowire(Lean\Api\Factory\LeanApiFormFactory::class),
|
||||||
|
Lean\Api\Lib\RenderCORS::class => DI\create(Lean\Api\Lib\RenderCORS::class)->constructor(get(\Psr\Http\Message\ServerRequestInterface::class), env('LEAN_API_CORS_ORIGIN', '*')),
|
||||||
# League\Route\Strategy\ApplicationStrategy::class => DI\autowire(Lean\Api\ApplicationStrategy::class),
|
# League\Route\Strategy\ApplicationStrategy::class => DI\autowire(Lean\Api\ApplicationStrategy::class),
|
||||||
];
|
];
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# LEAN API
|
||||||
|
|
||||||
|
## An action logger to keep important actions in checks / allow easy notifications handling
|
||||||
|
|
||||||
|
[Documentation](../../) / Security / Action logs
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
### Available routes
|
||||||
|
|
||||||
|
{route:descriptor}
|
||||||
|
|
||||||
|
{request:debugger}
|
||||||
|
|
||||||
|
### Forms
|
||||||
|
|
||||||
|
{form:descriptor}
|
||||||
|
|
||||||
|
### Entity
|
||||||
|
|
||||||
|
{entity:descriptor}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# LEAN API
|
||||||
|
|
||||||
|
## CSRF Token generation for non-idempotent requests
|
||||||
|
|
||||||
|
[Documentation](../../) / Security / CRSF
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
### Available routes
|
||||||
|
|
||||||
|
{route:descriptor}
|
||||||
|
|
||||||
|
{request:debugger}
|
||||||
|
|
||||||
|
### Forms
|
||||||
|
|
||||||
|
{form:descriptor}
|
||||||
|
|
||||||
|
### Entity
|
||||||
|
|
||||||
|
{entity:descriptor}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# LEAN API
|
||||||
|
|
||||||
|
## Logging request logs allowing deeper forensic than simple request logs
|
||||||
|
|
||||||
|
[Documentation](../../) / Security / Requests
|
||||||
|
|
||||||
|
--------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
### Available routes
|
||||||
|
|
||||||
|
{route:descriptor}
|
||||||
|
|
||||||
|
{request:debugger}
|
||||||
|
|
||||||
|
### Forms
|
||||||
|
|
||||||
|
{form:descriptor}
|
||||||
|
|
||||||
|
### Entity
|
||||||
|
|
||||||
|
{entity:descriptor}
|
||||||
@@ -80,12 +80,12 @@ class EntityGenerate
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isset($this->formNamespace)) {
|
if (isset($this->formNamespace)) {
|
||||||
$formPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->formNamespace), $this->formNamespace ]);
|
$formPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->formNamespace), str_replace('\\', DIRECTORY_SEPARATOR, $this->formNamespace) ]);
|
||||||
$formPath = $this->readline(sprintf("Path of Forms (default: %s) : ", $formPath), $formPath);
|
$formPath = $this->readline(sprintf("Path of Forms (default: %s) : ", $formPath), $formPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isset($this->factoryNamespace)) {
|
if (isset($this->factoryNamespace)) {
|
||||||
$factoryPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->factoryNamespace), $this->factoryNamespace ]);
|
$factoryPath = implode(DIRECTORY_SEPARATOR, [ $this->pathFromPSR($this->factoryNamespace), str_replace('\\', DIRECTORY_SEPARATOR, $this->factoryNamespace) ]);
|
||||||
$factoryPath = $this->readline(sprintf("Path of Factory (default: %s) : ", $factoryPath), $factoryPath);
|
$factoryPath = $this->readline(sprintf("Path of Factory (default: %s) : ", $factoryPath), $factoryPath);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Attribute\Security;
|
||||||
|
|
||||||
|
#[\Attribute(\Attribute::TARGET_METHOD)]
|
||||||
|
class ActionLog
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
#public string $key,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -13,7 +13,6 @@ use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
|||||||
## [Taxus(Entity\UserTypeEnum::Developer)]
|
## [Taxus(Entity\UserTypeEnum::Developer)]
|
||||||
#[RouteObj(base: "/lean/debug/errors")]
|
#[RouteObj(base: "/lean/debug/errors")]
|
||||||
class Errors {
|
class Errors {
|
||||||
|
|
||||||
use \Lean\Api\Lib\ControllerTrait;
|
use \Lean\Api\Lib\ControllerTrait;
|
||||||
|
|
||||||
#[Route("/documentation", name: "lean.api:errors-doc", method: "GET", description: "Documentation section")]
|
#[Route("/documentation", name: "lean.api:errors-doc", method: "GET", description: "Documentation section")]
|
||||||
|
|||||||
@@ -1,23 +1,22 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Lean\Api\Controller;
|
namespace Lean\Api\Controller;
|
||||||
|
|
||||||
use Lean\Api\{Controller, Entity, Form, Lib};
|
use Lean\Api\{Controller, Entity, Form, Lib};
|
||||||
use Notes\Route\Attribute\Method\Route;
|
use Notes\Route\Attribute\Method\Route;
|
||||||
use Notes\Route\Attribute\Object\Route as RouteObj;
|
use Notes\Route\Attribute\Object\Route as RouteObj;
|
||||||
use Notes\Security\Attribute\Security;
|
use Notes\Security\Attribute\Security;
|
||||||
use Notes\Security\Attribute\Taxus;
|
use Notes\Security\Attribute\Taxus;
|
||||||
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
||||||
|
|
||||||
#[Security(locked: false)]
|
#[Security(locked: false)]
|
||||||
#[RouteObj(base: "/lean/debug")]
|
#[RouteObj(base: "/lean")]
|
||||||
class Debug {
|
class LeanApi {
|
||||||
|
use \Lean\Api\Lib\ControllerTrait;
|
||||||
use \Lean\Api\Lib\ControllerTrait;
|
|
||||||
|
#[Route("/", name: "lean.api:doc", method: "GET", description: "Documentation section")]
|
||||||
#[Route("/", name: "lean.api:debug-doc", method: "GET", description: "Documentation section")]
|
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
||||||
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
{
|
||||||
{
|
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/lean-api.md", [ ], [ ]);
|
||||||
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/lean-api.md", [ Entity\Error::class, ], [ Form\Debug\ErrorContext::class ]);
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Controller\Security;
|
||||||
|
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
|
||||||
|
use Notes\Route\Attribute\Method\Route;
|
||||||
|
use Notes\Security\Attribute\Security;
|
||||||
|
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
#[Security(locked: true)]
|
||||||
|
##[Taxus(Entity\UserTypeEnum::Developer)]
|
||||||
|
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/action-logs")]
|
||||||
|
class ActionLog {
|
||||||
|
use \Lean\Api\Lib\ControllerTrait;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected UserInterface $user;
|
||||||
|
|
||||||
|
#[Route("/documentation", name: "lean.api:security-action-log-doc", method: "GET", description: "Route de documentation pour cette section")]
|
||||||
|
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
||||||
|
{
|
||||||
|
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/action-logs.md", [ \Lean\Api\Entity\Security\ApiRequestLog::class ], [ \Lean\Api\Form\Security\RequestLogContext::class ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Route("/", name: "lean.api:security-action-log-list", method: [ "GET" ], description: "Affiche la liste de toute les journaux d'actions")]
|
||||||
|
public function list(ServerRequestInterface $request, array $arguments): ResponseInterface
|
||||||
|
{
|
||||||
|
$result = $this->searchEntitiesFromRequest($request, $this->leanApiEntityFactory->securityApiActionLog)
|
||||||
|
->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityApiActionLog];
|
||||||
|
|
||||||
|
return $this->outputSearchResult($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Route("/{id:\d+}", name: "lean.api:security-action-log-single", method: [ "GET" ], description: "Permet de récupérer une action par son id")]
|
||||||
|
public function single(ServerRequestInterface $request, array $arguments): ResponseInterface
|
||||||
|
{
|
||||||
|
$result = $this->searchEntityFromRequest($request, $this->leanApiEntityFactory->securityApiActionLog)
|
||||||
|
->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityApiActionLog];
|
||||||
|
|
||||||
|
return $this->outputSearchResult($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
# No routes needed, every modifying request hits this method
|
||||||
|
public function add(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
||||||
|
{
|
||||||
|
$entity = new $this->leanApiEntityFactory->securityApiActionLog();
|
||||||
|
|
||||||
|
$this->form($this->leanApiFormFactory->securityActionLogSave($entity, $this->user), $request->getAttribute('lean-api.security-action:context'));
|
||||||
|
|
||||||
|
return $this->output($entity, (int) $entity->isLoaded());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Controller\Security;
|
||||||
|
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
|
||||||
|
use Notes\Route\Attribute\Method\Route;
|
||||||
|
use Notes\Security\Attribute\Security;
|
||||||
|
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
#[Security(locked: true)]
|
||||||
|
##[Taxus(Entity\UserTypeEnum::Developer)]
|
||||||
|
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/csrf")]
|
||||||
|
class CSRF {
|
||||||
|
use \Lean\Api\Lib\ControllerTrait;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected UserInterface $user;
|
||||||
|
|
||||||
|
#[Route("/documentation", name: "lean.api:security-csrf-doc", method: "GET", description: "Route de documentation pour cette section")]
|
||||||
|
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
||||||
|
{
|
||||||
|
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/csrf.md", [ ], [ ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Route("/", name: "lean.api:security-csrf-generate", method: [ "GET" ], description: "Generate a CSRF token")]
|
||||||
|
public function generate(ServerRequestInterface $request, array $arguments): ResponseInterface
|
||||||
|
{
|
||||||
|
$context = $this->leanApiFormFactory->securityCsrfGenerateContext($request->withMethod('PUT'));
|
||||||
|
|
||||||
|
return $this->output([
|
||||||
|
'token' => $this->form($this->leanApiFormFactory->securityCsrfGenerate($this->user), $context)->executionStatus
|
||||||
|
], 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Route("/{token}", name: "lean.api:security-csrf-test-token", method: [ "POST", "PUT", "DELETE", "PATCH" ], description: "Verify a CSRF token")]
|
||||||
|
public function test(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$valid = $this->validate($request->withHeader('X-CSRF-Token', $arguments['token']), $arguments);
|
||||||
|
}
|
||||||
|
catch (\Throwable $ex) {
|
||||||
|
$valid = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return $this->output([
|
||||||
|
'valid' => $valid
|
||||||
|
], 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function validate(ServerRequestInterface $request, array $arguments) : bool
|
||||||
|
{
|
||||||
|
$context = $this->leanApiFormFactory->securityCsrfVerifyTokenContext($request);
|
||||||
|
|
||||||
|
# This form call WILL throw an exception if anything is wrong (missing, invalid, outdated) with the CSRF token.
|
||||||
|
return (bool) $this->form($this->leanApiFormFactory->securityCsrfVerifyToken($this->user, $arguments['token']), $context)->executionStatus;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Controller\Security;
|
||||||
|
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use CSSLSJ\TransportScolaire\Api\{Entity, Form};
|
||||||
|
use Notes\Route\Attribute\Method\Route;
|
||||||
|
use Notes\Security\Attribute\Security;
|
||||||
|
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
#[Security(locked: true)]
|
||||||
|
##[Taxus(Entity\UserTypeEnum::Developer)]
|
||||||
|
#[\Notes\Route\Attribute\Object\Route(base: "/lean/security/request-logs")]
|
||||||
|
class RequestLog {
|
||||||
|
use \Lean\Api\Lib\ControllerTrait;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected UserInterface $user;
|
||||||
|
|
||||||
|
#[Route("/documentation", name: "lean.api:security-request-log-doc", method: "GET", description: "Route de documentation pour cette section")]
|
||||||
|
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
||||||
|
{
|
||||||
|
return $this->renderMarkdown(LEAN_API_PROJECT_PATH . "/meta/docs/security/request-logs.md", [ \Lean\Api\Entity\Security\ApiRequestLog::class ], [ \Lean\Api\Form\Security\RequestLogContext::class ]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Route("/", name: "lean.api:security-request-log-list", method: [ "GET" ], description: "Affiche la liste de toute les journaux de requête")]
|
||||||
|
public function list(ServerRequestInterface $request, array $arguments): ResponseInterface
|
||||||
|
{
|
||||||
|
$result = $this->searchEntitiesFromRequest($request, $this->leanApiEntityFactory->securityRequestLog)
|
||||||
|
->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityRequestLog];
|
||||||
|
|
||||||
|
return $this->outputSearchResult($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Route("/{id:\d+}", name: "lean.api:security-request-log-single", method: [ "GET" ], description: "Permet de récupérer une requête par son id")]
|
||||||
|
public function single(ServerRequestInterface $request, array $arguments): ResponseInterface
|
||||||
|
{
|
||||||
|
$result = $this->searchEntityFromRequest($request, $this->leanApiEntityFactory->securityRequestLog)
|
||||||
|
->getAttribute('lean.searchRequest')[$this->leanApiEntityFactory->securityRequestLog];
|
||||||
|
|
||||||
|
return $this->outputSearchResult($result);
|
||||||
|
}
|
||||||
|
|
||||||
|
# No routes needed, every request hits this method
|
||||||
|
public function add(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
||||||
|
{
|
||||||
|
$entity = new $this->leanApiEntityFactory->securityRequestLog();
|
||||||
|
|
||||||
|
$context = $this->leanApiFormFactory->securityRequestLogSaveContext($request->withAttribute('api:request-log-original-method', $request->getMethod())-> withMethod('PUT'));
|
||||||
|
|
||||||
|
$this->form($this->leanApiFormFactory->securityRequestLogSave($entity, $arguments['response'], $this->user), $context);
|
||||||
|
|
||||||
|
return $this->output($entity, (int) $entity->isLoaded());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Cronard;
|
||||||
|
|
||||||
|
use CSSLSJ\TransportScolaire\Api\{Controller\Api, Entity, Form, Lib};
|
||||||
|
use Notes\Breadcrumb\Attribute\Method\Breadcrumb;
|
||||||
|
use Notes\Cronard\Attribute\Method\Cronard;
|
||||||
|
use Notes\Route\Attribute\Method\Route;
|
||||||
|
use Notes\Route\Attribute\Object\Route as RouteObj;
|
||||||
|
use Notes\Security\Attribute\Taxus;
|
||||||
|
use Psr\Http\Message\{ResponseInterface, ServerRequestInterface};
|
||||||
|
use Storage\{Cookie, Session};
|
||||||
|
use TheBugs\Email\MailerInterface;
|
||||||
|
use function CSSLSJ\TransportScolaire\Api\View\{form, route};
|
||||||
|
|
||||||
|
##[Taxus(Entity\UserTypeEnum::Developer)]
|
||||||
|
#[RouteObj(base: "/lean/cronard")]
|
||||||
|
class System {
|
||||||
|
use Lib\ControllerTrait;
|
||||||
|
|
||||||
|
#[Route("/", name: "lean-api.cronard:documentation", method: "GET", description: "Route de documentation pour cette section")]
|
||||||
|
public function documentation(ServerRequestInterface $request, array $arguments) : ResponseInterface
|
||||||
|
{
|
||||||
|
return $this->renderMarkdown(getenv("PROJECT_PATH") . "/meta/docs/cronard.md", [ ], []);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Cronard('0 0 1 * *')]
|
||||||
|
#[Route("/clean/request-logs", name: "lean-api.cronard:clean-request-logs", method: ["DELETE"], description: "Fait le ménage automatiquement des logs de requêtes datant de plus d'un an")]
|
||||||
|
public function clean_request_logs(ServerRequestInterface $request, array $arguments): ResponseInterface
|
||||||
|
{
|
||||||
|
# return $this->outputSearchResult($results);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Entity\Security;
|
||||||
|
|
||||||
|
use Lean\Api\Attribute\EntityField;
|
||||||
|
use Notes\Attribute\Ignore;
|
||||||
|
use Ulmus\Attribute\Obj\Table;
|
||||||
|
use Ulmus\Attribute\Property\{Field, Filter, FilterJoin, OrderBy, Relation, Join, Virtual, Where};
|
||||||
|
use Ulmus\Common\Sql;
|
||||||
|
use Ulmus\Entity\EntityInterface;
|
||||||
|
use Ulmus\Repository;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
use Ulmus\SearchRequest;
|
||||||
|
|
||||||
|
#[Table(name: "lean_api_security_action_logs", adapter: "lean.api")]
|
||||||
|
class ApiActionLog implements EntityInterface, \JsonSerializable
|
||||||
|
{
|
||||||
|
use \Ulmus\EntityTrait;
|
||||||
|
|
||||||
|
#[Field\Id(name: "id")]
|
||||||
|
public int $id;
|
||||||
|
|
||||||
|
#[Field\ForeignKey(name: "object_id"), EntityField(field: "object_id")]
|
||||||
|
public int $objectId;
|
||||||
|
|
||||||
|
#[Field(name: "object_type"), EntityField(field: "object_type")]
|
||||||
|
public string $objectType;
|
||||||
|
|
||||||
|
#[Field\ForeignKey(name: "user_id"), EntityField(field: "user_id")]
|
||||||
|
public ? int $userId;
|
||||||
|
|
||||||
|
#[Field(name: "user_type", length: 100), EntityField(field: "user_type")]
|
||||||
|
public ? string $userType;
|
||||||
|
|
||||||
|
#[Field(name: "event", length: 100), EntityField]
|
||||||
|
public string $event;
|
||||||
|
|
||||||
|
#[Field(name: "method", length: 15), EntityField]
|
||||||
|
public string $method;
|
||||||
|
|
||||||
|
#[Field(name: "description"), EntityField]
|
||||||
|
public ? string $description;
|
||||||
|
|
||||||
|
#[Field(name: "data"), EntityField]
|
||||||
|
public array $data;
|
||||||
|
|
||||||
|
#[Field(name: "created_at")]
|
||||||
|
public \Ulmus\Entity\Field\Datetime $createdAt;
|
||||||
|
|
||||||
|
#[Relation("oneToOne", key: "user", foreignKey: "id")]
|
||||||
|
public UserInterface $userEntity;
|
||||||
|
|
||||||
|
public function getUser() : ? UserInterface
|
||||||
|
{
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
public function getHash() : string
|
||||||
|
{
|
||||||
|
return md5(sprintf("%d:%s", $this->id, $this->objectType));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[Ignore]
|
||||||
|
public static function searchRequest(...$arguments) : SearchRequest\SearchRequestInterface
|
||||||
|
{
|
||||||
|
return new #[SearchRequest\Attribute\SearchRequestParameter(ApiActionLog::class, description: "Les établissements peuvent être recherchés/filtrés de différentes manière en requête GET en empruntant la route de liste complète.")] class(... $arguments) extends SearchRequest\SearchRequest {
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchWhere(source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
||||||
|
public string $event;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchWhere(source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
||||||
|
public string $method;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchWhere(parameter: "object_type", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
||||||
|
public string $objectType;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchWhere(parameter: "object_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
||||||
|
public int $objectId;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchWhere(parameter: "user_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
||||||
|
public int $userId;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchWhere(parameter: "user_id", source: SearchRequest\Attribute\PropertyValueSource::ATTRIBUTE_FIRST)]
|
||||||
|
public string $userType;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchOrderBy(field: "createdAt")]
|
||||||
|
public SearchRequest\Attribute\OrderByEnum $orderByDate = SearchRequest\Attribute\OrderByEnum::Descending;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchManual]
|
||||||
|
public int $page = 1;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchManual]
|
||||||
|
public int $limit = 0;
|
||||||
|
|
||||||
|
public function filter(Repository $repository) : Repository
|
||||||
|
{
|
||||||
|
return $repository;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Entity\Security;
|
||||||
|
|
||||||
|
use Lean\Api\Entity\Field\Datetime;
|
||||||
|
use Lean\Api\Lib;
|
||||||
|
use Lean\Api\Attribute\EntityField;
|
||||||
|
use Notes\Attribute\Ignore;
|
||||||
|
use Ulmus\Attribute\Obj\Table;
|
||||||
|
use Ulmus\Attribute\Property\{Field};
|
||||||
|
use Ulmus\Entity\EntityInterface;
|
||||||
|
use Ulmus\SearchRequest;
|
||||||
|
|
||||||
|
#[Table(name: "lean_api_security_request_logs", adapter: "lean.api")]
|
||||||
|
class ApiRequestLog implements EntityInterface, \JsonSerializable
|
||||||
|
{
|
||||||
|
use \Ulmus\EntityTrait;
|
||||||
|
|
||||||
|
#[Field\PrimaryKey]
|
||||||
|
public int $id;
|
||||||
|
|
||||||
|
#[Field\ForeignKey(name: "user_id")]
|
||||||
|
#[EntityField(description: "ID de l'usagé (lorsque connecté) qui a lancé la requête", field: 'user_id')]
|
||||||
|
public ? int $userId = null;
|
||||||
|
|
||||||
|
#[Field(length: 10)]
|
||||||
|
#[EntityField(description: "Method HTTP")]
|
||||||
|
public string $method;
|
||||||
|
|
||||||
|
#[Field(length: 255)]
|
||||||
|
#[EntityField(description: "URI sans les paramètres")]
|
||||||
|
public string $endpoint;
|
||||||
|
|
||||||
|
#[Field(length: 15)]
|
||||||
|
#[EntityField(description: "IPv4 de l'usagé")]
|
||||||
|
public ? string $ipv4;
|
||||||
|
|
||||||
|
#[Field(length: 45)]
|
||||||
|
#[EntityField(description: "IPv6 de l'usagé")]
|
||||||
|
public ? string $ipv6;
|
||||||
|
|
||||||
|
#[Field(name: "request_headers")]
|
||||||
|
#[EntityField(field: "request_headers")]
|
||||||
|
public array $requestHeaders = [];
|
||||||
|
|
||||||
|
#[Field(name: "request_body")]
|
||||||
|
#[EntityField(field: "request_body")]
|
||||||
|
public array $requestBody = [];
|
||||||
|
|
||||||
|
#[Field(name: "status_code")]
|
||||||
|
#[EntityField(field: "status_code")]
|
||||||
|
public int $statusCode;
|
||||||
|
|
||||||
|
#[Field(name: "response_headers")]
|
||||||
|
#[EntityField(field: "response_headers")]
|
||||||
|
public array $responseHeaders = [];
|
||||||
|
|
||||||
|
#[Field(name: "response_body")]
|
||||||
|
#[EntityField(field: "response_body")]
|
||||||
|
public ? string $responseBody;
|
||||||
|
|
||||||
|
#[Field]
|
||||||
|
#[EntityField(field: "duration")]
|
||||||
|
public float $duration;
|
||||||
|
|
||||||
|
#[Field\UpdatedAt(name: "updated_at", readonly: true)]
|
||||||
|
#[EntityField(description: "Date de la dernière mise-à-jour pour cette donnée.")]
|
||||||
|
public ? Datetime $updatedAt;
|
||||||
|
|
||||||
|
#[Field\CreatedAt(name: "created_at", readonly: true)]
|
||||||
|
#[EntityField(description: "Date de création pour cette donnée.")]
|
||||||
|
public Datetime $createdAt;
|
||||||
|
|
||||||
|
#[Ignore]
|
||||||
|
public static function searchRequest(...$arguments) : SearchRequest\SearchRequestInterface
|
||||||
|
{
|
||||||
|
return new #[SearchRequest\Attribute\SearchRequestParameter(ApiRequestLog::class,)] class(... $arguments) extends SearchRequest\SearchRequest {
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchWhere(parameter: 'id', description: "Récupère une requete par son id unique.", source: SearchRequest\Attribute\PropertyValueSource::RequestAttribute)]
|
||||||
|
public string $id;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchOrderBy(field: "createdAt")]
|
||||||
|
public string $orderByDate = "DESC";
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchManual]
|
||||||
|
public int $page = 1;
|
||||||
|
|
||||||
|
#[SearchRequest\Attribute\SearchManual]
|
||||||
|
public int $limit = 50;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Exception;
|
||||||
|
|
||||||
|
class CSRFInvalidToken extends \Exception {}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Exception;
|
||||||
|
|
||||||
|
class CSRFMissingToken extends \Exception {}
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
<?php
|
|
||||||
|
|
||||||
namespace Lean\Api\Factory;
|
|
||||||
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
|
||||||
use Picea\Ui\Method\FormInterface;
|
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Ulmus\Entity\EntityInterface;
|
|
||||||
use Lean\Api\Entity;
|
|
||||||
|
|
||||||
interface DebugFormFactoryInterface
|
|
||||||
{
|
|
||||||
public function __construct(ServerRequestInterface $request, LanguageHandler $languageHandler, MessageFactoryInterface $messageFactory,);
|
|
||||||
|
|
||||||
### ERROR SAVE
|
|
||||||
public function errorSave(Entity\Error|EntityInterface $entity): FormInterface;
|
|
||||||
public function errorSaveContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
|
|
||||||
public function errorDelete(Entity\Error|EntityInterface $entity): FormInterface;
|
|
||||||
public function errorDeleteContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
|
|
||||||
}
|
|
||||||
@@ -1,21 +1,14 @@
|
|||||||
<?php
|
<?php
|
||||||
|
|
||||||
namespace Lean\Api\Factory;
|
namespace Lean\Api\Factory\FormFactories;
|
||||||
|
|
||||||
use Lean\Api\{Factory, Form, Entity, Lib};
|
|
||||||
use Lean\LanguageHandler;
|
|
||||||
use Picea\Ui\Method\FormContextInterface;
|
use Picea\Ui\Method\FormContextInterface;
|
||||||
use Picea\Ui\Method\FormInterface;
|
use Picea\Ui\Method\FormInterface;
|
||||||
use Psr\Http\Message\ServerRequestInterface;
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
use Ulmus\Entity\EntityInterface;
|
use Ulmus\Entity\EntityInterface;
|
||||||
|
use Lean\Api\{Factory, Form, Entity, Lib};
|
||||||
|
|
||||||
class DebugFormFactory implements DebugFormFactoryInterface
|
trait DebugTrait{
|
||||||
{
|
|
||||||
public function __construct(
|
|
||||||
protected ServerRequestInterface $request,
|
|
||||||
protected LanguageHandler $languageHandler,
|
|
||||||
protected MessageFactoryInterface $messageFactory,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public function errorSave(EntityInterface|Entity\Error $entity): FormInterface
|
public function errorSave(EntityInterface|Entity\Error $entity): FormInterface
|
||||||
{
|
{
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Factory\FormFactories;
|
||||||
|
|
||||||
|
use Picea\Ui\Method\FormContextInterface;
|
||||||
|
use Picea\Ui\Method\FormInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Ulmus\Entity\EntityInterface;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
trait SecurityTrait
|
||||||
|
{
|
||||||
|
public function securityRequestLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiRequestLog $entity, ResponseInterface $response, UserInterface $user): FormInterface
|
||||||
|
{
|
||||||
|
return new \Lean\Api\Form\Security\SaveRequestLog($this->languageHandler, $this->messageFactory, $entity, $response, $user);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function securityRequestLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
||||||
|
{
|
||||||
|
return new \Lean\Api\Form\Security\RequestLogContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function securityCsrfGenerate(UserInterface $user): FormInterface
|
||||||
|
{
|
||||||
|
return new \Lean\Api\Form\Security\CsrfGenerate($this->languageHandler, $this->messageFactory, $user, 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function securityCsrfGenerateContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
||||||
|
{
|
||||||
|
return new \Lean\Api\Form\Security\CsrfGenerateContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function securityCsrfVerifyToken(UserInterface $user, string $token): FormInterface
|
||||||
|
{
|
||||||
|
return new \Lean\Api\Form\Security\CsrfVerifyToken($this->languageHandler, $this->messageFactory, $user, $token);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function securityCsrfVerifyTokenContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
||||||
|
{
|
||||||
|
return new \Lean\Api\Form\Security\CsrfVerifyTokenContext($this->languageHandler, $this->messageFactory, $request ?: $this->request, $formName);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function securityActionLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiActionLog $entity, UserInterface $user): FormInterface
|
||||||
|
{
|
||||||
|
return new \Lean\Api\Form\Security\SaveActionLog($this->languageHandler, $this->messageFactory, $entity, $user);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function securityActionLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface
|
||||||
|
{
|
||||||
|
return new \Lean\Api\Form\Security\ActionLogContext($this->languageHandler, $this->messageFactory, $request->withParsedBody([]) ?: $this->request, $formName);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Factory;
|
||||||
|
|
||||||
|
use Lean\Api\Entity;
|
||||||
|
|
||||||
|
class LeanApiEntityFactory
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
public string $error = Entity\Error::class,
|
||||||
|
public string $securityApiActionLog = Entity\Security\ApiActionLog::class,
|
||||||
|
public string $securityRequestLog = Entity\Security\ApiRequestLog::class,
|
||||||
|
) {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Factory;
|
||||||
|
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use Lean\LanguageHandler;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
|
||||||
|
class LeanApiFormFactory implements LeanApiFormFactoryInterface
|
||||||
|
{
|
||||||
|
use FormFactories\DebugTrait, FormFactories\SecurityTrait;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected ServerRequestInterface $request;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected LanguageHandler $languageHandler;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected MessageFactoryInterface $messageFactory;
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Factory;
|
||||||
|
|
||||||
|
use Picea\Ui\Method\FormContextInterface;
|
||||||
|
use Picea\Ui\Method\FormInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Ulmus\Entity\EntityInterface;
|
||||||
|
use Lean\Api\Entity;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
interface LeanApiFormFactoryInterface
|
||||||
|
{
|
||||||
|
### SECURITY / REQUEST LOGS
|
||||||
|
public function securityRequestLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiRequestLog $entity, ResponseInterface $response, UserInterface $user): FormInterface;
|
||||||
|
public function securityRequestLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
|
||||||
|
|
||||||
|
### SECURITY / CSRF
|
||||||
|
public function securityCsrfGenerate(UserInterface $user): FormInterface;
|
||||||
|
public function securityCsrfGenerateContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
|
||||||
|
|
||||||
|
### SECURITY / ACTION LOGS
|
||||||
|
public function securityActionLogSave(EntityInterface|\Lean\Api\Entity\Security\ApiActionLog $entity, UserInterface $user): FormInterface;
|
||||||
|
public function securityActionLogSaveContext(?ServerRequestInterface $request = null, ?string $formName = null): FormContextInterface;
|
||||||
|
|
||||||
|
### DEBUG / ERROR
|
||||||
|
public function errorSave(Entity\Error|EntityInterface $entity): FormInterface;
|
||||||
|
public function errorSaveContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
|
||||||
|
public function errorDelete(Entity\Error|EntityInterface $entity): FormInterface;
|
||||||
|
public function errorDeleteContext(?ServerRequestInterface $request = null, ? string $formName = null): FormContextInterface;
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Form\Security;
|
||||||
|
|
||||||
|
use CSSLSJ\TransportScolaire\Api\{Entity};
|
||||||
|
use Lean\Api\Attribute\ContextField;
|
||||||
|
use Lean\Api\Lib\FormContext;
|
||||||
|
use Ulmus\Entity\EntityInterface;
|
||||||
|
use Ulmus\Event\Entity\DatasetFill;
|
||||||
|
use Ulmus\Ulmus;
|
||||||
|
|
||||||
|
#[ContextField(description: "")]
|
||||||
|
class ActionLogContext extends FormContext
|
||||||
|
{
|
||||||
|
protected EntityInterface $entity;
|
||||||
|
|
||||||
|
#[ContextField(mandatory: true)]
|
||||||
|
public string $event;
|
||||||
|
|
||||||
|
#[ContextField(mandatory: true)]
|
||||||
|
public string $method;
|
||||||
|
|
||||||
|
#[ContextField(mandatory: true)]
|
||||||
|
public int $object_id;
|
||||||
|
|
||||||
|
#[ContextField(mandatory: true)]
|
||||||
|
public string $object_type;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public ? int $user_id;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public string $user_type;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public string $description;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public array $data = [];
|
||||||
|
|
||||||
|
private DatasetFill $datasetFillEvent;
|
||||||
|
|
||||||
|
public function attachEntity(EntityInterface $entity) : void
|
||||||
|
{
|
||||||
|
$this->entity = $entity;
|
||||||
|
|
||||||
|
$this->datasetFillEvent = new class() implements \Ulmus\Event\Entity\DatasetFill
|
||||||
|
{
|
||||||
|
public readonly array $data;
|
||||||
|
|
||||||
|
public function execute(\Generator $generator, \Ulmus\Entity\EntityInterface $entity): void
|
||||||
|
{
|
||||||
|
$this->data = $entity::repository()->generateDatasetDiff($entity);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
$this->entity->eventRegister($this->datasetFillEvent);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function initializeEntity(\Lean\Api\Entity\Security\ApiActionLog $actionLog) : void
|
||||||
|
{
|
||||||
|
if (isset($this->entity) && $this->entity->isLoaded()) {
|
||||||
|
if ($pk = array_key_first($this->entity::resolveEntity()->getPrimaryKeyField())) {
|
||||||
|
if (isset($this->entity->$pk)) {
|
||||||
|
$this->object_id = $this->entity->$pk;
|
||||||
|
$this->object_type = $this->entity::class;
|
||||||
|
|
||||||
|
if (isset($this->datasetFillEvent->data)) {
|
||||||
|
$this->data = $this->datasetFillEvent->data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw new \InvalidArgumentException("An EntityInterface must be provided using the attachEntity() method.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function valid(? \Lean\Api\Entity\Security\ApiActionLog $actionLog = null): bool
|
||||||
|
{
|
||||||
|
return isset($this->object_id) && isset($this->object_type);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Form\Security;
|
||||||
|
|
||||||
|
use Lean\Api\{Entity};
|
||||||
|
use Lean\Api\Factory\MessageFactoryInterface;
|
||||||
|
use Lean\LanguageHandler;
|
||||||
|
use Picea\Ui\Method\FormContextInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
class CsrfGenerate extends \Lean\Api\Form\Save
|
||||||
|
{
|
||||||
|
protected string $contextClass = CsrfGenerateContext::class;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
protected LanguageHandler $languageHandler,
|
||||||
|
protected MessageFactoryInterface $message,
|
||||||
|
protected UserInterface $entity,
|
||||||
|
protected int $expires = (10 * 60), # 10 minutes
|
||||||
|
)
|
||||||
|
{
|
||||||
|
parent::__construct($this->languageHandler, $this->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function initialize(FormContextInterface $context): void { }
|
||||||
|
|
||||||
|
public function execute(FormContextInterface $context): mixed
|
||||||
|
{
|
||||||
|
$ts = ( new \Datetime() )->getTimestamp();
|
||||||
|
|
||||||
|
$jwt = new \Ulmus\User\Authorize\Bearer\JsonWebTokenEncoder([
|
||||||
|
'sub' => $this->getEntity()->isLoaded() ? $this->getEntity()->id : null,
|
||||||
|
'iat' => $ts,
|
||||||
|
'exp' => $ts + $this->expires,
|
||||||
|
], hash('sha512', getenv('LEAN_RANDOM')));
|
||||||
|
|
||||||
|
return $jwt->encode();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Form\Security;
|
||||||
|
|
||||||
|
use CSSLSJ\TransportScolaire\Api\{Entity};
|
||||||
|
use Lean\Api\Attribute\ContextField;
|
||||||
|
use Lean\Api\Exception\CSRFMissingToken;
|
||||||
|
use Lean\Api\Lib\FormContext;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
#[ContextField(description: "")]
|
||||||
|
class CsrfGenerateContext extends FormContext
|
||||||
|
{
|
||||||
|
public function valid(? UserInterface $user = null): bool
|
||||||
|
{
|
||||||
|
return parent::valid();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Form\Security;
|
||||||
|
|
||||||
|
use Lean\Api\{Entity};
|
||||||
|
use Lean\Api\Factory\MessageFactoryInterface;
|
||||||
|
use Lean\LanguageHandler;
|
||||||
|
use Picea\Ui\Method\FormContextInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Ulmus\User\Authorize\Bearer\JsonWebTokenDecoder;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
class CsrfVerifyToken extends \Lean\Api\Form\Save
|
||||||
|
{
|
||||||
|
protected string $contextClass = CsrfVerifyTokenContext::class;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
protected LanguageHandler $languageHandler,
|
||||||
|
protected MessageFactoryInterface $message,
|
||||||
|
protected UserInterface $entity,
|
||||||
|
protected string $token,
|
||||||
|
)
|
||||||
|
{
|
||||||
|
parent::__construct($this->languageHandler, $this->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function initialize(FormContextInterface $context): void { }
|
||||||
|
|
||||||
|
public function execute(FormContextInterface $context): bool
|
||||||
|
{
|
||||||
|
$decoder = new JsonWebTokenDecoder($this->token, hash('sha512', getenv('LEAN_RANDOM')));
|
||||||
|
|
||||||
|
$decoder->decode();
|
||||||
|
# Validate JWT
|
||||||
|
# throw error if any
|
||||||
|
|
||||||
|
# Validate expires
|
||||||
|
# throw expires error if any
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Form\Security;
|
||||||
|
|
||||||
|
use CSSLSJ\TransportScolaire\Api\{Entity};
|
||||||
|
use Lean\Api\Attribute\ContextField;
|
||||||
|
use Lean\Api\Exception\CSRFMissingToken;
|
||||||
|
use Lean\Api\Lib\FormContext;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
#[ContextField(description: "")]
|
||||||
|
class CsrfVerifyTokenContext extends FormContext
|
||||||
|
{
|
||||||
|
public function valid(? UserInterface $user = null): bool
|
||||||
|
{
|
||||||
|
if ( in_array($this->getRequest()->getMethod(), [ 'POST', 'PUT', 'DELETE', 'PATCH' ]) ) {
|
||||||
|
if (! $this->getRequest()->hasHeader('X-CSRF-Token')) {
|
||||||
|
throw new CSRFMissingToken("A CSRF token must be provided to run non-safe methods.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::valid();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Form\Security;
|
||||||
|
|
||||||
|
use CSSLSJ\TransportScolaire\Api\{Entity};
|
||||||
|
use Lean\Api\Attribute\ContextField;
|
||||||
|
use Lean\Api\Lib\FormContext;
|
||||||
|
|
||||||
|
#[ContextField(description: "")]
|
||||||
|
class RequestLogContext extends FormContext
|
||||||
|
{
|
||||||
|
#[ContextField]
|
||||||
|
public ? int $user_id;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public string $method;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public string $endpoint;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public string $ipv4;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public string $ipv6;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public array $request_headers;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public array $request_body;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public int $status_code;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public array $response_headers;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public string $response_body;
|
||||||
|
|
||||||
|
#[ContextField]
|
||||||
|
public float $duration;
|
||||||
|
|
||||||
|
public function valid(? \Lean\Api\Entity\Security\ApiRequestLog $requestLog = null): bool
|
||||||
|
{
|
||||||
|
return parent::valid();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Form\Security;
|
||||||
|
|
||||||
|
use Lean\Api\{Attribute\Action, Entity};
|
||||||
|
use Lean\Api\Factory\MessageFactoryInterface;
|
||||||
|
use Lean\LanguageHandler;
|
||||||
|
use Picea\Ui\Method\FormContextInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
class SaveActionLog extends \Lean\Api\Form\Save
|
||||||
|
{
|
||||||
|
protected string $contextClass = ActionLogContext::class;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
protected LanguageHandler $languageHandler,
|
||||||
|
protected MessageFactoryInterface $message,
|
||||||
|
protected Entity\Security\ApiActionLog $entity,
|
||||||
|
protected UserInterface $user,
|
||||||
|
)
|
||||||
|
{
|
||||||
|
parent::__construct($this->languageHandler, $this->message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function initialize(FormContextInterface|ActionLogContext $context): void
|
||||||
|
{
|
||||||
|
parent::initialize($context);
|
||||||
|
|
||||||
|
if ($this->user->isLoaded()) {
|
||||||
|
$context->user_id = $this->user->id;
|
||||||
|
$context->user_type = $this->user::class;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Form\Security;
|
||||||
|
|
||||||
|
use Lean\Api\{Entity};
|
||||||
|
use Lean\Api\Factory\MessageFactoryInterface;
|
||||||
|
use Lean\LanguageHandler;
|
||||||
|
use Picea\Ui\Method\FormContextInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Ulmus\User\Entity\UserInterface;
|
||||||
|
|
||||||
|
class SaveRequestLog extends \Lean\Api\Form\Save
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
protected LanguageHandler $languageHandler,
|
||||||
|
protected MessageFactoryInterface $message,
|
||||||
|
protected Entity\Security\ApiRequestLog $entity,
|
||||||
|
protected ResponseInterface $response,
|
||||||
|
protected UserInterface $user,
|
||||||
|
)
|
||||||
|
{
|
||||||
|
parent::__construct($this->languageHandler, $this->message);
|
||||||
|
|
||||||
|
$this->contextClass = RequestLogContext::class;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function initialize(FormContextInterface|RequestLogContext $context): void
|
||||||
|
{
|
||||||
|
parent::initialize($context);
|
||||||
|
|
||||||
|
$request = $context->getRequest();
|
||||||
|
|
||||||
|
$context->user_id = $this->user->isLoaded() ? $this->user->id : null;
|
||||||
|
$context->method = $request->getAttribute('api:request-log-original-method');
|
||||||
|
$context->endpoint = $request->getUri();
|
||||||
|
$context->ipv4 = $request->getHeaderLine('x-forwarded-for') ?: $request->getServerParams()['REMOTE_ADDR'];
|
||||||
|
$context->request_headers = array_replace($request->getHeaders(), [ 'authorization' => "{removed}", ]);
|
||||||
|
$context->request_body = $request->getBody()->getSize() > 100000 ? "{too large}" : $request->getParsedBody();
|
||||||
|
$context->status_code = $this->response->getStatusCode();
|
||||||
|
$context->response_headers = $this->response->getHeaders();
|
||||||
|
$context->response_body = substr($this->response->getBody()->getContents(), 0, 100000);
|
||||||
|
$context->duration = microtime(true) - $request->getServerParams()['REQUEST_TIME'];
|
||||||
|
}
|
||||||
|
}
|
||||||
+40
-26
@@ -21,35 +21,31 @@ trait LeanApiTrait
|
|||||||
protected ContainerInterface $container;
|
protected ContainerInterface $container;
|
||||||
|
|
||||||
#[Ignore]
|
#[Ignore]
|
||||||
public function renderMarkdown(string $filepath, array $entities = [], array $forms = [], int $code = 200, array $headers = []) : ResponseInterface
|
public function renderMarkdown(string $filepath, array $entities = [], array $forms = [], int $code = 200, array $headers = []): ResponseInterface
|
||||||
{
|
{
|
||||||
if ( ! class_exists(CommonMarkConverter::class)) {
|
if (!class_exists(CommonMarkConverter::class)) {
|
||||||
throw new \BadFunctionCallException("League\CommonMark seems to be missing, please install dependency before trying to render Markdown content");
|
throw new \BadFunctionCallException("League\CommonMark seems to be missing, please install dependency before trying to render Markdown content");
|
||||||
}
|
}
|
||||||
|
|
||||||
$markdown = ( new CommonMarkConverter() )->convert(file_get_contents($filepath))->getContent();
|
$markdown = (new CommonMarkConverter())->convert(file_get_contents($filepath))->getContent();
|
||||||
|
|
||||||
if (str_contains($markdown, '{route:descriptor}'))
|
if (str_contains($markdown, '{route:descriptor}')) {
|
||||||
{
|
|
||||||
$markdown = str_replace('{route:descriptor}', $this->renderRawView('lean-api/route_descriptor', [
|
$markdown = str_replace('{route:descriptor}', $this->renderRawView('lean-api/route_descriptor', [
|
||||||
'routes' => (new RouteDescriptor($this, $this->picea->compiler->getExtensionFromToken('url'), $this->container))->getRoutes()
|
'routes' => (new RouteDescriptor($this, $this->picea->compiler->getExtensionFromToken('url'), $this->container))->getRoutes()
|
||||||
]), $markdown);
|
]), $markdown);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (str_contains($markdown, '{request:debugger}'))
|
if (str_contains($markdown, '{request:debugger}')) {
|
||||||
{
|
|
||||||
$markdown = str_replace('{request:debugger}', $this->renderRawView('lean-api/request_debugger', []), $markdown);
|
$markdown = str_replace('{request:debugger}', $this->renderRawView('lean-api/request_debugger', []), $markdown);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (str_contains($markdown, '{entity:descriptor}'))
|
if (str_contains($markdown, '{entity:descriptor}')) {
|
||||||
{
|
|
||||||
$markdown = str_replace('{entity:descriptor}', $this->renderRawView('lean-api/entity_descriptor', [
|
$markdown = str_replace('{entity:descriptor}', $this->renderRawView('lean-api/entity_descriptor', [
|
||||||
'entities' => (new EntityDescriptor())->getEntities(... $entities)
|
'entities' => (new EntityDescriptor())->getEntities(... $entities)
|
||||||
]), $markdown);
|
]), $markdown);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (str_contains($markdown, '{form:descriptor}'))
|
if (str_contains($markdown, '{form:descriptor}')) {
|
||||||
{
|
|
||||||
$markdown = str_replace('{form:descriptor}', $this->renderRawView('lean-api/form_descriptor', [
|
$markdown = str_replace('{form:descriptor}', $this->renderRawView('lean-api/form_descriptor', [
|
||||||
'forms' => (new FormDescriptor())->getForms(... $forms)
|
'forms' => (new FormDescriptor())->getForms(... $forms)
|
||||||
]), $markdown);
|
]), $markdown);
|
||||||
@@ -59,7 +55,7 @@ trait LeanApiTrait
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[Ignore]
|
#[Ignore]
|
||||||
protected function output(\JsonSerializable|array $data, int $count) : ResponseInterface
|
protected function output(\JsonSerializable|array $data, int $count): ResponseInterface
|
||||||
{
|
{
|
||||||
return $this->renderJson([
|
return $this->renderJson([
|
||||||
'data' => $data,
|
'data' => $data,
|
||||||
@@ -68,18 +64,18 @@ trait LeanApiTrait
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[Ignore]
|
#[Ignore]
|
||||||
protected function outputSearchResult(ApiSearchRequestInterface $apiSearchRequest) : ResponseInterface
|
protected function outputSearchResult(ApiSearchRequestInterface $apiSearchRequest): ResponseInterface
|
||||||
{
|
{
|
||||||
return $this->output($apiSearchRequest->getResult(), $apiSearchRequest->getSearch()->count);
|
return $this->output($apiSearchRequest->getResult(), $apiSearchRequest->getSearch()->count);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[Ignore]
|
#[Ignore]
|
||||||
protected function searchEntityFromRequest(ServerRequestInterface $request, string $entityType, ? string $resultKey = null) : ServerRequestInterface
|
protected function searchEntityFromRequest(ServerRequestInterface $request, string $entityType, ?string $resultKey = null): ServerRequestInterface
|
||||||
{
|
{
|
||||||
$search = $entityType::searchRequest()->fromRequest($request);
|
$search = $entityType::searchRequest()->fromRequest($request);
|
||||||
$entity = $entityType::repository()->filterServerRequest($search)->loadOne() ?? false;
|
$entity = $entityType::repository()->filterServerRequest($search, false)->loadOne() ?? false;
|
||||||
|
|
||||||
if (! $entity ) {
|
if (!$entity) {
|
||||||
throw new \InvalidArgumentException(sprintf("L'entré pour l'entité demandé (%s) est introuvable avec le ou les arguments fournis '%s'", $entityType, json_encode($request->getAttributes(), \JSON_PARTIAL_OUTPUT_ON_ERROR)));
|
throw new \InvalidArgumentException(sprintf("L'entré pour l'entité demandé (%s) est introuvable avec le ou les arguments fournis '%s'", $entityType, json_encode($request->getAttributes(), \JSON_PARTIAL_OUTPUT_ON_ERROR)));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -87,11 +83,17 @@ trait LeanApiTrait
|
|||||||
$request = $request->withAttribute("lean.searchRequest", $this->searchEntityResult());
|
$request = $request->withAttribute("lean.searchRequest", $this->searchEntityResult());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($request->getAttribute('lean-api.security-action:context')) {
|
||||||
|
$request->getAttribute('lean-api.security-action:context')->attachEntity($entity);
|
||||||
|
}
|
||||||
|
|
||||||
$request->getAttribute("lean.searchRequest")[$resultKey ?: $entityType] = new class($search, $entity) implements ApiSearchRequestInterface {
|
$request->getAttribute("lean.searchRequest")[$resultKey ?: $entityType] = new class($search, $entity) implements ApiSearchRequestInterface {
|
||||||
public function __construct(
|
public function __construct(
|
||||||
public readonly SearchRequestInterface $search,
|
public readonly SearchRequestInterface $search,
|
||||||
public readonly EntityInterface $entity,
|
public readonly EntityInterface $entity,
|
||||||
) {}
|
)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
public function getSearch(): SearchRequestInterface
|
public function getSearch(): SearchRequestInterface
|
||||||
{
|
{
|
||||||
@@ -108,12 +110,12 @@ trait LeanApiTrait
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[Ignore]
|
#[Ignore]
|
||||||
protected function searchEntitiesFromRequest(ServerRequestInterface $request, string $entityType, ? string $resultKey = null) : ServerRequestInterface
|
protected function searchEntitiesFromRequest(ServerRequestInterface $request, string $entityType, ?string $resultKey = null, bool $count = true): ServerRequestInterface
|
||||||
{
|
{
|
||||||
$search = $entityType::searchRequest()->fromRequest($request);
|
$search = $entityType::searchRequest()->fromRequest($request);
|
||||||
$entity = $entityType::repository()->filterServerRequest($search)->loadAll();
|
$entity = $entityType::repository()->filterServerRequest($search, $count)->loadAll();
|
||||||
|
|
||||||
if (! $entity ) {
|
if (!$entity) {
|
||||||
throw new \InvalidArgumentException(sprintf("L'entré pour l'entité demandé (%s) est introuvable avec le ou les arguments fournis '%s'", $entityType, json_encode($request->getAttributes())));
|
throw new \InvalidArgumentException(sprintf("L'entré pour l'entité demandé (%s) est introuvable avec le ou les arguments fournis '%s'", $entityType, json_encode($request->getAttributes())));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,8 +126,10 @@ trait LeanApiTrait
|
|||||||
$request->getAttribute("lean.searchRequest")[$resultKey ?: $entityType] = new class($search, $entity) implements ApiSearchRequestInterface {
|
$request->getAttribute("lean.searchRequest")[$resultKey ?: $entityType] = new class($search, $entity) implements ApiSearchRequestInterface {
|
||||||
public function __construct(
|
public function __construct(
|
||||||
public readonly SearchRequestInterface $search,
|
public readonly SearchRequestInterface $search,
|
||||||
public readonly EntityCollection $collection,
|
public readonly EntityCollection $collection,
|
||||||
) {}
|
)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
public function getSearch(): SearchRequestInterface
|
public function getSearch(): SearchRequestInterface
|
||||||
{
|
{
|
||||||
@@ -142,8 +146,9 @@ trait LeanApiTrait
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[Ignore]
|
#[Ignore]
|
||||||
protected function searchEntityResult() :\ArrayObject {
|
protected function searchEntityResult(): \ArrayObject
|
||||||
return new class()extends \ArrayObject implements ApiSearchRequestInterface {
|
{
|
||||||
|
return new class() extends \ArrayObject implements ApiSearchRequestInterface {
|
||||||
|
|
||||||
public function getSearch(): SearchRequestInterface
|
public function getSearch(): SearchRequestInterface
|
||||||
{
|
{
|
||||||
@@ -154,7 +159,8 @@ trait LeanApiTrait
|
|||||||
return $this[array_key_last($this->getArrayCopy())]->getSearch();
|
return $this[array_key_last($this->getArrayCopy())]->getSearch();
|
||||||
}
|
}
|
||||||
|
|
||||||
public function getResult() : EntityInterface|EntityCollection {
|
public function getResult(): EntityInterface|EntityCollection
|
||||||
|
{
|
||||||
if ($this->count() !== 1) {
|
if ($this->count() !== 1) {
|
||||||
throw new \LogicException("Search results contains more than one results. Impossible to continue without precising which one you needs.");
|
throw new \LogicException("Search results contains more than one results. Impossible to continue without precising which one you needs.");
|
||||||
}
|
}
|
||||||
@@ -163,4 +169,12 @@ trait LeanApiTrait
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[Ignore]
|
||||||
|
protected function attachActionEntity(ServerRequestInterface $request, EntityInterface $entity): void
|
||||||
|
{
|
||||||
|
if ($request->getAttribute('lean-api.security-action:attribute')) {
|
||||||
|
$request->getAttribute('lean-api.security-action:context')->attachEntity($entity);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,9 @@
|
|||||||
|
|
||||||
namespace Lean\Api\Lib;
|
namespace Lean\Api\Lib;
|
||||||
|
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use Lean\Api\Factory\LeanApiFormFactoryInterface;
|
||||||
|
use Lean\Api\Factory\LeanApiEntityFactory;
|
||||||
use Notes\Route\Attribute\Object\Route;
|
use Notes\Route\Attribute\Object\Route;
|
||||||
|
|
||||||
#[Route(method: ['GET', 'POST', ])]
|
#[Route(method: ['GET', 'POST', ])]
|
||||||
@@ -10,4 +13,10 @@ trait ControllerTrait
|
|||||||
use \Lean\ControllerTrait, \Lean\Api\LeanApiTrait {
|
use \Lean\ControllerTrait, \Lean\Api\LeanApiTrait {
|
||||||
\Lean\Api\LeanApiTrait::renderMarkdown insteadof \Lean\ControllerTrait;
|
\Lean\Api\LeanApiTrait::renderMarkdown insteadof \Lean\ControllerTrait;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected LeanApiFormFactoryInterface $leanApiFormFactory;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected LeanApiEntityFactory $leanApiEntityFactory;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Lib;
|
||||||
|
|
||||||
|
use Lean\Api\Factory\MessageFactoryInterface;
|
||||||
|
use Lean\LanguageHandler;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Ulmus\Entity\EntityInterface;
|
||||||
|
|
||||||
|
class DeleteFormContext extends FormContext
|
||||||
|
{
|
||||||
|
public function valid(? EntityInterface $entity = null) : bool
|
||||||
|
{
|
||||||
|
if ( $entity === null ) {
|
||||||
|
$this->pushErrorMessage('lean.api.form.delete.error.entity');
|
||||||
|
}
|
||||||
|
|
||||||
|
return parent::valid();
|
||||||
|
}
|
||||||
|
}
|
||||||
+28
-14
@@ -11,37 +11,38 @@ class RenderCORS
|
|||||||
{
|
{
|
||||||
public function __construct(
|
public function __construct(
|
||||||
protected ServerRequestInterface $request,
|
protected ServerRequestInterface $request,
|
||||||
public string|array $origin = "http://localhost,https://localhost",
|
public string|array $origin = [ "http://localhost", "https://localhost" ],
|
||||||
public bool $allowCredentials = true,
|
public bool $allowCredentials = true,
|
||||||
public string|array $methods = [ "GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", ],
|
public string|array $methods = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS",],
|
||||||
public string|array $headers = [ "Content-Type", "Authorization", "X-Requested-With" ],
|
public string|array $headers = ["Content-Type", "Authorization", "X-Requested-With", "X-CSRF-Token"],
|
||||||
) {
|
) {
|
||||||
if (is_string($this->origin)) {
|
if (is_string($origin)) {
|
||||||
$this->origin = explode(',', $this->origin);
|
$this->origin = explode(',', $this->origin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public function renderHeader(ServerRequestInterface $request) : void
|
public function renderHeader(ServerRequestInterface $request): void
|
||||||
{
|
{
|
||||||
$matched = $this->matchOrigin($this->request->getServerParams()['HTTP_ORIGIN'] ?? null, $this->origin);
|
$matched = $this->matchOrigin($this->getOrigin($request), $this->origin);
|
||||||
|
|
||||||
if (! $matched) {
|
if (!$matched) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
var_dump($matched);die();
|
||||||
|
|
||||||
$render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e));
|
$render = fn(string|array $e) => is_string($e) ? $e : sprintf('%s', implode(', ', $e));
|
||||||
|
|
||||||
header('Access-Control-Allow-Origin: ' . $matched);
|
header(sprintf('Access-Control-Allow-Origin: %s', $matched));
|
||||||
header(sprintf('Access-Control-Allow-Methods: %s', $render($this->methods)));
|
header(sprintf('Access-Control-Allow-Methods: %s', $render($this->methods)));
|
||||||
header(sprintf('Access-Control-Allow-Headers: %s', $render($this->headers)));
|
header(sprintf('Access-Control-Allow-Headers: %s', $render($this->headers)));
|
||||||
header('Access-Control-Allow-Credentials: ' . ($this->allowCredentials ? 'true' : 'false'));
|
header(sprintf('Access-Control-Allow-Credentials: %s', $this->allowCredentials ? 'true' : 'false'));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function fromResponse(ResponseInterface $response, bool $emptyResponse = false) : ResponseInterface
|
public function fromResponse(ResponseInterface $response, bool $emptyResponse = false): ResponseInterface
|
||||||
{
|
{
|
||||||
$matched = $this->matchOrigin($this->request->getServerParams()['HTTP_ORIGIN'] ?? null, $this->origin);
|
$matched = $this->matchOrigin($this->getOrigin($this->request), $this->origin);
|
||||||
|
|
||||||
if (! $matched) {
|
if (!$matched) {
|
||||||
return $response;
|
return $response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +67,7 @@ class RenderCORS
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach ((array) $allowList as $rule) {
|
foreach ((array)$allowList as $rule) {
|
||||||
if ($rule === '*') {
|
if ($rule === '*') {
|
||||||
return '*';
|
return '*';
|
||||||
}
|
}
|
||||||
@@ -89,5 +90,18 @@ class RenderCORS
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
protected function getOrigin(ServerRequestInterface $request): string
|
||||||
|
{
|
||||||
|
$server = $request->getServerParams();
|
||||||
|
|
||||||
|
if (isset($server['HTTP_ORIGIN'])) {
|
||||||
|
return $server['HTTP_ORIGIN'];
|
||||||
|
}
|
||||||
|
|
||||||
|
$protocol = $server['HTTP_X_FORWARDED_PROTO'] ?? ((!empty($server['HTTPS']) && $server['HTTPS'] !== 'off') ? 'https' : 'http');
|
||||||
|
$host = $server['HTTP_X_FORWARDED_HOST'] ?? $server['HTTP_HOST'] ?? $server['SERVER_NAME'];
|
||||||
|
|
||||||
|
return $protocol . '://' . $host;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
namespace Lean\Api\Middleware;
|
namespace Lean\Api\Middleware;
|
||||||
|
|
||||||
|
use DI\Attribute\Inject;
|
||||||
use Laminas\Diactoros\Response\JsonResponse;
|
use Laminas\Diactoros\Response\JsonResponse;
|
||||||
use Lean\Factory\HttpFactory;
|
use Lean\Factory\HttpFactory;
|
||||||
use Picea\Ui\Method\FormHandler;
|
use Picea\Ui\Method\FormHandler;
|
||||||
@@ -10,15 +11,12 @@ use Psr\Http\Message\ResponseInterface;
|
|||||||
use Psr\Http\Message\ServerRequestInterface;
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
use Lean\Api\{Controller\Debug, Factory\DebugFormFactoryInterface, Form, Entity};
|
use Lean\Api\{Factory\LeanApiFormFactoryInterface, Form, Entity};
|
||||||
|
|
||||||
class ApiRenderer implements MiddlewareInterface {
|
class ApiRenderer implements MiddlewareInterface {
|
||||||
|
|
||||||
public function __construct(
|
#[Inject]
|
||||||
protected ContainerInterface $container,
|
protected LeanApiFormFactoryInterface $leanApiFormFactory;
|
||||||
# protected DebugFormFactoryInterface $debugFormFactory,
|
|
||||||
) {
|
|
||||||
}
|
|
||||||
|
|
||||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
||||||
{
|
{
|
||||||
@@ -27,7 +25,7 @@ class ApiRenderer implements MiddlewareInterface {
|
|||||||
}
|
}
|
||||||
catch(\Throwable $ex) {
|
catch(\Throwable $ex) {
|
||||||
if (static::awaitingJson($request)) {
|
if (static::awaitingJson($request)) {
|
||||||
$this->saveError($request, $ex);
|
# $this->saveError($request, $ex);
|
||||||
|
|
||||||
return HttpFactory::createJsonResponse([
|
return HttpFactory::createJsonResponse([
|
||||||
'status' => 'failed',
|
'status' => 'failed',
|
||||||
@@ -36,6 +34,7 @@ class ApiRenderer implements MiddlewareInterface {
|
|||||||
# 'error_id' => $errorId,
|
# 'error_id' => $errorId,
|
||||||
'message' => $ex->getMessage(),
|
'message' => $ex->getMessage(),
|
||||||
] + (getenv('DEBUG') ? [
|
] + (getenv('DEBUG') ? [
|
||||||
|
'type' => $ex::class,
|
||||||
'file' => $ex->getFile(),
|
'file' => $ex->getFile(),
|
||||||
'line' => $ex->getLine(),
|
'line' => $ex->getLine(),
|
||||||
'code' => $ex->getCode(),
|
'code' => $ex->getCode(),
|
||||||
@@ -66,17 +65,17 @@ class ApiRenderer implements MiddlewareInterface {
|
|||||||
if ($debugFormFactory = $this->container->get(DebugFormFactoryInterface::class)) {
|
if ($debugFormFactory = $this->container->get(DebugFormFactoryInterface::class)) {
|
||||||
$request = $request->withMethod('PUT')->withParsedBody([]);
|
$request = $request->withMethod('PUT')->withParsedBody([]);
|
||||||
|
|
||||||
$context = $debugFormFactory->errorSaveContext($request);
|
$context = $this->leanApiFormFactory->errorSaveContext($request);
|
||||||
|
|
||||||
$context->sets([
|
$context->sets([
|
||||||
'message' => $exception->getMessage(),
|
'message' => $exception->getMessage(),
|
||||||
'code' => $exception->getCode(),
|
'code' => $exception->getCode(),
|
||||||
'file' => $exception->getFile(),
|
'file' => $exception->getFile(),
|
||||||
'line' => $exception->getLine(),
|
'line' => $exception->getLine(),
|
||||||
'trace' => $exception->getTrace(),
|
'trace' => $exception->getTrace(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$form = $debugFormFactory->errorSave($entity = new Entity\Error());
|
$form = $this->leanApiFormFactory->errorSave($entity = new Entity\Error());
|
||||||
|
|
||||||
new FormHandler($request, $form, $context);
|
new FormHandler($request, $form, $context);
|
||||||
}
|
}
|
||||||
@@ -96,7 +95,6 @@ class ApiRenderer implements MiddlewareInterface {
|
|||||||
$item = static::encodeHtml($item);
|
$item = static::encodeHtml($item);
|
||||||
}
|
}
|
||||||
elseif (is_string($item)) {
|
elseif (is_string($item)) {
|
||||||
dump($item);
|
|
||||||
$item = htmlspecialchars($item);
|
$item = htmlspecialchars($item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ use Psr\Http\Message\ResponseInterface;
|
|||||||
use Psr\Http\Message\ServerRequestInterface;
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
use Psr\Http\Server\MiddlewareInterface;
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
use Psr\Http\Server\RequestHandlerInterface;
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
use Lean\Api\{ Entity};
|
||||||
|
|
||||||
class CORS implements MiddlewareInterface
|
class CORS implements MiddlewareInterface
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,87 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Middleware\Security;
|
||||||
|
|
||||||
|
use Lean\Api\Controller\Security\ActionLog;
|
||||||
|
use Lean\Api\Factory\LeanApiFormFactoryInterface;
|
||||||
|
use Lean\Api\Form;
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use Lean\Event\RoutingMapRoutes;
|
||||||
|
use Lean\Routing;
|
||||||
|
use Mcnd\Event\EventManager;
|
||||||
|
use Notes\ObjectReflection;
|
||||||
|
use Notes\ObjectResolver;
|
||||||
|
use Notes\Route\Attribute\Method\Route;
|
||||||
|
use Picea\Ui\Method\FormContextInterface;
|
||||||
|
use Psr\Container\ContainerInterface;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
|
||||||
|
class ActionLogMiddleware implements MiddlewareInterface {
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected readonly LeanApiFormFactoryInterface $leanApiFormFactory;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected readonly ActionLog $actionLogController;
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected readonly EventManager $eventManager;
|
||||||
|
|
||||||
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
||||||
|
{
|
||||||
|
$eventHandler = $this->createEventHandler($request);
|
||||||
|
|
||||||
|
$this->eventManager->eventRegister($eventHandler);
|
||||||
|
|
||||||
|
$handler = $handler->handle($request);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ($handler->getStatusCode() < 300) {
|
||||||
|
if (isset($eventHandler->request)) {
|
||||||
|
if ($eventHandler->request->getAttribute('lean-api.security-action:attribute')) {
|
||||||
|
$this->actionLogController->add($eventHandler->request, []);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(\Throwable $ex) {
|
||||||
|
if (getenv('DEBUG')) {
|
||||||
|
throw $ex;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected function createEventHandler(ServerRequestInterface $request) : object
|
||||||
|
{
|
||||||
|
return new class($this->leanApiFormFactory->securityActionLogSaveContext($request)) implements RoutingMapRoutes {
|
||||||
|
|
||||||
|
public readonly ServerRequestInterface $request;
|
||||||
|
|
||||||
|
public function __construct(
|
||||||
|
public readonly Form\Security\ActionLogContext $context,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function execute(Routing $routing, ContainerInterface $container, ServerRequestInterface &$request, Route $attribute): void
|
||||||
|
{
|
||||||
|
if (in_array($request->getMethod(), [ 'PATCH', 'POST', 'PUT', 'DELETE' ])) {
|
||||||
|
$objectReflection = ObjectReflection::fromClass($attribute->class, null)->reflectClass();
|
||||||
|
$actionLog = $objectReflection->methods[$attribute->classMethod]->getAttribute(\Lean\Api\Attribute\Security\ActionLog::class);
|
||||||
|
|
||||||
|
if ($actionLog) {
|
||||||
|
$this->context->event = $attribute->name;
|
||||||
|
$this->context->method = $request->getMethod();
|
||||||
|
|
||||||
|
$request = $this->request = $request
|
||||||
|
->withAttribute('lean-api.security-action:attribute', $actionLog->object)
|
||||||
|
->withAttribute('lean-api.security-action:context', $this->context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Middleware\Security;
|
||||||
|
|
||||||
|
use Lean\Api\Lib\RenderCORS;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
use Lean\Api\{ Entity};
|
||||||
|
|
||||||
|
class CORSMiddleware implements MiddlewareInterface
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
protected RenderCORS $cors,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
||||||
|
{
|
||||||
|
return $this->cors->fromResponse($handler->handle($request));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Middleware\Security;
|
||||||
|
|
||||||
|
use Lean\Api\Controller\Security\CSRF;
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use Lean\Api\Exception\{ CSRFMissingToken, CSRFInvalidToken };
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
|
||||||
|
class CSRFMiddleware implements MiddlewareInterface {
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected CSRF $csrfController;
|
||||||
|
|
||||||
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
||||||
|
{
|
||||||
|
if ( str_contains($request->getHeaderLine('Content-Type'), 'json') && ! getenv('LEAN_API_DISABLE_CSRF')) {
|
||||||
|
$this->csrfController->validate($request, ['token' => $request->getHeaderLine('X-CSRF-Token')]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return $handler->handle($request);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Middleware\Security;
|
||||||
|
|
||||||
|
use Lean\Api\Controller\Security\RequestLog;
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
|
||||||
|
class RequestLogMiddleware implements MiddlewareInterface {
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected RequestLog $requestLogController;
|
||||||
|
|
||||||
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
||||||
|
{
|
||||||
|
$response = $handler->handle($request);
|
||||||
|
|
||||||
|
# Skip 404
|
||||||
|
if ($response->getStatusCode() < 400 || $response->getStatusCode() >= 500) {
|
||||||
|
try {
|
||||||
|
if ( str_contains($response->getHeaderLine('Content-Type'), 'json') ) {
|
||||||
|
$this->requestLogController->add($request, [ 'response' => $response ]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(\Throwable $ex) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Lean\Api\Middleware;
|
||||||
|
|
||||||
|
use Lean\Api\Controller\Security\RequestLog;
|
||||||
|
use DI\Attribute\Inject;
|
||||||
|
use Psr\Http\Message\ResponseInterface;
|
||||||
|
use Psr\Http\Message\ServerRequestInterface;
|
||||||
|
use Psr\Http\Server\MiddlewareInterface;
|
||||||
|
use Psr\Http\Server\RequestHandlerInterface;
|
||||||
|
|
||||||
|
#[\Deprecated]
|
||||||
|
class SecurityMiddleware implements MiddlewareInterface {
|
||||||
|
|
||||||
|
#[Inject]
|
||||||
|
protected RequestLog $requestLogController;
|
||||||
|
|
||||||
|
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
|
||||||
|
{
|
||||||
|
$response = $handler->handle($request);
|
||||||
|
|
||||||
|
try {
|
||||||
|
if ( str_contains($response->getHeaderLine('Content-Type'), 'json') ) {
|
||||||
|
$this->requestLogController->add($request, [ 'response' => $response ]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch(\Throwable $ex) {}
|
||||||
|
|
||||||
|
return $response;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -156,31 +156,30 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
launchRequest(requestMethod, input.value, editor.getValue())
|
launchRequest(requestMethod, input.value, editor.getValue())
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
responseHead.querySelector('.response-code').innerText = response.status;
|
responseHead.querySelector('.response-code').innerText = response.status;
|
||||||
responseHead.querySelector('.response-message').innerText = response.statusText;
|
responseHead.querySelector('.response-message').innerText = response.statusText;
|
||||||
|
|
||||||
aceMode = parseContentType(response);
|
aceMode = parseContentType(response);
|
||||||
|
|
||||||
return response.text();
|
return response.text();
|
||||||
})
|
})
|
||||||
.then(body => {
|
.then(body => {
|
||||||
if (aceMode === "json") {
|
if (aceMode === "json") {
|
||||||
body = JSON.stringify(JSON.parse(body), null, 2);
|
body = JSON.stringify(JSON.parse(body), null, 2);
|
||||||
|
responseEditorElement.innerHTML = DOMEncode(body);
|
||||||
|
}
|
||||||
|
else if (aceMode === "html") {
|
||||||
|
let b64 = btoa(unescape(encodeURIComponent(body)));
|
||||||
|
|
||||||
responseEditorElement.innerHTML = DOMEncode(body);
|
responseEditorElement.innerHTML = `<iframe style='width:100%; min-height:60vh' src="data:text/html;base64,${b64}"></iframe>`
|
||||||
}
|
}
|
||||||
else if (aceMode === "html") {
|
else {
|
||||||
let b64 = btoa(unescape(encodeURIComponent(body)));
|
responseEditorElement.innerText = body;
|
||||||
|
}
|
||||||
|
|
||||||
responseEditorElement.innerHTML = `<iframe style='width:100%; min-height:60vh' src="data:text/html;base64,${b64}"></iframe>`
|
formatResponse("ace/mode/" + aceMode);
|
||||||
}
|
}).finally(() => requestDebugger.classList.remove("loading"));
|
||||||
else {
|
|
||||||
responseEditorElement.innerText = body;
|
|
||||||
}
|
|
||||||
|
|
||||||
formatResponse("ace/mode/" + aceMode);
|
|
||||||
}).finally(() => requestDebugger.classList.remove("loading"));
|
|
||||||
|
|
||||||
responseResponse.classList.toggle('hide', false);
|
responseResponse.classList.toggle('hide', false);
|
||||||
});
|
});
|
||||||
@@ -197,13 +196,41 @@
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
async function fetchCSRFToken() {
|
||||||
|
let headers = {
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
};
|
||||||
|
|
||||||
|
if (token.value) {
|
||||||
|
headers['X-CSRF-Token'] = token.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseData = {
|
||||||
|
method: "GET",
|
||||||
|
mode: "cors",
|
||||||
|
cache: "no-cache",
|
||||||
|
credentials: "same-origin",
|
||||||
|
headers: headers,
|
||||||
|
redirect: "follow",
|
||||||
|
referrerPolicy: "no-referrer"
|
||||||
|
};
|
||||||
|
|
||||||
|
let fetching = await fetch("{% route 'lean.api:security-csrf-generate' %}", responseData).then(j => j.json())
|
||||||
|
|
||||||
|
if (fetching.data.token === undefined) {
|
||||||
|
throw new Error("An error occured trying to fetch a CSRF token.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return fetching.data.token;
|
||||||
|
}
|
||||||
|
|
||||||
async function launchRequest(method = "POST", url = "", body = "{}") {
|
async function launchRequest(method = "POST", url = "", body = "{}") {
|
||||||
let headers = {
|
let headers = {
|
||||||
"Content-Type": "application/json"
|
"Content-Type": "application/json"
|
||||||
};
|
};
|
||||||
|
|
||||||
if (token.value) {
|
if (token.value) {
|
||||||
headers['Authorization'] = `Bearer ${token.value}`;
|
headers['X-CSRF-Token'] = token.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
method = method.toUpperCase();
|
method = method.toUpperCase();
|
||||||
@@ -212,14 +239,15 @@
|
|||||||
method: method,
|
method: method,
|
||||||
mode: "cors",
|
mode: "cors",
|
||||||
cache: "no-cache",
|
cache: "no-cache",
|
||||||
credentials: headers.Authorization ? "omit" : "same-origin",
|
credentials: "same-origin",
|
||||||
headers: headers,
|
headers: headers,
|
||||||
redirect: "follow",
|
redirect: "follow",
|
||||||
referrerPolicy: "no-referrer"
|
referrerPolicy: "no-referrer"
|
||||||
};
|
};
|
||||||
|
|
||||||
if ( [ "HEAD", "GET" ].indexOf(method) === -1 ) {
|
if ( [ "HEAD", "GET", "OPTIONS", "TRACE", "CONNECT" ].indexOf(method) === -1 ) {
|
||||||
responseData.body = body;
|
responseData.body = body;
|
||||||
|
responseData.headers['X-CSRF-Token'] = await fetchCSRFToken();
|
||||||
}
|
}
|
||||||
|
|
||||||
requestDebugger.classList.add("loading");
|
requestDebugger.classList.add("loading");
|
||||||
|
|||||||
Reference in new issue
Block a user