Here's a good way to kill user sessions:
use an EventListener
with an onKernelRequest
event. In your main code: public function onKernelRequest(KernelEvent $event)
$request = $event->getRequest();
$token = $this->container->get('security.token_storage')->getToken();
if ($token === null) { // somehow
return;
}
if ($token->getUser()->isLocked() === true) {
// you must implement a boolean flag on your user Entities, which the admins can set to false
$this->container->get('security.token_storage')->setToken(); // default is null, therefore null
$request->getSession()->invalidate(); // these lines will invalidate user session on next request
return;
}
Now, on to your other question: How to list users with their online status? Easy, your user Entities should implement another boolean flag, such as isOnline
(with a getter and setter).
Next, you should create a LoginListener
(no need to implement any interface). And in your main code:
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) {
$user = $event->getAuthenticationToken()->getUser();
if ($user instanceof UserInterface) {
// set isOnline flag === true
// you will need to fetch the $user with the EntityManager ($this->em)
// make sure it exists, set the flag and then
$this->em->flush();
}
}
Your third event should be a LogoutListener
, where you will set the isOnline flag === false
Symfony calls a LogoutListener (as a handler) when a user requests logout.
But you can write your own:
class LogoutListener implements LogoutHandlerInterface {
public function logout(Request $request, Response $response, TokenInterface $token): void
{
$user = $token->getUser();
if (!$user instanceof UserInterface) { /** return if user is somehow anonymous
* this should not happen here, unless... reasons */
return;
}
// else
$username = $user->getUsername(); // each user class must implement getUsername()
// get the entity Manager ($this->em, injected in your constructor)
// get your User repository
$repository = $this->em->getRepository(MyUser::class);
$user = $repository->findOneBy(['username' => $username]); // find one by username
$user->setIsOnline(false);
$this->em->flush(); // done, you've recorded a logout
}
}
Hope this helps. With a bit of luck, it will. Cheers! :-)