em = $entityManager; $this->tokenStorage = $tokenStorage; $this->router = $router; $this->merchantResolver = $merchantResolver; } public static function getSubscribedEvents() { return [ KernelEvents::REQUEST => ['setUserRolesFromKernelRequest'], SecurityEvents::INTERACTIVE_LOGIN => ['setUserRolesAuthenticationSuccess'], ]; } public function setUserRolesFromKernelRequest(RequestEvent $event) { if (!$event->isMainRequest()) { return; } if ($this->setUserRoles($event->getRequest())) { $response = new RedirectResponse($this->router->generate('app_admin_dashboard')); $event->setResponse($response); } } public function setUserRolesAuthenticationSuccess(InteractiveLoginEvent $interactiveLoginEvent) { $this->setUserRoles($interactiveLoginEvent->getRequest()); } public function setUserRoles(Request $request): bool { if ($this->tokenStorage && $this->tokenStorage->getToken()) { $token = $this->tokenStorage->getToken(); $sessionUser = $token->getUser(); if ($sessionUser instanceof UserInterface) { $userMerchant = $this->merchantResolver->getUserMerchant($sessionUser); if ($userMerchant) { $roles = $userMerchant->getRoles(); } else { $roles = [RolesDefinition::ROLE_USER]; } if ($roles != $sessionUser->getRoles()) { $sessionUser->setRoles($roles); $this->em->update($sessionUser); $this->em->flush(); $token = new UsernamePasswordToken( $sessionUser, null, 'main', $sessionUser->getRoles() ); $this->tokenStorage->setToken($token); return true; } } } return false; } }