src/EventListener/AuthenticationFailureListener.php line 21

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\RequestStack;
  4. use App\Manager\UserManager;
  5. use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
  6. use Symfony\Component\Security\Core\Exception\BadCredentialsException;
  7. class AuthenticationFailureListener 
  8. {
  9.     private $userManager;
  10.     private $request;
  11.     public function __constructUserManager $userManagerRequestStack $requestStack)
  12.     {
  13.         $this->request    $requestStack->getCurrentRequest();;
  14.         $this->userManager $userManager;
  15.     }
  16.     public function __invoke(AuthenticationFailureEvent $event){
  17.         if ($event->getAuthenticationException() instanceof BadCredentialsException){
  18.             $this->setFailedLogin();
  19.         } 
  20.     }
  21.     public function setFailedLogin() {
  22.         if (null !== $user $this->userManager->load($this->request->request->get('username')) ) {
  23.             $failedLogin  $user->getFailedLogin();
  24.             $attempts     $failedLogin[0] ?? 0// $failedLogin[0] : number of attempts
  25.             $now          date("Y-m-d H:i:s");
  26.             $lastAttempt  $failedLogin[1] ?? "";
  27.             if (empty($lastAttempt)) {
  28.                 $attempts $attempts ;
  29.                 if($attempts >= 6) {
  30.                     $lastAttempt $now;
  31.                     $attempts    0;
  32.                     $user->setLocked(true);
  33.                 }
  34.             } elseif ((round(abs(strtotime($now) - strtotime($lastAttempt)) / 60,2) > 30)  ) { //if date of last attempt depass the 30 min, increment number of attempts
  35.                 $attempts    1;
  36.                 $lastAttempt "";
  37.                 $user->setLocked(false);
  38.             }/* elseif (round(abs(strtotime($now) - strtotime($lastAttempt)) / 60,2) < 30)  {
  39.                 $attempts =  $attempts + 1;
  40.                 if ($attempts >= 6) {
  41.                     $lastAttempt = $now;
  42.                     $attempts    = 0;
  43.                     $this->setLocked(true);
  44.                 } 
  45.             }*/
  46.             $failedLogin[0]    = $attempts;
  47.             $failedLogin[1]    = $lastAttempt;
  48.             $user->setFailedLogin($failedLogin);
  49.             $this->userManager->save($user);
  50.        }
  51.     }
  52. }