I have a symfony application where I'd like to log every quest with ROLE_ADMIN
in the database. I've tried adding a new bundle, but I'm not really sure how that get's loaded in AppKernel.php
. Any guidance you could provide would be extremely helpful.
1 Answer
I would create an event listener on kernel.request
event and check if request comes from an user with ROLE_ADMIN
.
First create the service and inject security.authorization_checker
and doctrine.orm.entity_manager
:
admin_log_listener:
class: AppBundle\EventListener\AdminLogListener
arguments: [ "@security.authorization_checker", "@doctrine.orm.entity_manager" ]
tags:
- { name: kernel.event_listener, event: kernel.request }
Then create the event listener:
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
use Doctrine\ORM\EntityManager;
class AdminLogListener {
protected $authChecker;
protected $entityManager;
public function __construct(AuthorizationChecker $authChecker, EntityManager $entityManager)
{
$this->authChecker = $authChecker;
$this->entityManager = $entityManager;
}
public function onKernelRequest(GetResponseEvent $event)
{
if ($this->authChecker->isGranted('ROLE_ADMIN')) {
// Use $this->entityManager to send query or call a repository function
// Refer to http://www.doctrine-project.org/api/orm/2.5/class-Doctrine.ORM.EntityManager.html
}
}
}