Add rules to prevent tracking of certain requests

This commit is contained in:
Daniel Siepmann 2020-02-13 12:26:43 +01:00
parent 27819c73ef
commit 6a2cd9bc50
Signed by: Daniel Siepmann
GPG key ID: 33D6629915560EF4
2 changed files with 42 additions and 8 deletions

View file

@ -27,6 +27,8 @@ 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 Symfony\Component\ExpressionLanguage\ExpressionLanguage;
use TYPO3\CMS\Core\Context\Context;
class Pageview implements MiddlewareInterface class Pageview implements MiddlewareInterface
{ {
@ -35,17 +37,41 @@ class Pageview implements MiddlewareInterface
*/ */
private $repository; private $repository;
public function __construct(Repository $repository) /**
* @var Context
*/
private $context;
/**
* @var string
*/
private $rule = '';
public function __construct(Repository $repository, Context $context, string $rule)
{ {
$this->repository = $repository; $this->repository = $repository;
$this->context = $context;
$this->rule = $rule;
} }
public function process( public function process(
ServerRequestInterface $request, ServerRequestInterface $request,
RequestHandlerInterface $handler RequestHandlerInterface $handler
): ResponseInterface { ): ResponseInterface {
if ($this->shouldTrack($request, $this->context)) {
$this->repository->add(Factory::fromRequest($request)); $this->repository->add(Factory::fromRequest($request));
}
return $handler->handle($request); return $handler->handle($request);
} }
private function shouldTrack(
ServerRequestInterface $request,
Context $context
): bool {
return (bool) (new ExpressionLanguage())->evaluate($this->rule, [
'request' => $request,
'context' => $context,
]);
}
} }

View file

@ -18,3 +18,11 @@ services:
public: true public: true
arguments: arguments:
- '@DanielSiepmann\DI\DatabaseConnection\Pageview' - '@DanielSiepmann\DI\DatabaseConnection\Pageview'
DanielSiepmann\Tracking\Middleware\Pageview:
public: true
arguments:
$rule: >
not (context.getAspect("backend.user").isLoggedIn())
and not (request.getHeader("User-Agent")[0] matches "/^Wget/")
and not (request.getHeader("User-Agent")[0] matches "/Googlebot|Bingbot|Slurp|DuckDuckBot|Baiduspider|YandexBot|Sogou|Exabot/")