src/Controller/SecurityController.php line 239

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AppUser;
  4. use App\Form\ActivationTokenAgainType;
  5. use App\Form\ChangePasswordType;
  6. use App\Form\ForgottenPasswordType;
  7. use App\Form\RegistrationType;
  8. use App\Form\ProfileType;
  9. use App\Model\UrlGenerator;
  10. use App\Traits\Uploader;
  11. use App\Validator;
  12. use Doctrine\ORM\EntityManagerInterface;
  13. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Component\Routing\RouterInterface;
  18. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  19. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  20. use Symfony\Component\String\Slugger\SluggerInterface;
  21. class SecurityController extends DefaultController
  22. {
  23.     use UrlGenerator;
  24.     use Validator;
  25.     use Uploader;
  26.     private $userRepository;
  27.     private $encoder;
  28.     private $mailer;
  29.     private $router;
  30.     private $eventDispatcher;
  31.     private $entityManager;
  32.     public function __construct(EntityManagerInterface $em,UserPasswordEncoderInterface $encoder,\Swift_Mailer $mailer,RouterInterface $router)
  33.     {
  34.        $this->userRepository $em->getRepository(AppUser::class);
  35.        $this->encoder $encoder;
  36.        $this->mailer $mailer;
  37.        $this->router $router;
  38.        $this->entityManager $em;
  39.     }
  40.     /**
  41.      * @Route("/registrace", name="app_registration")
  42.      */
  43.     public function registration(Request $request) :Response
  44.     {
  45.         $user = new AppUser();
  46.         $appParameters $this->loadAppParameters();
  47.         $publicKey $appParameters['Captcha']['public-key'];
  48.         $clientIPAdress $_SERVER['REMOTE_ADDR'] == '::1' '89.24.215.86' $_SERVER['REMOTE_ADDR'];
  49.         $form $this->createForm(RegistrationType::class, $user);
  50.         $form->handleRequest($request);
  51.         if ($form->isSubmitted() && $form->isValid())
  52.         {
  53.             /* get recaptcha */
  54.             $recaptchaResponse $form->get('recaptchaResponse')->getData();
  55.             // $recaptchaResponse2 = $form->get('g-recaptcha-response')->getData();
  56.             $recaptchaSecret $appParameters['Captcha']['secret-key'];
  57.             $post_data http_build_query(
  58.                 array(
  59.                     'secret' => $recaptchaSecret,
  60.                     'response' => $recaptchaResponse,
  61.                     'remoteip' => $clientIPAdress
  62.                 )
  63.             );
  64.             $opts = array('http' =>
  65.                 array(
  66.                     'method'  => 'POST',
  67.                     'header'  => 'Content-type: application/x-www-form-urlencoded',
  68.                     'content' => $post_data
  69.                 )
  70.             );
  71.             $context  stream_context_create($opts);
  72.             $recaptcha file_get_contents('https://www.google.com/recaptcha/api/siteverify'false$context);
  73.             // ziskani recaptcha ranku
  74.             //$recaptcha = file_get_contents('https://www.google.com/recaptcha/api/siteverify'. '?secret=' . $recaptchaSecret . '&response=' . $recaptchaResponse . 'remoteip=' . $clientIPAdress);
  75.             $recaptcha json_decode($recaptcha);
  76.             if ($recaptcha->success == false)
  77.             {
  78.                 print_r($recaptcha);
  79.                 print($clientIPAdress);
  80.                 print_r($recaptchaResponse);
  81.                 // print_r($recaptchaResponse2);
  82.                 die;
  83.                 // $errorMessage = $recaptcha->error-codes;
  84.                 $this->addFlash(
  85.                     'error',
  86.                     'Chyba při ověřování uživatele, reCAPTCHAerror, zkuste prosím registraci později.'
  87.                 );
  88.                 return $this->redirectToRoute('app_login');
  89.             }
  90.             print_r($recaptcha);
  91.             if ($recaptcha->success)
  92.             {
  93.                 $hash $this->encoder->encodePassword($user$user->getPassword());
  94.                 $user->setPassword($hash)
  95.                      ->setRoles(['ROLE_USER']);
  96.                 $this->userRepository->newUser($user);
  97.                 $url $this->getFullUrl($this->router,
  98.                     $this->generateUrl('app_activate', ['token' => $user->getActivationToken()])
  99.                 );
  100.                 $this->sendLinkByEmail('AKTIVACE ÚČTU',
  101.                     $appParameters['Email']['no-reply'],
  102.                     $user->getEmail(),
  103.                     'emails/activate_account.html.twig',
  104.                     $url);
  105.                 $this->addFlash(
  106.                     'success',
  107.                     'Registrace proběhla úspěšně. Na váš email jsem vám zaslali aktivační link.'
  108.                 );
  109.                 return $this->redirectToRoute('app_login');
  110.             }
  111.         }
  112.         return $this->render('security/registration.html.twig',array('form' =>$form->createView(),'publicKeyCaptcha' => $publicKey ) );
  113.     }
  114.     /**
  115.      * @param $token
  116.      * @Route ("/aktivace-uctu={token}", name="app_activate")
  117.      */
  118.     public function activateAccount($token) : Response
  119.     {
  120.         $user $this->userRepository->findOneBy(['activationToken' => $token]);
  121.         if(!$user)
  122.             return $this->redirectToRoute('app_login',['activation' => false]);
  123.         $user
  124.             ->setActive(true)
  125.             ->setActivationToken(null);
  126.         $this->userRepository->update($user);
  127.         $this->addFlash(
  128.             'success',
  129.             'Učet byl úspěšně aktivován'
  130.         );
  131.         return $this->redirectToRoute('app_login');
  132.     }
  133.     /**
  134.      * @return Response
  135.      * @Route ("/poslat-znovu-aktivacni-email", name="app_activate_again")
  136.      */
  137.     public function sendActivationTokenAgain(Request $request)
  138.     {
  139.         $form $this->createForm(ActivationTokenAgainType::class);
  140.         $form->handleRequest($request);
  141.         if ($form->isSubmitted() && $form->isValid())
  142.         {
  143.             $email $form->get('email')->getData();
  144.             $user $this->userRepository
  145.                 ->findOneBy(['email' => $email]);
  146.             if (!$user) {
  147.                 $this->addFlash(
  148.                     'error',
  149.                  'Uživatel s touto emailovou adresou nebyl nazelen.'
  150.                 );
  151.                 return $this->redirectToRoute('app_activate_again');
  152.             }
  153.             if ($user->isActive()) {
  154.                 $this->addFlash(
  155.                     'error',
  156.                     'Učet byl již aktivován !'
  157.                 );
  158.                 return $this->redirectToRoute('app_activate_again');
  159.             }
  160.             $token $this->userRepository
  161.                 ->setNewActivationToken($user);
  162.             if (!$token) {
  163.                 $this->addFlash(
  164.                     'warning',
  165.                     'Autorizační token je možné vygenerovat jednou za půl hodiny.'
  166.                 );
  167.                 return $this->redirectToRoute('app_activate_again');
  168.             }
  169.             $url $this->getFullUrl$this->router,
  170.                 $this->generateUrl('app_activate',['token' => $token])
  171.             );
  172.             $appParameters $this->loadAppParameters();
  173.             $this->sendLinkByEmail('AKTIVACE ÚČTU',
  174.                 $appParameters['Email']['no-reply'],
  175.                 $user->getEmail(),
  176.                 'emails/activate_account.html.twig',
  177.                 $url);
  178.             $this->addFlash(
  179.                 'success',
  180.                      'Váš účet byl úspěšně vytvořen. Na vámi zadanou emailovou adresu jsme vám poslalí aktivační link'
  181.             );
  182.             return $this->redirectToRoute('app_login');
  183.         }
  184.         return $this->render('security/activation_token_again.html.twig',[ 'form' => $form->createView() ]);
  185.     }
  186.     /**
  187.      * @Route("/", name="app_login")
  188.      */
  189.     public function login(AuthenticationUtils $authenticationUtils): Response
  190.     {
  191.         if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
  192.             return $this->redirectToRoute('app_dashboard');
  193.         }
  194.         // get the login error if there is one
  195.         $error $authenticationUtils->getLastAuthenticationError();
  196.         // last username entered by the user
  197.         $lastUsername $authenticationUtils->getLastUsername();
  198.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  199.     }
  200.     /**
  201.      * @Route("/logout", name="app_logout")
  202.      */
  203.     public function logout()
  204.     {
  205.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  206.     }
  207.     public function sendLinkByEmail($subject,$from,$to,$template,$url)
  208.     {
  209.         $message = (new \Swift_Message($subject))
  210.             ->setFrom($from)
  211.             ->setTo($to)
  212.             ->setBody(
  213.                 $this->renderView(
  214.                     $template,
  215.                     ['url' => $url]
  216.                 ),
  217.                 'text/html'
  218.             )
  219.         ;
  220.         return $this->mailer->send($message);
  221.     }
  222.     /**
  223.      * @Route ("/zadost-zmena-hesla",name="app_forgotten_password")
  224.      */
  225.     public function forgottenPasswordRequest(Request $request)
  226.     {
  227.          $form $this->createForm(ForgottenPasswordType::class);
  228.          $form->handleRequest($request);
  229.          if ($form->isSubmitted() && $form->isValid())
  230.          {
  231.              $email $form->get('email')->getData();
  232.              $user $this->userRepository
  233.                           ->findOneBy(['email' => $email]);
  234.              if (!$user) {
  235.                  $this->addFlash(
  236.                      'error',
  237.                      'Uživatel s touto emailovou adresou nebyl nazelen.'
  238.                  );
  239.                  return  $this->redirectToRoute('app_forgotten_password');
  240.              }
  241.              $token $this->userRepository
  242.                            ->setNewForgottenToken($user);
  243.              if ($token == false) {
  244.                  $this->addFlash(
  245.                      'warning',
  246.                      'O změnu hesla je možne požádat každých 30 minut'
  247.                  );
  248.                  return  $this->redirectToRoute('app_forgotten_password');
  249.              }
  250.              $url $this->getFullUrl$this->router,
  251.                  $this->generateUrl('app_change_password',['token' => $token])
  252.              );
  253.              $appParameters $this->loadAppParameters();
  254.              $emailStatus $this->sendLinkByEmail('ZMĚNA HESLA',
  255.                                             $appParameters['Email']['no-reply'],
  256.                                             $user->getEmail(),
  257.                                    'emails/forgotten_password.html.twig',
  258.                                            $url
  259.                                    );
  260.             if ($emailStatus == 0)
  261.             {
  262.                 $this->addFlash(
  263.                     'warning',
  264.                     'Chyba při odesílání emailu'
  265.                 );  
  266.             }
  267.             elseif ($emailStatus 0)
  268.             {
  269.                 $this->addFlash(
  270.                     'success',
  271.                     'Email ke změně hesla byl úspěšně odeslán. Zkontrolujte si emailovou schránku'
  272.                 );
  273.             }
  274.             else
  275.             {
  276.                 $this->addFlash(
  277.                     'warning',
  278.                     'Neznámý chybový stav (email)'
  279.                 ); 
  280.             }
  281.              return $this->redirectToRoute('app_login');
  282.          }
  283.          return $this->render('security/forgotten_password.html.twig',['form' => $form->createView()]);
  284.     }
  285.     /**
  286.      * @Route ("/zmena-hesla={token}",name="app_change_password")
  287.      */
  288.     public function changePassword($tokenRequest $request)
  289.     {
  290.         $user $this->userRepository
  291.                      ->findOneBy(['lostPasswordToken' => $token]);
  292.         if (!$user) {
  293.             $this->addFlash(
  294.                 'error',
  295.              'Autorizační token není možné najít'
  296.             );
  297.             return $this->redirectToRoute('app_login');
  298.         }
  299.         $form $this->createForm(ChangePasswordType::class,$user);
  300.         $form->handleRequest($request);
  301.         if ($form->isSubmitted() && $form->isValid())
  302.         {
  303.             $password $form->get('password')->getData();
  304.             $hash $this->encoder->encodePassword($user$password);
  305.             $user->setPassword($hash);
  306.             $this->userRepository->update($user);
  307.             $this->addFlash(
  308.                 'success',
  309.                 'Vaše heslo bylo uspěšně změněno. Můžete se přihlásit'
  310.             );
  311.             return $this->redirectToRoute('app_login');
  312.         }
  313.         return $this->render('security/forgotten_password_change.html.twig',['form' => $form->createView()]);
  314.     }
  315.     /**
  316.      * @Route("/profil", name="app_editProfile")
  317.      */
  318.     public function editProfile(Request $request,SluggerInterface $slugger)
  319.     {
  320.         $profile $this->userRepository->find($this->getUser()->getId());
  321.         $signExists is_null($profile->getSign()) ? true false;
  322.         if (is_null($profile)) {
  323.             $this->addFlash(
  324.                 'error',
  325.                 'Tohoto uživatele není možné najít'
  326.             );
  327.             return $this->redirectToRoute('app_registration');
  328.         }
  329.         $form $this->createForm(ProfileType::class,$profile,['signNotExist' => $signExists]);
  330.         $form->handleRequest($request);
  331.         if ($form->isSubmitted() && $form->isValid()) {
  332.             $signatureFile $form->get('signatureFile')->getData();
  333.             if (!empty($signatureFile)) {
  334.                 $fileInfo getimagesize($signatureFile);
  335.                 $signValid $this->imageValidate($fileInfo,array('width' =>300,'height' =>100 ));
  336.                 if ($signValid['valid'] == false)
  337.                 {
  338.                     $this->addFlash(
  339.                         'error',
  340.                              $signValid['message']
  341.                     );
  342.                     return $this->redirectToRoute('app_editProfile');
  343.                 }
  344.                 // smaze se puvodni soubor s podpisem
  345.                 $oldSign $profile->getSign();
  346.                 if ($oldSign) {
  347.                     $this->remove($this->getParameter('dir_signatures') . '/' $oldSign);
  348.                 }
  349.                 $originalFilename pathinfo($signatureFile->getClientOriginalName(), PATHINFO_FILENAME);
  350.                 $safeFilename $slugger->slug($originalFilename);
  351.                 $newFilename $safeFilename.'-'.uniqid().'.'.$signatureFile->guessExtension();
  352.                 try {
  353.                     $signatureFile->move(
  354.                         $this->getParameter('dir_signatures'),
  355.                         $newFilename
  356.                     );
  357.                     $profile->setSign($newFilename);
  358.                 } catch (FileException $e) {
  359.                     // ... handle exception if something happens during file upload
  360.                 }
  361.             }
  362.             $password $form->get('password')->getData();
  363.             if (!empty($password)) {
  364.                 $hash $this->encoder->encodePassword($profile$password);
  365.                 $profile->setPassword($hash);
  366.             }
  367.             $this->userRepository->update($profile);
  368.             $this->addFlash('success','Profil aktualizován');
  369.             return $this->redirectToRoute('app_editProfile');
  370.         }
  371.         return $this->render('security/profile.html.twig',['form' => $form->createView()]);
  372.     }
  373. }