src/Security/AppAuthenticator.php line 60

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\User;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\HttpFoundation\RedirectResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  10. use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
  11. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  12. use Symfony\Component\Security\Core\Security;
  13. use Symfony\Component\Security\Core\User\UserInterface;
  14. use Symfony\Component\Security\Core\User\UserProviderInterface;
  15. use Symfony\Component\Security\Csrf\CsrfToken;
  16. use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
  17. use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
  18. use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
  19. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  20. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  21. class AppAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
  22. {
  23.     use TargetPathTrait;
  24.     public const LOGIN_ROUTE 'app_login';
  25.     private $entityManager;
  26.     private $urlGenerator;
  27.     private $csrfTokenManager;
  28.     private $passwordEncoder;
  29.     private $session;
  30.     
  31.     public function __construct(EntityManagerInterface $entityManagerUrlGeneratorInterface $urlGeneratorCsrfTokenManagerInterface $csrfTokenManagerUserPasswordEncoderInterface $passwordEncoderSessionInterface $session)
  32.     {
  33.         $this->entityManager $entityManager;
  34.         $this->urlGenerator  $urlGenerator;
  35.         $this->csrfTokenManager $csrfTokenManager;
  36.         $this->passwordEncoder  $passwordEncoder;
  37.         $this->session  $session;
  38.     }
  39.     public function supports(Request $request)
  40.     {
  41.         return self::LOGIN_ROUTE === $request->attributes->get('_route')
  42.             && $request->isMethod('POST');
  43.     }
  44.     public function getCredentials(Request $request)
  45.     {
  46.         $credentials = [
  47.             'email' => $request->request->get('email'),
  48.             'password' => $request->request->get('password'),
  49.             'csrf_token' => $request->request->get('_csrf_token')
  50.         ];
  51.                
  52.         $request->getSession()->set(Security::LAST_USERNAME$credentials['email']);
  53.         return $credentials;
  54.     }
  55.     public function getUser($credentialsUserProviderInterface $userProvider)
  56.     {
  57.         $token = new CsrfToken('authenticate'$credentials['csrf_token']);
  58.         if (!$this->csrfTokenManager->isTokenValid($token)) {
  59.             throw new InvalidCsrfTokenException();
  60.         }
  61.         $user $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
  62.         if (!$user) {
  63.             // fail authentication with a custom error
  64.             throw new CustomUserMessageAuthenticationException('Email could not be found.');
  65.         }
  66.        
  67.         return $user;
  68.     }
  69.     public function checkCredentials($credentialsUserInterface $user)
  70.     {
  71.         return $this->passwordEncoder->isPasswordValid($user$credentials['password']);
  72.     }
  73.     /**
  74.      * Used to upgrade (rehash) the user's password automatically over time.
  75.      */
  76.     public function getPassword($credentials): ?string
  77.     {
  78.         return $credentials['password'];
  79.     }
  80.     public function onAuthenticationSuccess(Request $requestTokenInterface $token$providerKey)
  81.     {
  82.        
  83.         //START USERDATA
  84.         $userData = [
  85.             'id'    => $token->getUser()->getId(),
  86.             'email' => $token->getUser()->getEmail(),
  87.             'first_name' => $token->getUser()->getFirstName(),            
  88.             'last_name'  => $token->getUser()->getLastName(),
  89.             'role_id'    => $token->getUser()->getUserRole()->getId()            
  90.         ];                                
  91.         $this->session->set($token->getUser()->getEmail(), $userData);        
  92.         // END USERDATA
  93.         //START PERMISSIONS
  94.         $userPerms $this->entityManager->getRepository(User::class)->getPermissionsByRole($token->getUser()->getUserRole()->getId());
  95.         $permsList = [];
  96.         $defaultModule "";
  97.         foreach($userPerms as $perms)
  98.         {
  99.             
  100.             if($perms['main_module'] == 1)
  101.             {
  102.                 $defaultModule $perms['url_access'];
  103.             }
  104.             $permsList[] = $perms;
  105.         }
  106.         $this->session->set($token->getUser()->getEmail()."_perms"$permsList);                
  107.         //END PERMISSIONS
  108.         
  109.         //START MENU
  110.         $userModules $this->entityManager->getRepository(User::class)->getModulesByRole($token->getUser()->getUserRole()->getId());
  111.         $moduleList = [];
  112.         foreach($userModules as $module)
  113.         {
  114.             $children $this->entityManager->getRepository(User::class)->getModulesChildrenByParent($module['module_id']);
  115.             $childrenList = [];
  116.             foreach($children as $child)
  117.             {
  118.                 $childrenList[] = $child;    
  119.             }
  120.             
  121.             $merged array_merge($module, ['children'=>$childrenList]);
  122.             $moduleList[] = $merged;
  123.         }    
  124.         $this->session->set($token->getUser()->getEmail()."_menu"$moduleList);                        
  125.         //END MENU
  126.         
  127.         
  128.         if ($targetPath $this->getTargetPath($request->getSession(), $providerKey)) {
  129.             return new RedirectResponse($targetPath);
  130.         }        
  131.         
  132.         if($defaultModule == "")
  133.         {
  134.             throw new \Exception('Se debe agregar un módulo principal para este rol');
  135.         }
  136.         
  137.         // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
  138.         return new RedirectResponse($this->urlGenerator->generate($defaultModule));
  139.         //throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
  140.     }
  141.     protected function getLoginUrl()
  142.     {
  143.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  144.     }
  145. }