77 lines
2.3 KiB
PHP
77 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Logging;
|
|
|
|
use App\Entity\User;
|
|
use Monolog\Attribute\AsMonologProcessor;
|
|
use Monolog\LogRecord;
|
|
use Symfony\Bundle\SecurityBundle\Security;
|
|
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
|
|
|
|
#[AsMonologProcessor]
|
|
class UserDataProcessor
|
|
{
|
|
/**
|
|
* The SAPI is injected rather than read from PHP_SAPI inside the processor so a test can
|
|
* exercise the web path: under PHPUnit php_sapi_name() is always "cli", which made
|
|
* everything below the check unreachable from every functional test.
|
|
*/
|
|
public function __construct(
|
|
private readonly Security $security,
|
|
private readonly string $sapi = \PHP_SAPI,
|
|
) {
|
|
}
|
|
|
|
public function __invoke(LogRecord $record): LogRecord
|
|
{
|
|
if (isset($record->extra['user'])) {
|
|
return $record;
|
|
}
|
|
|
|
if ('cli' === $this->sapi) {
|
|
$record->extra['user'] = [
|
|
'id' => null,
|
|
'username' => 'SYSTEM',
|
|
'role' => 'system',
|
|
];
|
|
|
|
return $record;
|
|
}
|
|
|
|
$user = $this->security->getUser();
|
|
|
|
if (null === $user) {
|
|
$record->extra['user'] = [
|
|
'id' => null,
|
|
'username' => 'ANONYMOUS',
|
|
'role' => 'public',
|
|
];
|
|
|
|
return $record;
|
|
}
|
|
|
|
// Check for switched or aliased users
|
|
$originalUser = null;
|
|
$token = $this->security->getToken();
|
|
if ($token instanceof SwitchUserToken) {
|
|
// User is currently switched to
|
|
$originalUser = $token->getOriginalToken()->getUser();
|
|
}
|
|
if (null !== $originalUser) {
|
|
$username = sprintf('%s (via %s)', $user->getUserIdentifier(), $originalUser->getUserIdentifier());
|
|
} else {
|
|
$username = $user->getUserIdentifier();
|
|
}
|
|
$record->extra['user'] = [
|
|
// Only a user table row has an id: the stateless "api" firewall resolves its shared
|
|
// key to an in-memory user, and calling getId() on that is a 500 on a request that
|
|
// had already stored its data.
|
|
'id' => $user instanceof User ? $user->getId() : null,
|
|
'username' => $username,
|
|
'roles' => $user->getRoles(),
|
|
];
|
|
|
|
return $record;
|
|
}
|
|
}
|