src/Controller/SecurityController.php line 129

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Agency;
  4. use App\Entity\Address;
  5. use App\Entity\JoinTableAgencyUser;
  6. use App\Entity\User;
  7. use App\Entity\UserDetail;
  8. use App\Form\AgencyRegistrationType;
  9. use App\Form\PasswordCreationType;
  10. use App\Form\PasswordRecoveryType;
  11. use App\Service\ValidationService;
  12. use Doctrine\Persistence\ManagerRegistry;
  13. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  14. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  15. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  16. use Symfony\Component\Form\FormError;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Mailer\MailerInterface;
  20. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  23. use Symfony\Contracts\Translation\TranslatorInterface;
  24. use Symfony\Component\Validator\Validator\ValidatorInterface;
  25. /**
  26.  * @Route({"en": "/en", "it": "/it"}, defaults={"_locale" = "it"}, requirements={"_locale" = "it|en"})
  27.  */
  28. class SecurityController extends AbstractController
  29.     protected $mr;
  30.     private $params;
  31.     public function __construct(ManagerRegistry $managerRegistryParameterBagInterface $params)
  32.     {
  33.         $this->mr $managerRegistry;
  34.         $this->params $params;
  35.     }
  36.     /**
  37.      * @Route({"en":"/", "it":"/"}, name="homepage")
  38.      */
  39.     public function homepage(Request $requestMailerInterface $mailerAuthenticationUtils $authenticationUtilsTranslatorInterface $translator): Response
  40.     {
  41.         $em $this->mr->getManager();
  42.         $session $request->getSession();
  43.         $error $authenticationUtils->getLastAuthenticationError();
  44.         $lastUsername $authenticationUtils->getLastUsername();
  45.         $pswUser = new User();
  46.         $form $this->createForm(PasswordRecoveryType::class, $pswUser, array('locale' => $request->getLocale()));
  47.         $form->handleRequest($request);
  48.         if($form->isSubmitted()){
  49.             $valid true;
  50.             $path 'https://www.google.com/recaptcha/api/siteverify?secret=6LcEdHAnAAAAAGDMfuV9qKR-EzPOBx7N24Liqjin&response='.$request->request->get("g-recaptcha-response");
  51.             
  52.             $ch curl_init();
  53.             curl_setopt($chCURLOPT_HTTPHEADER, array(                                                                          
  54.                 'Content-Type: application/json',
  55.                 'Accept: application/json')                                                                       
  56.             );
  57.             curl_setopt($chCURLOPT_URL,$path);
  58.             curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  59.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  60.             curl_setopt($chCURLOPT_CUSTOMREQUEST"GET");
  61.             $result curl_exec($ch);
  62.             curl_close($ch);
  63.             
  64.             $res json_decode($resulttrue);
  65.             
  66.             if(!$res["success"]){
  67.                 $valid false;
  68.                 $form->get('recaptcha')->addError(new FormError($translator->trans('flash_login_01', [], 'website')));
  69.                 $this->addFlash('notice_warning'$translator->trans('flash_login_02', [], 'website'));
  70.             }
  71.             if($valid && $form->isValid()){
  72.                 $user $em->getRepository("App\Entity\User")->findOneByEmail($pswUser->getEmail());
  73.                 if($user){
  74.                     $user->setOneTimeCode(md5(uniqid()));
  75.                     $em->flush();
  76.                     $message = (new TemplatedEmail())
  77.                         ->subject($this->params->get('subject_recover_password'))
  78.                         ->from($this->params->get('sender_email'))
  79.                         ->to($user->getEmail())
  80.                         ->htmlTemplate('email/password_recovery.html.twig')
  81.                         ->context(['user' => $user]);
  82.                     $mailer->send($message);
  83.                 }
  84.                 
  85.                 $this->addFlash('notice_success'$translator->trans('flash_login_03', [], 'website'));
  86.                 return $this->redirectToRoute('homepage');
  87.             }
  88.             else
  89.                 $this->addFlash('notice_warning'$translator->trans('flash_login_04', [], 'website'));
  90.         }
  91.         return $this->render('default/index.html.twig', array(
  92.             'last_username' => $lastUsername,
  93.             'error' => $error,
  94.             'form' => $form->createView()
  95.         ));
  96.     }
  97.     /**
  98.      * @Route({"en":"/login-check", "it":"/accedi-controllo"}, name="login_check")
  99.      */
  100.     public function loginCheck() {}
  101.     /**
  102.      * @Route({"en":"/logout", "it":"/disconnetti"}, name="logout")
  103.      */
  104.     public function logout() {}
  105.     /**
  106.      * @Route({"en":"/registration", "it":"/registrati"}, name="registration")
  107.      */
  108.     public function registration(Request $requestValidatorInterface $validatorTranslatorInterface $translatorMailerInterface $mailer)
  109.     {
  110.         $em $this->mr->getManager();
  111.         $session $request->getSession();
  112.         
  113.         $agency = new Agency();
  114.         $form $this->createForm(AgencyRegistrationType::class, $agency);
  115.         $form->handleRequest($request);
  116.         if($form->isSubmitted()){
  117.             
  118.             $valid true;
  119.             if($valid$valid ValidationService::validateNotBlank($validator$translator$form->get('userName'));
  120.             if($valid$valid ValidationService::validateNotBlank($validator$translator$form->get('userSurname'));
  121.             if($valid$valid ValidationService::validateNotBlank($validator$translator$form->get('userEmail'));
  122.             if($valid$valid ValidationService::validateNotDuplicate($validator$translator$form->get('userEmail'), $em"App\Entity\User", ['id' => -1]);
  123.             if($valid$valid ValidationService::validateNotDuplicate($validator$translator$form->get('vat'), $em"App\Entity\Agency", ['id' => -1]);
  124.             if($valid$valid ValidationService::validateNotBlank($validator$translator$form->get('street'));
  125.             if($valid$valid ValidationService::validateNotBlank($validator$translator$form->get('number'));
  126.             if($valid$valid ValidationService::validateNotBlank($validator$translator$form->get('zip'));
  127.             if($valid$valid ValidationService::validateNotBlank($validator$translator$form->get('city'));
  128.             if($valid$valid ValidationService::validateNotBlank($validator$translator$form->get('province'));
  129.             $path 'https://www.google.com/recaptcha/api/siteverify?secret=6LcEdHAnAAAAAGDMfuV9qKR-EzPOBx7N24Liqjin&response='.$request->request->get("g-recaptcha-response");
  130.             $ch curl_init();
  131.             curl_setopt($chCURLOPT_HTTPHEADER, array('Content-Type: application/json''Accept: application/json'));
  132.             curl_setopt($chCURLOPT_URL$path);
  133.             curl_setopt($chCURLOPT_SSL_VERIFYPEERfalse);
  134.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  135.             curl_setopt($chCURLOPT_CUSTOMREQUEST"GET");
  136.             $result curl_exec($ch);
  137.             curl_close($ch);
  138.             $res json_decode($resulttrue);
  139.             if(!$res["success"]){
  140.                 $valid false;
  141.                 $form->get('recaptcha')->addError(new FormError($translator->trans('flash_registration_01', [], 'website')));
  142.                 $this->addFlash('notice_warning'$translator->trans('flash_registration_02', [], 'website'));
  143.             }
  144.             if($valid && $form->isValid()){
  145.                 $agencyGroup $em->getRepository('App\Entity\AgencyGroup')->findOneById(1); // Gruppo Holidays
  146.                 $agency->setDirectoryPath(uniqid());
  147.                 $agency->setGroup($agencyGroup);
  148.                 $em->persist($agency);
  149.                 $address = new Address();
  150.                 $address->setAgency($agency);
  151.                 $address->setName('Sede legale');
  152.                 $address->setStreet($form->get('street')->getData());
  153.                 $address->setNumber($form->get('number')->getData());
  154.                 $address->setInternal($form->get('internal')->getData());
  155.                 $address->setStairs($form->get('stairs')->getData());
  156.                 $address->setFloor($form->get('floor')->getData());
  157.                 $address->setZip($form->get('zip')->getData());
  158.                 $address->setCity($form->get('city')->getData());
  159.                 $address->setProvince($form->get('province')->getData());
  160.                 $em->persist($address);
  161.                 $user = new User();
  162.                 $user->setEmail($form->get('userEmail')->getData());
  163.                 $user->setName($form->get('userName')->getData());
  164.                 $user->setSurname($form->get('userSurname')->getData());
  165.                 $user->setRole('ROLE_USER');
  166.                 $user->setDirectoryPath(uniqid());
  167.                 $user->setOneTimeCode(md5(uniqid()));
  168.                 $user->setAdminActive(true);
  169.                 $em->persist($user);
  170.                 $userDetail = new UserDetail();
  171.                 $userDetail->setUser($user);
  172.                 $em->persist($userDetail);
  173.                 $jtau = new JoinTableAgencyUser();
  174.                 $jtau->setAgency($agency);
  175.                 $jtau->setUser($user);
  176.                 $jtau->setActive(true);
  177.                 $jtau->setAgencyAdmin(true);
  178.                 $em->persist($jtau);
  179.                 
  180.                 $em->flush();
  181.                 $message = (new TemplatedEmail())
  182.                     ->subject($this->params->get('subject_registration'))
  183.                     ->from($this->params->get('sender_email'))
  184.                     ->to($user->getEmail())
  185.                     ->htmlTemplate('email/registration.html.twig')
  186.                     ->context(['user' => $user]);
  187.                 $mailer->send($message);
  188.                 $this->addFlash('notice_success'$translator->trans('flash_registration_03', [], 'website'));
  189.                 return $this->redirectToRoute('homepage');
  190.             }
  191.             else
  192.                 $this->addFlash('notice_warning'$translator->trans('flash_registration_04', [], 'website'));
  193.         }
  194.         return $this->render('default/registration.html.twig', array(
  195.             'form' => $form->createView()
  196.         ));
  197.     }
  198.     /**
  199.      * @Route({"en":"/create-password/{oneTimeCode}", "it":"/crea-password/{oneTimeCode}"}, name="password_creation", requirements={"oneTimeCode" = "[\w\d]{32}"})
  200.      */
  201.     public function passwordCreation(Request $request$oneTimeCodeValidatorInterface $validatorUserPasswordHasherInterface $passwordHasherTranslatorInterface $translator)
  202.     {
  203.         //DISCONNETTO L'UTENTE SE CONNESSO
  204.         $this->get('security.token_storage')->setToken(null);
  205.         $em $this->mr->getManager();
  206.         
  207.         $user $em->getRepository('App\Entity\User')->findOneByOneTimeCode($oneTimeCode);
  208.         $now = new \DateTime('now');
  209.         $form $this->createForm(PasswordCreationType::class, $user, array('locale' => $request->getLocale()));
  210.         $form->handleRequest($request);
  211.         if($form->isSubmitted()){
  212.             $valid true;
  213.             $valid ValidationService::validateNotBlank($validator$translator$form->get('password'));
  214.             if($valid){
  215.                 $psw $form->get('password')->getData();
  216.                 $count 0;
  217.                 if(preg_match('/[0-9]/'$psw)) $count++;
  218.                 if(preg_match('/[a-z]/'$psw)) $count++;
  219.                 if(preg_match('/[A-Z]/'$psw)) $count++;
  220.                 if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/'$psw)) $count++;
  221.                 if($count 3)
  222.                 {
  223.                     $this->addFlash('notice_warning'$translator->trans('flash_create_psw_01', [], 'website'));
  224.                     $valid false;
  225.                 }
  226.             }
  227.             if($valid && $form->isValid()){
  228.                 $password $passwordHasher->hashPassword($user$form->get("password")->getData());
  229.                 $user->setPassword($password);
  230.                 $em->flush();
  231.             
  232.                 $this->addFlash('notice_success'$translator->trans('flash_create_psw_02', [], 'website'));
  233.                 return $this->redirectToRoute("homepage");
  234.             }
  235.         }
  236.         
  237.         return $this->render('default/password_create.html.twig', array(
  238.             'oneTimeCode' => $oneTimeCode,
  239.             'form' => $form->createView()
  240.         ));
  241.     }
  242. }