Ambu
Ambu

Reputation: 194

How do I create system logs during authentication?

I was following the guide here and implemented basic authentication system: https://symfony.com/doc/current/security.html

However, I would like to add system logs to my application. To be precise, I would like:

I know that I can put logs in my SecurityController, like this:

public function login(AuthenticationUtils $authenticationUtils, Request $request, EntityManagerInterface $em): Response
{
    // if ($this->getUser()) {
    //     return $this->redirectToRoute('target_path');
    // }

    $log = new Logs();
    $em->persist($log);

    $log->setAction('auth')
        ->setDate(new DateTime())
        ->setIp($request->getClientIp());

    $em->flush();

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();
    // last username entered by the user
    $lastUsername = $authenticationUtils->getLastUsername();

    return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
}

but it only gives me the information that someone was on the login page. What do I modify or add to get the other info?

Upvotes: 0

Views: 149

Answers (1)

Mesuti
Mesuti

Reputation: 908

I think this will be solve your problem.

You should do it via Symfony events. These 2 events triggering after failed/succeed login attempts: security.authentication.success and security.authentication.failure .

I will make an example for success and you can apply it for failure:

  1. Add this to your config/service.yml

    App\EventListener\SuccessLoginListener:
    tags:
        - { name: 'kernel.event_listener', event: 'security.authentication.success'}
    
  2. Then you can create the Listener and do it logging process in it

    namespace App\EventListener;
    
    use Doctrine\ORM\EntityManagerInterface;
    use Symfony\Component\Security\Http\Event\AuthenticationSuccessEvent;
    
    class SuccessLoginListener
    {
    private $em;
    
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
    
    public function onSecurityAuthenticationSuccess(AuthenticationSuccessEvent $event)
    {
    // TODO: Create your log entity at here.
    }
    }
    

Upvotes: 1

Related Questions