Add TokenProcessor

This commit is contained in:
Dany Maillard 2016-12-25 20:27:49 +01:00
parent 9b8d96b845
commit 3763515cae
3 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,43 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Monolog\Processor;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
/**
* Adds the current security token to the log entry.
*
* @author Dany Maillard <danymaillard93b@gmail.com>
*/
class TokenProcessor
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function __invoke(array $records)
{
$records['extra']['token'] = null;
if (null !== $token = $this->tokenStorage->getToken()) {
$records['extra']['token'] = array(
'username' => $token->getUsername(),
'authenticated' => $token->isAuthenticated(),
'roles' => array_map(function ($role) { return $role->getRole(); }, $token->getRoles()),
);
}
return $records;
}
}

View File

@ -0,0 +1,42 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bridge\Monolog\Tests\Processor;
use PHPUnit\Framework\TestCase;
use Symfony\Bridge\Monolog\Processor\TokenProcessor;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
/**
* Tests the TokenProcessor.
*
* @author Dany Maillard <danymaillard93b@gmail.com>
*/
class TokenProcessorTest extends TestCase
{
public function testProcessor()
{
$token = new UsernamePasswordToken('user', 'password', 'provider', array('ROLE_USER'));
$tokenStorage = $this->getMockBuilder(TokenStorageInterface::class)->getMock();
$tokenStorage->method('getToken')->willReturn($token);
$processor = new TokenProcessor($tokenStorage);
$record = array('extra' => array());
$record = $processor($record);
$this->assertArrayHasKey('token', $record['extra']);
$this->assertEquals($token->getUsername(), $record['extra']['token']['username']);
$this->assertEquals($token->isAuthenticated(), $record['extra']['token']['authenticated']);
$roles = array_map(function ($role) { return $role->getRole(); }, $token->getRoles());
$this->assertEquals($roles, $record['extra']['token']['roles']);
}
}

View File

@ -23,6 +23,7 @@
"require-dev": {
"symfony/console": "~2.8|~3.0|~4.0",
"symfony/event-dispatcher": "~2.8|~3.0|~4.0",
"symfony/security-core": "~2.8|~3.0|~4.0",
"symfony/var-dumper": "~3.3|~4.0"
},
"conflict": {