- <?php
- namespace App\Controller\Seguridades;
- use App\Controller\InformacionGeneralController;
- use App\Entity\Seguridades\GrupoCargo;
- use App\Entity\Seguridades\IntentosAcceso;
- use App\Entity\Seguridades\Usuario;
- use App\Entity\TalentoHumano\CargoRolUo;
- use App\Entity\TalentoHumano\Persona;
- use App\Entity\TalentoHumano\RelacionLaboral;
- use App\Entity\VinculacionSociedad\ContactosEmpresa;
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
- use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
- use Symfony\Component\HttpFoundation\{Request};
- use Symfony\Component\Routing\Annotation\Route;
- use App\Service\{AdminService, CacheService, EmailService, LoginService};
- use Doctrine\ORM\EntityManagerInterface;
- use Symfony\Component\Form\Extension\Core\Type\{SubmitType, TextType};
- use Symfony\Component\Security\Core\User\UserInterface;
- class AuthController extends AbstractController
- {
-     public function index(AuthenticationUtils $authenticationUtils, Request $request, EntityManagerInterface $em, CacheService $cache, LoginService $login)
-     {      
-         //$informacionGeneral = new InformacionGeneralController($em);
-         //$logoUrl = $informacionGeneral->getLogoUrl();
-         $message='';
-         $error = $authenticationUtils->getLastAuthenticationError();
-         $lastUsername = $authenticationUtils->getLastUsername(); 
-         if($error):
-             $user=$login->checkUser($lastUsername,$em);
-             if($user):
-                 $cache->add('lastUsername',$lastUsername);
-                 if($user['active']):    
-                     if(!$user['bloqueado']):  
-                         
-                         $message = $login->checkAttemps($user,$em);
-                         
-                         if(!$message):
-                             return $this->redirectToRoute('bloqueado');
-                         endif;
-                     else:
-                         return $this->redirectToRoute('usuarioBloqueado');
-                     endif;
-                 else:
-                     $cache->add('inactivo',true);
-                     return $this->redirectToRoute('inactivo');
-                 endif;
-             else:
-                 $message = 'Usuario/Contraseña Incorrectos';    
-             endif;
-         endif;  
-         return $this->render('Seguridades/auth/login/login.html.twig', [
-             'error' => $error,
-             'last_username' => $lastUsername,
-             'message'=> $message,
-             'logoUrl'=> 'assets/img/Avatar_profileJPG.jpg'
-         ]);
-     }
-     /**
-      * @Route("/loginGmail", name="loginGmail")
-      */
-     public function loginGmail(EntityManagerInterface $em){
-        return $this->redirectToRoute('home');
-       }
-      //--------------------------------------------------------------------------------------------------------------  
-   
-     public function inactivo(CacheService $cache)
-     { 
-         if($cache->get('inactivo') && $cache->get('lastUsername')):
-             $cache->delete('lastUsername');$cache->delete('inactivo'); 
-             return $this->render('Seguridades/auth/inactivo.html.twig');
-         else:
-             return $this->redirectToRoute('login');
-         endif;
-     }
-     public function usuarioBloqueado(CacheService $cache)
-     { 
-         if($cache->get('lastUsername')):
-             $cache->delete('lastUsername');
-             return $this->render('Seguridades/auth/bloqueado.html.twig');
-         else:
-             return $this->redirectToRoute('login');
-         endif;
-     }
-   //--------------------------------------------------------------------------------------------------------------  
-     
-     public function bloqueado(LoginService $login,CacheService $cache,EntityManagerInterface $em)
-     {       
-         $user = $cache->get('lastUsername');
-         if($user)://verificamos si existe un correo en cache
-             $cache->delete('lastUsername');
-             $user = $em->getRepository(Usuario::class)->findOneBy(['usuario'=>$user]);
-             
-             $dataPerson = $this->getDataUser($user);
-             $login->sendEmailBloqueo($dataPerson,$em);
-             
-             //Cambia el estado del usuario
-             $login->setStateUser($user,$em);
-             $correo = $user->getIdPersona()->getMailPersonal();
-             $correo = substr($correo, 0,5); $correo .= 'XXXXXXX';
-             $this->removeAttempsUser($em,$user);
-             return $this->render('Seguridades/auth/comprobar.html.twig',[
-                 'nombres'=>$dataPerson['nombres'], 
-                 'apellido1'=>$dataPerson['apellido1'], 
-                 'apellido2'=>$dataPerson['apellido2'],
-                 'correo'=>$correo
-             ]);
-         else:
-             return $this->redirectToRoute('login');
-         endif;            
-     }   
-     private function removeAttempsUser(EntityManagerInterface $em, Usuario $user){
-         $attemp = $em->getRepository(IntentosAcceso::class)->findOneBy(['idUsuario'=>$user->getId()]);
-         $em->remove($attemp);$em->flush();
-     }
-     /**
-      * @Route("/newPassMail", name="newPassMail")
-      */
-     public function newPassMail(Request $request, LoginService $login, EntityManagerInterface $em){
-         $response = ['response' => false, 'message' => 'El usuario se encuentra inactivo'];
-         $idUsuario = $request->request->get('idUsuario');
-         $user = $em->getRepository(Usuario::class)->find($idUsuario);
-         if ($user && $user->getActivo()) {
-             $dataUser = $this->getDataUser($user);
-             $pass = $login->setPasswordUser($user, $em);
-             $login->SendEmail($dataUser, $pass, $em);
-             $response['response'] = true;
-             $response['message'] = 'Clave generada exitosamente';
-         }
-         return $this->json($response, 200);
-     }
-     public function recuperacion(Request $request,LoginService $login,EntityManagerInterface $em)
-     {        
-         $form = $this->createRecForm();
-         $form->handleRequest($request);
-         $user = $message ='';
-         if($form->isSubmitted()):    
-             $usuario=$form->get('usuario')->getData();
-             $user=$login->getUserLog($usuario, $em);
-             if($user && $user->getActivo()):
-                 $datosUser = $this->getDataUser($user);
-                 $pass=$login->setPasswordUser($user,$em);  
-                 $login->SendEmail($datosUser,$pass,$em);
-                 return $this->render('Seguridades/auth/recuperar_password.html.twig');
-             else:
-                 $message = "El Usuario no existe o se encuentra Inactivo, porfavor contactarse con el Administrador";
-             endif;
-             
-         endif;
-         
-         return $this->render('Seguridades/auth/recuperar.html.twig',[
-             'form'=> $form->createView(),
-             'user'=>$user,
-             'message'=>$message
-         ]);
-     }
-     private function getDataUser(Usuario $user){
-         return [
-             'mail' => $user->getIdPersona()->getMailPersonal(),
-             'usuario' => $user->getUsuario(),
-             'nombres' => $user->getIdPersona()->getNombres(),
-             'apellidos' => $user->getIdPersona()->getApellidos(),
-         ];
-     }
-     
-     //Control de Registro de Logeo
-     public function accessControl(UserInterface $user, EntityManagerInterface $em, CacheService $cache, AdminService $adminService, LoginService $loginSer){
-         //Borra los intentos
-         $intentosAcceso = $em->getRepository(IntentosAcceso::class)->findOneBy(['idUsuario'=>$user->getId()]);    
-         if($intentosAcceso): $em->remove($intentosAcceso);$em->flush(); endif;
- /*         $cargo = $em->getRepository(RelacionLaboral::class)->findOneBy(['idPersona'=>$user->getIdPersona()->getId()]);
-         $grupo = $em->getRepository(GrupoCargo::class)->findOneBy(['idCargosRol'=>$cargo->getIdCargosRol()->getId()]);
-  */
-         //Comprueba si está activo
-         if(!$user->getActivo()):
-             $cache->add('lastUsername',$user->getUsername());
-             $cache->add('inactivo',true);
-             return $this->redirectToRoute('inactivo');
-         endif;
-         //Comprueba si está Bloqueado
-         if($user->getBloqueado()):
-             $cache->add('lastUsername',$user->getUsername());
-             return $this->redirectToRoute('bloqueado');
-         endif;
-          //Compueba si tiene que cambiar la contraseña
-         if($adminService->checkPassChange($user)):return $this->redirectToRoute('change_pass');endif;
-          //Determina que tipo de Usuario acaba de loguearse
-          $loginSer->addAccess($user,'home', $em);
-          return $this->redirectToRoute('home'); 
-         //return $this->redirectToRoute('profile');   
-        /*  if($grupo->getIdGrupo()->getNombre() === 'Administradores'):
-             $loginSer->addAccess($user,'system', $em);
-             return $this->redirectToRoute('system');   
-         else:
-         endif;  */
-     }
-     
-     private function createRecForm(){
-         return $this->createFormBuilder($user = new Usuario)
-             ->add('usuario', TextType::class, array(
-                 'attr'=>[
-                     'class'=>'form-control'
-                 ],
-                 'mapped'=> false))
-             ->add('submit', SubmitType::class, array(
-                 'attr'=>[
-                     'class'=>'btn btn-primary'
-                 ],
-                 'label'=> 'Recuperar Cuenta'))
-             ->getForm();
-     }
-     
-     
- }
-