src/Controller/RegistrationController.php line 155

Open in your IDE?
  1. <?php
  2. // src/Controller/RegistrationController.php
  3. namespace App\Controller;
  4. use App\Form\UserType;
  5. use App\Entity\User;
  6. use App\Helper\Helpers;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  11. use Psr\Log\LoggerInterface;
  12. use \Datetime;
  13. class RegistrationController extends AbstractController
  14. {
  15.     /**
  16.      * @Route("/register", name="user_registration")
  17.      */
  18.     public function registerAction(Request $requestUserPasswordEncoderInterface $passwordEncoderLoggerInterface $logger)
  19.     {
  20.         $securityContext $this->container->get('security.authorization_checker');
  21.         if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
  22.             return $this->redirectToRoute('main');
  23.         }
  24.         if (isset($_GET['info'])) {
  25.             $info=$_GET['info'];
  26.         } else {
  27.             $info="";
  28.         }
  29.         // 1) build the form
  30.         $user = new User();
  31.         $form $this->createForm(UserType::class, $user);
  32.         
  33.         $error null;        
  34.         // 2) handle the submit (will only happen on POST)
  35.         $form->handleRequest($request);
  36.         if ($form->isSubmitted()) {
  37.             if($form->isValid()){
  38.                 
  39.                 // reCAPTCHA validation
  40.                 $captcha $request->request->get('g-recaptcha-response');
  41.                 $secret '6LfSVu0dAAAAACvOElC-RsnH9-UwU9nS6287Muar';
  42.                 $response json_decode(
  43.                     file_get_contents(
  44.                         sprintf(
  45.                             'https://www.google.com/recaptcha/api/siteverify?secret=%s&response=%s',
  46.                             $secret,
  47.                             $captcha
  48.                         )
  49.                     ),
  50.                     true
  51.                 );
  52.                 if ($response['success'] == false) {
  53.                     return $this->render(
  54.                         'registration/register.html.twig',array('form' => $form->createView(),
  55.                             'error' => 'reCAPTCHA'
  56.                             )
  57.                     );
  58.                 }
  59.                 $repUser $this->getDoctrine()->getRepository(User::class);
  60.                 $existingUser $repUser->findOneByEmail($user->getEmail());
  61.                 if ($existingUser) {
  62.                     $error 'Este email ya se encuentra registrado';
  63.                     return $this->render('registration/register.html.twig',array(
  64.                             'form' => $form->createView(),
  65.                             'error' => $error,
  66.                         )
  67.                     );
  68.                 }
  69.                 $password $passwordEncoder->encodePassword($user$user->getPlainPassword());
  70.                 $user->setRoles(["ROLE_USER"]);
  71.                 //$user->setActive(false);
  72.                 $user->setActive(true);
  73.                 $user->setPassword($password);
  74.                 date_default_timezone_set('Europe/Madrid');
  75.                 $user->setCreatedDate(new \DateTime());
  76.                 
  77.                 $to $user->getEmail();
  78.                 $hash Helpers::encrypt($to);
  79.                 $subject 'Activa tu cuenta en EntradasyTickets';
  80.                 $from 'admin@entradasytickets.com';
  81.                 $separator md5(time());
  82.                 $eol PHP_EOL;
  83.                 // main header
  84.                 $headers "From: " $from $eol;
  85.                 $headers .= "MIME-Version: 1.0" $eol;
  86.                 $headers .= "Content-Type: multipart/mixed; boundary=\"" $separator "\"";
  87.                 $message file_get_contents('./partials/register1.html');
  88.                 $message .= "<br/><h3><strong>ATENCION: Tu cuenta aun no esta activa.</strong></h3>";
  89.                 $message .= "<br/><a href='https://entradasytickets.com/verify_email?hash=".$hash."'>Por favor haz click aqui para activarla:";
  90.                 $message .= "<br/>https://entradasytickets.com/verify_email?hash=".$hash;
  91.                 $message .= "<br/>";
  92.                 $message .= "<br/>";
  93.                 $message .= "<br/><h3>¡Gracias por crear tu cuenta!</h3>";
  94.                 $message .= file_get_contents('./partials/register2.html');
  95.                 $body "";
  96.                 // message
  97.                 $body .= "--" $separator $eol;
  98.                 $body .= "Content-Type: text/html; charset=\"iso-8859-1\"" $eol;
  99.                 $body .= "Content-Transfer-Encoding: 8bit" $eol $eol;
  100.                 $body .= $message $eol;
  101.                 $body .= "--" $separator $eol;
  102.                 $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" $eol;
  103.                 $body .= "Content-Transfer-Encoding: 8bit" $eol $eol;
  104.                 $body .= "*Este mensaje se envia con HTML si no lo ves bien por favor configure su navegador" $eol;
  105.                 //mail($to, $subject, $body, $headers);
  106.                 // 4) save the User!
  107.                 $entityManager $this->getDoctrine()->getManager();
  108.                 $entityManager->persist($user);
  109.                 $logger->info('User register successfully');
  110.                 $entityManager->flush();
  111.                 // ... do any other work - like sending them an email, etc
  112.                 // maybe set a "flash" success message for the user
  113.                 return $this->redirectToRoute(
  114.                     'login',
  115.                     //array('info' => "Para poder seguir adelante tienes que activar la cuenta a través del enlace de confirmación que hemos enviado por correo. IMPORTANTE MIRAR BANDEJA DE SPAM")
  116.                     array('info' => "Puedes iniciar sesión para comprar las entradas")
  117.                 );
  118.             }else{
  119.                 $error "Las contraseñas deben coincidir";
  120.             }
  121.         }
  122.         return $this->render('registration/register.html.twig',array(
  123.             'form' => $form->createView(),
  124.             'error' => $error,
  125.             'info' => $info
  126.         ));
  127.     }
  128.     /**
  129.      * @Route("/recover_password", name="recover_password")
  130.      */
  131.     public function remindpw(UserPasswordEncoderInterface $passwordEncoderLoggerInterface $logger)
  132.     {
  133.         $securityContext $this->container->get('security.authorization_checker');
  134.         if ($securityContext->isGranted('IS_AUTHENTICATED_FULLY')) {
  135.             return $this->redirectToRoute('main');
  136.         }
  137.         if (isset($_POST['_email'])) {
  138.             $repUser $this->getDoctrine()->getRepository(User::class);
  139.             if ($user $repUser->findOneByEmail($_POST['_email'])) {
  140.                 //mandar mail con contraseña generada automaticamente
  141.                 $psswd substr(md5(microtime()), 18);
  142.                 $password $passwordEncoder->encodePassword($user$psswd);
  143.                 $user->setPassword($password);
  144.                 $to $user->getEmail();
  145.                 $from 'admin@entradasytickets.com';
  146.                 $subject 'Tu nueva contraseña en EntradasyTickets';
  147.                 $separator md5(time());
  148.                 $eol PHP_EOL;
  149.                 // main header
  150.                 $headers "From: " $from $eol;
  151.                 $headers .= "MIME-Version: 1.0" $eol;
  152.                 $headers .= "Content-Type: multipart/mixed; boundary=\"" $separator "\"";
  153.                 $message file_get_contents('./partials/register1.html');
  154.                 $message .= "<br/>Te hemos generado una nueva contraseña automática:";
  155.                 $message .= "<br/><h3>".$psswd;
  156.                 $message .= "</h3><br/>";
  157.                 $message .= "<br/>Entra en tu cuenta y cambia esta contraseña por la que prefieras.";
  158.                 $message .= "<br/>";
  159.                 $message .= "<br/>";
  160.                 //si no ha activado su cuenta
  161.                 if (!$user->getisActive()) {
  162.                     $hash Helpers::encrypt($to);
  163.                     $message .= "<br/><h4><strong>ATENCIÓN: Tu cuenta aún no está activa.</strong></h4>";
  164.                     $message .= "<br/><a href='https://entradasytickets.com/verify_email?hash=".$hash."'>Por favor haz click aquí para activarla:";
  165.                     $message .= "<br/>https://entradasytickets.com/verify_email?hash=".$hash;
  166.                     $message .= "<br/>";
  167.                     $message .= "<br/>";
  168.                 }
  169.                 $message .= file_get_contents('./partials/register2.html');
  170.                 $body "";
  171.                 // message
  172.                 $body .= "--" $separator $eol;
  173.                 $body .= "Content-Type: text/html; charset=\"iso-8859-1\"" $eol;
  174.                 $body .= "Content-Transfer-Encoding: 8bit" $eol $eol;
  175.                 $body .= $message $eol;
  176.                 mail($to$subject$body$headers);
  177.                 $entityManager $this->getDoctrine()->getManager();
  178.                 $entityManager->persist($user);
  179.                 $logger->info('User new password successfully sent');
  180.                 $entityManager->flush();
  181.                 return $this->redirectToRoute(
  182.                     'login',
  183.                     array('info' => "Tienes una nueva contraseña en tu buzón de correo electrónico. IMPORTANTE MIRAR BANDEJA DE SPAM")
  184.                 );
  185.             } else {
  186.                 //sino devolver con error al formulario
  187.                 return $this->render(
  188.                     'registration/recoverpw.html.twig',
  189.                     array('error' => 'El email introducido no está asociado a un usuario registrado.'
  190.                     )
  191.                 );
  192.             }
  193.         }
  194.         return $this->render(
  195.             'registration/recoverpw.html.twig'
  196.         );
  197.     }
  198. }