Symfony - How to logout locked or banned User automatically

If you want to logout locked or banned User automatically, you need, first of all, add new Listener with onKernelRequest(RequestEvent $event) method.

Just FYI, this method Symfony calls every time on every request, so, be careful to use this method. It can shoot yourself in the foot.

For example:


class SecurityUserListener { 
	public function onKernelRequest(RequestEvent $event) { }
}

After that, we need to check our User on status: banned or locked (what you need). For this we need to inject Token Storage in class constructor. Token Storage can return User.

So, lets do it:


class SecurityUserListener { 
    public function __construct(private TokenStorageInterface $tokenStorage) { } 
    public function onKernelRequest(RequestEvent $event) { 
        $user = $this->tokenStorage->getToken()?->getUser(); 
    }
}

Now, you can examine the user object's status. If it meets your criteria, set the current token to null (indicating no user in the token anymore) and invalidate the session.


class SecurityUserListener { 
	public function __construct(private TokenStorageInterface $tokenStorage) { } 
    public function onKernelRequest(RequestEvent $event) { 
    	$user = $this->tokenStorage->getToken()?->getUser(); 
        if ($user instanceof User) { 
        	if ($user->isLocked()) { 
            	$this->tokenStorage->setToken(); 
                $event->getRequest()->getSession()->invalidate(); 
            } 
        } 
    }
}

Now, your user is effectively logged out. As a final touch, consider adding a redirect to the login page and displaying a specific error message.

Something like this:


class SecurityUserListener { 
	public function __construct(private TokenStorageInterface $tokenStorage, private RouterInterface $router) { } 
	public function onKernelRequest(RequestEvent $event) { 
  		$user = $this->tokenStorage->getToken()?->getUser(); 
    	if ($user instanceof User) { 
    		// If user is locked - logout and show a locked user error 
        	if ($user->isLocked()) { 
        		$this->tokenStorage->setToken(); 
            	$event->getRequest()->getSession()->invalidate(); 
            	$exception = new CustomUserMessageAuthenticationException('Your account is banned.'); 
            	$event->getRequest()->getSession()->set(Security::AUTHENTICATION_ERROR, $exception); 
            	$event->setResponse(new RedirectResponse($this->router->generate('client_login'))); 
        	} 
    	} 
	}
}

With this implementation, a locked user will be logged out, and a custom error message will be displayed upon redirecting to the login page.

Comments

Popular posts from this blog

CSS Как прикрепить слой (div) к краю

MySQL - How to add JSON column type

Как сделать заголовок модуля активной ссылкой в Joomla 1.5