<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\RequestStack;
use App\Manager\UserManager;
use Symfony\Component\Security\Core\Event\AuthenticationFailureEvent;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
class AuthenticationFailureListener
{
private $userManager;
private $request;
public function __construct( UserManager $userManager, RequestStack $requestStack)
{
$this->request = $requestStack->getCurrentRequest();;
$this->userManager = $userManager;
}
public function __invoke(AuthenticationFailureEvent $event){
if ($event->getAuthenticationException() instanceof BadCredentialsException){
$this->setFailedLogin();
}
}
public function setFailedLogin() {
if (null !== $user = $this->userManager->load($this->request->request->get('username')) ) {
$failedLogin = $user->getFailedLogin();
$attempts = $failedLogin[0] ?? 0; // $failedLogin[0] : number of attempts
$now = date("Y-m-d H:i:s");
$lastAttempt = $failedLogin[1] ?? "";
if (empty($lastAttempt)) {
$attempts = $attempts + 1 ;
if($attempts >= 6) {
$lastAttempt = $now;
$attempts = 0;
$user->setLocked(true);
}
} elseif ((round(abs(strtotime($now) - strtotime($lastAttempt)) / 60,2) > 30) ) { //if date of last attempt depass the 30 min, increment number of attempts
$attempts = 1;
$lastAttempt = "";
$user->setLocked(false);
}/* elseif (round(abs(strtotime($now) - strtotime($lastAttempt)) / 60,2) < 30) {
$attempts = $attempts + 1;
if ($attempts >= 6) {
$lastAttempt = $now;
$attempts = 0;
$this->setLocked(true);
}
}*/
$failedLogin[0] = $attempts;
$failedLogin[1] = $lastAttempt;
$user->setFailedLogin($failedLogin);
$this->userManager->save($user);
}
}
}