src/Security/AppAuthenticator.php line 65

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.             'organization_id' => $token->getUser()->getOrganization()->getOrganizationId()
  91.         ];                                
  92.         $this->session->set($token->getUser()->getEmail(), $userData);        
  93.         // END USERDATA
  94.         //START PERMISSIONS
  95.         $userPerms $this->entityManager->getRepository(User::class)->getPermissionsByRole($token->getUser()->getUserRole()->getId());
  96.         $permsList = [];
  97.         $defaultModule "";
  98.         foreach($userPerms as $perms)
  99.         {
  100.             
  101.             if($perms['main_module'] == 1)
  102.             {
  103.                 $defaultModule $perms['url_access'];
  104.             }
  105.             $permsList[] = $perms;
  106.         }
  107.         $this->session->set($token->getUser()->getEmail()."_perms"$permsList);                
  108.         //END PERMISSIONS
  109.         
  110.         //START MENU
  111.         $userModules $this->entityManager->getRepository(User::class)->getModulesByRole($token->getUser()->getUserRole()->getId());
  112.         $moduleList = [];
  113.         foreach($userModules as $module)
  114.         {
  115.             $children $this->entityManager->getRepository(User::class)->getModulesChildrenByParent($module['module_id']);
  116.             $childrenList = [];
  117.             foreach($children as $child)
  118.             {
  119.                 $childrenList[] = $child;    
  120.             }
  121.             
  122.             $merged array_merge($module, ['children'=>$childrenList]);
  123.             $moduleList[] = $merged;
  124.         }    
  125.         $this->session->set($token->getUser()->getEmail()."_menu"$moduleList);                        
  126.         //END MENU
  127.         
  128.         
  129.         if ($targetPath $this->getTargetPath($request->getSession(), $providerKey)) {
  130.             return new RedirectResponse($targetPath);
  131.         }        
  132.         
  133.         if($defaultModule == "")
  134.         {
  135.             throw new \Exception('Se debe agregar un módulo principal para este rol');
  136.         }
  137.         
  138.         // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
  139.         return new RedirectResponse($this->urlGenerator->generate($defaultModule));
  140.         //throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
  141.     }
  142.     protected function getLoginUrl()
  143.     {
  144.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  145.     }
  146. }