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