src/Security/GoogleAuthenticator.php line 22

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\Fidelizacion\CategoriaCliente;
  4. use App\Entity\Fidelizacion\CategoriaClientePersona;
  5. use App\Entity\Fidelizacion\ParametrosFidelizacion;
  6. use App\Entity\Persona\CargoRolPersona;
  7. use App\Entity\Persona\CargosRol;
  8. use App\Entity\Persona\Persona;
  9. use App\Entity\Seguridades\Usuario;
  10. use Doctrine\ORM\EntityManagerInterface;
  11. use KnpU\OAuth2ClientBundle\Client\ClientRegistry;
  12. use KnpU\OAuth2ClientBundle\Security\Authenticator\SocialAuthenticator;
  13. use League\OAuth2\Client\Provider\GoogleUser;
  14. use Symfony\Component\HttpFoundation\{RedirectResponseRequest};
  15. use Symfony\Component\Routing\RouterInterface;
  16. use Symfony\Component\Security\Core\User\UserProviderInterface;
  17. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. class GoogleAuthenticator extends SocialAuthenticator
  20. {
  21.     private $clientRegistry;
  22.     private $em;
  23.     private $router;
  24.     public function __construct(ClientRegistry $clientRegistryEntityManagerInterface $emRouterInterface $router)
  25.     {
  26.         $this->clientRegistry $clientRegistry;
  27.         $this->em $em;
  28.         $this->router $router;
  29.     }
  30.     public function supports(Request $request)
  31.     {
  32.         return $request->getPathInfo() == '/connect/google/check' && $request->isMethod('GET');
  33.     }
  34.     public function getCredentials(Request $request)
  35.     {
  36.         return $this->fetchAccessToken($this->getGoogleClient());
  37.     }
  38.     public function getUser($credentialsUserProviderInterface $userProvider)
  39.     {
  40.         /** @var GoogleUser $googleUser */
  41.         $googleUser $this->getGoogleClient()->fetchUserFromToken($credentials);
  42.         $email $googleUser->getEmail();
  43.         //dump($googleUser);die();
  44.         $user $this->em->getRepository(Usuario::class)->findOneBy(['usuario' => $email'usuarioGmail' => true]);
  45.         if (!$user) {
  46.             $newPersona = new Persona();
  47.             $newPersona $this->setPersonaGmail($newPersona$googleUser);
  48.             $this->em->persist($newPersona);
  49.             $newCargoRolPersona = new CargoRolPersona();
  50.             $newCargoRolPersona
  51.                 ->setIdCargosRol($this->em->getRepository(CargosRol::class)->find(3))
  52.                 ->setIdPersona($newPersona)
  53.                 ->setIdUsuarioModificacion(0)
  54.                 ->setFechaModificacion(new \DateTime())
  55.                 ->setIpModificacion($_SERVER['REMOTE_ADDR'])
  56.             ;
  57.             $this->em->persist($newCargoRolPersona);
  58.             $categoriaClientePersona = new CategoriaClientePersona;
  59.             $parametroFidelizacionActivo $this->em->getRepository(ParametrosFidelizacion::class)->findOneBy(['activo' => true]);
  60.             $categoriaClientePersona
  61.                 ->setFechaAsignacionCategoria(new \DateTime())
  62.                 ->setActivo(true)
  63.                 ->setIdCategoriaCliente($this->em->getRepository(CategoriaCliente::class)->findOneBy(['idParametrosFidelizacion' => $parametroFidelizacionActivo->getId(), 'nivel' => 1]))
  64.                 ->setIdPersona($newPersona)
  65.                 ->setIdUsuarioModificacion(0)
  66.                 ->setFechaModificacion(new \DateTime())
  67.                 ->setIpModificacion($_SERVER['REMOTE_ADDR'])
  68.             ;
  69.             $this->em->persist($categoriaClientePersona);
  70.             $newUser = new Usuario();
  71.             $newUser $this->setUsuarioGmail($newUser$email);
  72.             $this->em->persist($newUser);
  73.             $this->em->flush();
  74.             return $newUser;
  75.         }
  76.         return $user;
  77.     }
  78.     private function setUsuarioGmail(Usuario $user$email)
  79.     {
  80.         $user->setUsuario($email)
  81.             ->setUsuarioGmail(true)
  82.             ->setActivo(true)
  83.             ->setBloqueado(false)
  84.             ->setNuevaClave(false)
  85.             ->setSuperAdmin(false)
  86.             ->setIdUsuarioModificacion(0)
  87.             ->setFechaModificacion(new \DateTime())
  88.             ->setIpModificacion($_SERVER['REMOTE_ADDR']);
  89.         return $user;
  90.     }
  91.     private function setPersonaGmail(Persona $persona$googleUser) {
  92.         $parametroFidelizacionActivo $this->em->getRepository(ParametrosFidelizacion::class)->findOneBy(['activo' => true]);
  93.         $imagen $this->generateAvatar($googleUser->getFirstName(), $googleUser->getLastName());
  94.         $persona
  95.             ->setFoto($imagen)
  96.             ->setApellidos($googleUser->getLastName())
  97.             ->setNombres($googleUser->getFirstName())
  98.             ->setMailPersonal($googleUser->getEmail())
  99.             ->setIdCategoriaCliente($this->em->getRepository(CategoriaCliente::class)->findOneBy(['idParametrosFidelizacion' => $parametroFidelizacionActivo->getId(), 'nivel' => 1]))
  100.             ->setIdUsuarioModificacion(0)
  101.             ->setFechaModificacion(new \DateTime())
  102.             ->setIpModificacion($_SERVER['REMOTE_ADDR']);
  103.         return $persona;
  104.     }
  105.     private function generateAvatar($nombres$apellidos)
  106.     {
  107.         $name substr($nombres01) . ' ' substr($apellidos01);
  108.         $size 512;
  109.         $bgColor "EEEEEE";
  110.         $txtColor "686868";
  111.         $url "https://ui-avatars.com/api/?name=" urlencode($name) . "&size={$size}&background={$bgColor}&color={$txtColor}";
  112.         $imageData file_get_contents($url);
  113.         $base64 base64_encode($imageData);
  114.         $imagen "data:image/png;base64," $base64;
  115.         return $imagen;
  116.     }
  117.     /**
  118.      * @return \knpU\OAuth2ClientBundle\Client\OAuth2Client
  119.      */
  120.     private function getGoogleClient()
  121.     {
  122.         return $this->clientRegistry
  123.             ->getClient('google');
  124.     }
  125.     /**
  126.      * @param Request $request The request that resulted in an AuthenticationException
  127.      * @param \Symfony\Component\Security\Core\Exception\AuthenticationException $authException The exception that started
  128.      * 
  129.      * @return \Symfony\Component\HttpFoundation\Response
  130.      */
  131.     public function start(Request $requestAuthenticationException $authException null)
  132.     {
  133.         return new RedirectResponse('/');
  134.     }
  135.     /**
  136.      * @param Request $request
  137.      * @param AuthenticationException $exception
  138.      * 
  139.      * @return \Symfony\Component\HttpFoundation\Response|null
  140.      */
  141.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception)
  142.     {
  143.         return new RedirectResponse($this->router->generate('login'));
  144.     }
  145.     /**
  146.      * @param Request $request 
  147.      * @param \Symfony\Component\Security\Core\Authentication\Token\TokenInterface $token
  148.      * @param string $providerKey The provider (i.e. firewall) key
  149.      * 
  150.      * @return void  
  151.      */
  152.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $providerKey)
  153.     {
  154.         return new RedirectResponse($this->router->generate('mi_cancionero'));
  155.     }
  156. }