OmarAguinaga OmarAguinaga - 5 months ago 13
PHP Question

Respond to a Symfony security annotation with something more than an error page

I want to implement a data log for attempts against my application. One of this will be when someone without the security rights wants to go to a certain page. For example a normal user trying to go to a url only avaiable for an administrator.

Symfony offers this security annotation:

/**
* @Security("has_role('ROLE_ADMIN')")
*/


And for now I use it to display an error page. But what I would like to do is to send the data to a database in case someone attempts to go in the admin only site recurrently (three or more times in less than a minute). The kind of data I will store is user, in case someone is logged in, IP, timestamp, among others. I already have a service that does the storing I just want to know if there is a way to know that someone is trying to access the page repeatedly without authorization and how to call my service in that case.

I have been looking all over the symfony documentation and couldn't find any information relevant to my problem. I would appreciate your help!

Thanks in advance.

SOLVED

I did what @ShiraNai7 told me to plus this in the service declaration in order to be able to use my other service. Thanks.

app.exception_listener:
class: InnoGames\Bundle\OfficeITBundle\EventListener\ExceptionListener
arguments: [@service_container]
tags:
- { name: kernel.event_listener, event: kernel.exception }

Answer

You could create a listner for the kernel.exception event and do your logging there.

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;

public function onKernelException(GetResponseForExceptionEvent $event)
{
    $exception = $event->getException();
    $request = $event->getRequest();

    // do your logging here
}

Also see Symfony docs - How to Create Event Listeners and Subscribers