src/Controller/SecurityController.php line 100

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Address;
  4. use App\Entity\Farm;
  5. use App\Entity\FarmProducer;
  6. use App\Entity\Organization;
  7. use App\Entity\Producer;
  8. use App\Entity\Profile;
  9. use App\Entity\User;
  10. use App\Form\CheckUserType;
  11. use App\Form\FarmType;
  12. use App\Form\OrganizationType;
  13. use App\Form\ProducerType;
  14. use App\Form\ProfileType;
  15. use App\Form\UserType;
  16. use App\Form\PasswordType;
  17. use App\Form\RecaptchaType;
  18. use App\Form\RecoverPasswordType;
  19. use App\Repository\AddressRepository;
  20. use App\Repository\UserRepository;
  21. use App\Service\EmailService;
  22. use App\Service\TokenGenerator;
  23. use App\Service\UserService;
  24. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  25. use Symfony\Component\Form\FormError;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\Routing\Annotation\Route;
  29. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  30. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  31. use Karser\Recaptcha3Bundle\Validator\Constraints\Recaptcha3Validator;
  32. use Symfony\Contracts\Translation\TranslatorInterface;
  33. use Symfony\Component\Mime\Email;
  34. use Twig\Environment;
  35. class SecurityController extends AbstractController
  36. {
  37.     public $recaptcha;
  38.     private $translator;
  39.     private $tokenGenerator;
  40.     public function __construct(TranslatorInterface $translatorTokenGenerator $tokenGenerator)
  41.     {
  42.         $this->translator $translator;
  43.         $this->tokenGenerator $tokenGenerator;
  44.     }
  45.     /**
  46.      * @Route("/login", name="app_login")
  47.      */
  48.     public function login(AuthenticationUtils $authenticationUtilsUserRepository $userRepository): Response
  49.     {
  50.         $error $authenticationUtils->getLastAuthenticationError();
  51.         $lastUsername $authenticationUtils->getLastUsername();
  52.         $email trim($lastUsername ?? '');
  53.         $user null;
  54.         if ($email) {
  55.             $user $userRepository->createQueryBuilder('u')
  56.                 ->where('LOWER(u.email) = :email')
  57.                 ->setParameter('email'mb_strtolower($email))
  58.                 ->getQuery()
  59.                 ->getOneOrNullResult();
  60.         }
  61.         if ($user && $this->isGranted('ROLE_USER')) {
  62.             return $this->redirectToRoute('app_dashboard');
  63.         }
  64.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  65.     }
  66.     /**
  67.      * @Route("/logout", name="app_logout")
  68.      */
  69.     public function logout()
  70.     {
  71.         throw new \Exception('This method can be blank - it will be intercepted by the logout key on your firewall');
  72.     }
  73.     /**
  74.      * @Route("/register", name="app_register")
  75.      */
  76.     public function register(
  77.         Request $request,
  78.         UserService $userService,
  79.         AddressRepository $addressRepository,
  80.         Recaptcha3Validator $recaptcha3Validator,
  81.         EmailService $emailService,
  82.         Environment $twig,
  83.         UserPasswordHasherInterface $userPasswordHasher
  84.     ): Response
  85.     {
  86.         $em $this->getDoctrine()->getManager();
  87.         $user = new User;
  88.         $userForm $this->createForm(UserType::class, $user);
  89.         $userForm->handleRequest($request);
  90.         $producer = new Producer;
  91.         $producerForm $this->createForm(ProducerType::class, $producer);
  92.         $producerForm->handleRequest($request);
  93.         $organization = new Organization;
  94.         $organizationForm $this->createForm(OrganizationType::class, $organization);
  95.         $organizationForm->handleRequest($request);
  96.         $farm = new Farm;
  97.         $farmForm $this->createForm(FarmType::class, $farm);
  98.         $farmForm->handleRequest($request);
  99.         $profile = new Profile();
  100.         $profileForm $this->createForm(ProfileType::class, $profile);
  101.         $profileForm->handleRequest($request);
  102.         $passwordForm $this->createForm(PasswordType::class, $user);
  103.         $passwordForm->handleRequest($request);
  104.         $recaptchaForm $this->createForm(RecaptchaType::class, $user);
  105.         $recaptchaForm->handleRequest($request);
  106.         // dd( $recaptcha3Validator );
  107.         // $score = $recaptcha3Validator->getLastResponse()->getScore();
  108.         if ( $userForm->isSubmitted()
  109.             and $userForm->isValid()
  110.             and $organizationForm->isValid()
  111.             and $producerForm->isValid()
  112.             and $farmForm->isValid()
  113.             and $profileForm->isValid()
  114.             and $recaptchaForm->isValid()
  115.             and $passwordForm->isValid())
  116.         {
  117.             $producer->setUser($user);
  118.             $producer->setOrganization($organization);
  119.             /* buscamos entonces por Google Id */
  120.             /* en producer */
  121.             $addressGid $producerForm->get('address')->getData();
  122.             if ( ! $address $addressRepository->findOneBy(['location' => $addressGid])  ) {
  123.                 $address = new Address();
  124.                 $address->setLocation$addressGid );
  125.                 $address->setAddress$addressGid );
  126.                 $em->persist$address );
  127.                 /* DEBUG: muy ineficiente arreglar */
  128.             }
  129.             $producer->setAddress$address );
  130.             /* en organization */
  131.             $addressGid $organizationForm->get('address')->getData();
  132.             if ( ! ( $address $addressRepository->findOneBy(['location' => $addressGid]) ) ) {
  133.                 $address = new Address();
  134.                 $address->setLocation$addressGid );
  135.                 $address->setAddress$addressGid );
  136.                 $em->persist$address );
  137.                 /* DEBUG: muy ineficiente arreglar */
  138.             }
  139.             $organization->setAddress$address );
  140.             /* en farm */
  141.             $addressGid $farmForm->get('address')->getData();
  142.             if ( ! ( $address $addressRepository->findOneBy(['location' => $addressGid]) ) ) {
  143.                 $address = new Address();
  144.                 $address->setLocation$addressGid );
  145.                 $address->setAddress$addressGid );
  146.                 $em->persist$address );
  147.                 /* DEBUG: muy ineficiente arreglar */
  148.             }
  149.             $farm->setAddress$address );
  150.             $farm->setOrganization($organization);
  151.             $farm->setProducer($producer);
  152.             $farmProducer = new FarmProducer();
  153.             $farmProducer->setFarm$farm );
  154.             $farmProducer->setProducer$producer );
  155.             $farm->addFarmProducer($farmProducer);
  156.             $userFormOrganization $userForm->has('organization')
  157.                 ? $userForm->get('organization')->getData()
  158.                 : null;
  159.             
  160.             if (!$userFormOrganization || !$organization) {
  161.                 $this->addFlash('error'"Error al crear el usuario: es necesario que el usuario tenga una organización" );
  162.                 return $this->redirectToRoute('app_register');
  163.             }    
  164.                 
  165.             $user->setOrganization($userFormOrganization ?? $organization);
  166.             $user->setRoles(['ROLE_USER''ROLE_MANAGER']);
  167.             $user->setUserType($organizationForm->get('userType')->getData());
  168.             
  169.             $hashedPassword $userPasswordHasher->hashPassword($user$user->getPassword());
  170.             $user->setPassword($hashedPassword);
  171.             $profile->setDefaultAnimalSpecie($profileForm->get('defaultAnimalSpecie')->getData());
  172.             $fullName $profile->getFullName();
  173.             if ( $user->isIsOrganization() ) {
  174.                 $organization->setName$fullName );
  175.                 $organization->setBusinessName$fullName );
  176.             }
  177.             if ( $organization->isIsProducer() ) {
  178.                 $name $organization->getName();
  179.                 $businessName $organization->getBusinessName();
  180.                 $address $organization->getAddress();
  181.                 $cuit $organization->getCuit();
  182.                 $phone $organization->getPhone();
  183.                 $producer->setName$name );
  184.                 $producer->setSurname'' );
  185.                 $producer->setBusinessName$businessName );
  186.                 $producer->setAddress$address );
  187.                 $producer->setCuit$cuit );
  188.                 $producer->setPhone$phone );
  189.             }
  190.             $token $this->tokenGenerator->generateToken();
  191.             $user->setConfirmationToken$token );
  192.             /* todos los persists, de haber un nuevo objeto agregarlo aca */
  193.             foreach( [$profile$farm$farmProducer$organization$producer$user ] as $obj ) {
  194.                 $em->persist$obj );
  195.             }
  196.             $em->flush();
  197.             $sendEmail false;
  198.             $automaticRegistration false;
  199.             /* para debug sin mandar email */
  200.             /* se usa para que muestre el email en lugar de mandarlo */
  201.             if ( $automaticRegistration ) {
  202.                 $email = new Email();
  203.                 $content $twig->render('emails/registration.html.twig', [
  204.                     'email' => $email,
  205.                     'user' => $user,
  206.                     'token' => $token
  207.                 ]);
  208.                 if ( $sendEmail ) {
  209.             
  210.                     return new Response$emailService->sendRegistrationToken($user$content) );
  211.             
  212.                 }        
  213.             
  214.             } else {
  215.             
  216.                 $content $twig->render('emails/manual_registration.html.twig');
  217.             }
  218.             return new Response$content );
  219.         }
  220.         /* return response */
  221.         return $this->render('security/register.html.twig', [
  222.             'user' => $user,
  223.             'userForm' => $userForm->createView(),
  224.             'producerForm' => $producerForm->createView(),
  225.             'organizationForm' => $organizationForm->createView(),
  226.             'farmForm' => $farmForm->createView(),
  227.             'profileForm' => $profileForm->createView(),
  228.             'passwordForm' => $passwordForm->createView(),
  229.             'recaptchaForm' => $recaptchaForm->createView(),
  230.         ]);
  231.     }
  232.     /**
  233.      * @Route("/registration_acceptance/{token}", name="app_registration_acceptance",  methods={"GET"})
  234.      */
  235.     public function registrationAcceptanceUserRepository $userRepository$token)
  236.     {
  237.         $user $userRepository->findOneBy(['confirmationToken' => $token]);
  238.         if ( $user && $token === $user->getConfirmationToken())
  239.         {
  240.             $user->setEnabledtrue );
  241.             $em $this->getDoctrine()->getManager();
  242.             $em->persist($user);
  243.             $em->flush();
  244.             /* esto hace que entre directamente, por ahora no
  245.              *
  246.             return $guardAuthenticatorHandler->authenticateUserAndHandleSuccess(
  247.                 $user,
  248.                 $request,
  249.                 $authenticator,
  250.                 'main'
  251.             );
  252.              */
  253.         }
  254.         return $this->render('security/registration_success.html.twig', [
  255.             'user' => $user,
  256.         ]);
  257.     }
  258.     /**
  259.      * @Route("/password_reset", name="app_password_reset_request",  methods={"GET","POST"})
  260.      */
  261.     public function passwordResetRequest(Request $requestUserService $userServiceEmailService $emailServiceTokenGenerator $tokenGenerator): Response
  262.     {
  263.         $form $this->createForm(CheckUserType::class);
  264.         $form->handleRequest($request);
  265.         $passwordForm $this->createForm(PasswordType::class);
  266.         $passwordForm->handleRequest($request);
  267.         if ( $form->isSubmitted() && $form->isValid()) {
  268.             $user $userService->findOneBy(array('email' => $form->getData()['email']));
  269.             if ($user) {
  270.                 $userService->update($user);
  271.                $emailService->sendPasswordRequest($user);
  272.                 $this->addFlash('success',$this->translator->trans('Password.resetPasswordEmail') . $user->getEmail() );
  273.                 return $this->redirectToRoute('app_login');
  274.                 // para probar sin email
  275.                 /* return $this->render('emails/password_reset_request.html.twig', [
  276.                     'userForm' => $userForm->createView(),
  277.                     'message' => "Se ha enviado un correo a " . $user->getEmail(),
  278.                     'user' => $user,
  279.                     'token' => $user->getConfirmationToken()
  280.                 ]);*/ 
  281.             } else {
  282.                 $form->addError(new FormError('No se encontró usuario'));
  283.             }
  284.         }
  285.         return $this->render('security/password_reset_request.html.twig', [
  286.             'form' => $form->createView(),
  287.         ]);
  288.     }
  289.     /**
  290.      * @Route("/password_reset/{token}", name="app_password_reset_confirm", )
  291.      */
  292.     public function passwordReset(Request $request$tokenUserService $userServiceUserPasswordHasherInterface $passwordHasher): Response
  293.     {
  294.         /** @var User $user */
  295.         $user $userService->findUserByConfirmationToken($token);
  296.         if (!$user) {
  297.             $checkUserForm $this->createForm(CheckUserType::class);
  298.             $checkUserForm->addError(new FormError('userNotFound'));
  299.             return $this->render('security/password_reset_request.html.twig', array(
  300.                 'form' => $checkUserForm->createView(),
  301.             ));
  302.         }
  303.         $form $this->createForm(PasswordType::class);
  304.         $form->handleRequest($request);
  305.         if ($form->isSubmitted()) {
  306.             if($form->isValid()) {
  307.                 $newEncodedPassword $passwordHasher->hashPassword($user$form->get('password')->getData());
  308.                 $user->setPassword($newEncodedPassword);
  309.                 $userService->update($user);
  310.                 $this->addFlash('success'$this->translator->trans('Password.resetSuccess'));
  311.                 return $this->redirectToRoute('app_login');
  312.             }
  313.             else {
  314.                 $this->addFlash('error'$this->translator->trans('Password.resetError'));
  315.             }
  316.         }
  317.         return $this->render('security/password_reset_confirm.html.twig', array(
  318.             'form' => $form->createView(),
  319.         ));
  320.     }
  321.     /**
  322.      * @Route("/password_reset_success", name="app_password_reset", methods={"POST"})
  323.      */
  324.     public function passwordResetSuccess(Request $requestUserPasswordHasherInterface $hasherUserService $userService): Response
  325.     {
  326.         $newPassword $request->get('password');
  327.         $token $request->get('token');
  328.         /** @var User $user */
  329.         $user $userService->findUserByConfirmationToken($token);
  330.         $user->setPassword($hasher->hashPassword($user$newPassword));
  331.         $user->setConfirmationToken(null);
  332.         $user->setPasswordRequestedAt(null);
  333.         $this->getDoctrine()->getManager()->flush();
  334.         return $this->render('security/password_reset_success.html.twig', []);
  335.     }
  336. }