src/Controller/SecurityController.php line 38

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Doctrine\Persistence\ManagerRegistry;
  4. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  5. use Symfony\Component\Mailer\MailerInterface;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\HttpFoundation\Response;
  10. use Symfony\Component\Form\FormError;
  11. use Symfony\Component\Validator\Validator\ValidatorInterface;
  12. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  13. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  14. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  15. use App\Entity\Master\User;
  16. use App\Form\PasswordCreationType;
  17. use App\Form\PasswordRecoveryType;
  18. use App\Form\Model\Contact;
  19. use App\Form\ContactType;
  20. use App\Service\ValidationService;
  21. class SecurityController extends AbstractController
  22. { 
  23.     protected $mr;
  24.     private $params;
  25.     public function __construct(ManagerRegistry $managerRegistry, ParameterBagInterface $params)
  26.     {
  27.         $this->mr = $managerRegistry;
  28.         $this->params = $params;
  29.     }
  30.     /**
  31.      * @Route("/login", name="login")
  32.      */
  33.     public function login(Request $request, MailerInterface $mailer, AuthenticationUtils $authenticationUtils): Response
  34.     {
  35.         $emMaster = $this->mr->getManager('master');
  36.         $session = $request->getSession();
  37.         $error = $authenticationUtils->getLastAuthenticationError();
  38.         $lastUsername = $authenticationUtils->getLastUsername();
  39.         $pswUser = new User();
  40.         $form = $this->createForm(PasswordRecoveryType::class, $pswUser);
  41.         $form->handleRequest($request);
  42.         if($form->isSubmitted()){
  43.             $valid = true;
  44.             $path = 'https://www.google.com/recaptcha/api/siteverify?secret=6LcmTdgUAAAAAHtbLS0hf0fJtNZALbjDqU_6Xxhq&response='.$request->request->get("g-recaptcha-response");
  45.             
  46.             $ch = curl_init();
  47.             curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
  48.                 'Content-Type: application/json',
  49.                 'Accept: application/json')                                                                       
  50.             );
  51.             curl_setopt($ch, CURLOPT_URL,$path);
  52.             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  53.             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  54.             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
  55.             $result = curl_exec($ch);
  56.             curl_close($ch);
  57.             
  58.             $res = json_decode($result, true);
  59.             
  60.             if(!$res["success"]){
  61.                 $valid = false;
  62.                 $form->get('recaptcha')->addError(new FormError("Convalidare prima di inviare la richiesta"));
  63.                 $this->addFlash('notice_warning', 'Prima di inviare la richiesta, provare di non essere un robot.');
  64.             }
  65.             if($valid && $form->isValid()){
  66.                 $user = $emMaster->getRepository("App\Entity\Master\User")->findOneByEmail($pswUser->getEmail());
  67.                 if($user){
  68.                     $datetime = new \DateTime('now');
  69.                     $user->setOneTimeCode(md5(uniqid()));
  70.                     $user->setExpirationOneTimeCode($datetime);
  71.                     $emMaster->flush();
  72.                     $message = (new TemplatedEmail())
  73.                         ->subject($this->params->get('subject_recover_password'))
  74.                         ->from($this->params->get('sender_email'))
  75.                         ->to($user->getEmail())
  76.                         ->htmlTemplate('email/password_recovery.html.twig')
  77.                         ->context(['user' => $user]);
  78.                     $mailer->send($message);
  79.                 }
  80.                 
  81.                 $this->addFlash('notice_success', "La richiesta è stata ricevuta correttamente.<br>Se l'account esiste, verrà inviato un messaggio di posta elettronica all'indirizzo corrispondente.");
  82.                 return $this->redirectToRoute('login');
  83.             }
  84.             else
  85.                 $this->addFlash('notice_warning', 'Controlla le informazioni inserite nel form di recupero password.');
  86.         }
  87.         return $this->render('default/login.html.twig', array(
  88.             'last_username' => $lastUsername,
  89.             'error' => $error,
  90.             'form' => $form->createView()
  91.         ));
  92.     }
  93.     /**
  94.      * @Route("/login_check", name="login_check")
  95.      */
  96.     public function loginCheck() {}
  97.     /**
  98.      * @Route("/logout", name="logout")
  99.      */
  100.     public function logout() {}
  101.     /**
  102.      * @Route("/crea-password/{oneTimeCode}", name="password_creation", requirements={"oneTimeCode" = "[\w\d]{32}"})
  103.      */
  104.     public function passwordCreation(Request $request, $oneTimeCode, ValidatorInterface $validator, UserPasswordHasherInterface $passwordHasher)
  105.     {
  106.         //DISCONNETTO L'UTENTE SE CONNESSO
  107.         $this->get('security.token_storage')->setToken(null);
  108.         $emMaster = $this->mr->getManager('master');
  109.         
  110.         $user = $emMaster->getRepository('App\Entity\Master\User')->findOneByOneTimeCode($oneTimeCode);
  111.         $now = new \DateTime('now');
  112.         if($user->getExpirationOneTimeCode() != null){
  113.             date_modify($user->getExpirationOneTimeCode(), '+3 hours');
  114.             if($now->format("YmdHis") < $user->getExpirationOneTimeCode()->format("YmdHis")){
  115.                 $form = $this->createForm(PasswordCreationType::class, $user);
  116.                 $form->handleRequest($request);
  117.                 if($form->isSubmitted()){
  118.                     $valid = true;
  119.                     $valid = ValidationService::validateNotBlank($validator, $form->get('password'));
  120.                     if($valid){
  121.                         $psw = $form->get('password')->getData();
  122.                         $count = 0;
  123.                         if(preg_match('/[0-9]/', $psw)) $count++;
  124.                         if(preg_match('/[a-z]/', $psw)) $count++;
  125.                         if(preg_match('/[A-Z]/', $psw)) $count++;
  126.                         if(preg_match('/[\!\#\$\&\(\)\.\+\-_]/', $psw)) $count++;
  127.                         if($count < 3)
  128.                         {
  129.                             $this->addFlash('notice_warning', "La password inserita non è sufficientemente forte.");
  130.                             $valid = false;
  131.                         }
  132.                     }
  133.                     if($valid && $form->isValid()){
  134.                         $password = $passwordHasher->hashPassword($user, $form->get("password")->getData());
  135.                         $user->setPassword($password);
  136.                         $emMaster->flush();
  137.                     
  138.                         $this->addFlash('notice_success', "La nuova password è stata creata correttamente; prima di poter accedere controllare se l'account è attivato.");
  139.                         return $this->redirectToRoute("login");
  140.                     }
  141.                 }
  142.                 
  143.                 return $this->render('default/create_password.html.twig', array(
  144.                     'oneTimeCode' => $oneTimeCode,
  145.                     'form' => $form->createView()
  146.                 ));
  147.             }
  148.             else{
  149.                 $this->addFlash('notice_warning', "Il codice per la generazione della password è scaduto.<br>La password deve essere creata entro 3 ore dalla richiesta di attivazione.<br>Per poter proseguire è necessario richiedere un nuovo codice.");
  150.                 return $this->redirectToRoute("login");
  151.             }
  152.         }
  153.         else{
  154.             $this->addFlash('notice_warning', "Per poter creare una nuova password è necessario prima richiedere l'attivazione dell'account.");
  155.             return $this->redirectToRoute("login");
  156.         }
  157.     }
  158. }