src/Controller/UsersControllerFrontend.php line 59

  1. <?php
  2. namespace App\Controller;
  3. use App\Form\UsersEditType;
  4. use App\Form\UsersRegisterType;
  5. use App\Entity\Users;
  6. use Doctrine\ORM\OptimisticLockException;
  7. use Doctrine\Persistence\ManagerRegistry;
  8. use Exception;
  9. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\JsonResponse;
  13. use Symfony\Component\HttpFoundation\RedirectResponse;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  17. use App\Manager\UserManager;
  18. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  19. use BeSimple\I18nRoutingBundle\Routing\Annotation\I18nRoute;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. class UsersControllerFrontend extends AbstractController
  22. {
  23.     public TranslatorInterface $translator;
  24.     public function __construct(TranslatorInterface $translator, private ManagerRegistry $managerRegistry, private TokenStorageInterface $usageTrackingTokenStorage)
  25.     {
  26.         $this->translator $translator;
  27.     }
  28.     /**
  29.      * Methods enable translation of error|notice flash messages.
  30.      *
  31.      * @param $key
  32.      * @param array $params
  33.      * @param null $domain
  34.      * @return mixed
  35.      */
  36.     public function trans($key, array $params = [], $domain null)
  37.     {
  38.         return $this->translator->trans($key$params$domain);
  39.     }
  40.     public function addFlashMessage($type$key, array $params = [], $domain null){
  41.         $this->addFlash($type$this->trans($key$params$domain));
  42.     }
  43.     /**
  44.      * @param Request $request
  45.      * @param UserPasswordHasherInterface $passwordEncoder
  46.      * @return RedirectResponse|Response
  47.      * @throws Exception
  48.      */
  49.     #[Route(path'/register'name'user_registration'methods: ['GET''POST'])]
  50.     public function registerAction(Request $requestUserPasswordHasherInterface $passwordEncoderUserManager $userManager)
  51.     {
  52.         // 1) build the form
  53.         $user = new Users();
  54.         $form $this->createForm(UsersRegisterType::class, $user);
  55.         // 2) handle the submit (will only happen on POST)
  56.         $form->handleRequest($request);
  57.         if ($form->isSubmitted() && $form->isValid()) {
  58.             $randomBytes random_bytes(32);
  59.             $user->setSalt(bin2hex($randomBytes));
  60.             //check for passwd length
  61.             $psswdErr FALSE;
  62.             if(!$userManager->hasPasswordMinimalLength($user->getPlainPassword())) {
  63.                 $this->addFlashMessage('error''profile_short_psswd', [], 'controller');
  64.                 $psswdErr TRUE;
  65.             }
  66.             if(!$userManager->isPasswordStrength($user->getPlainPassword(), $user->getUserIdentifier(), $user->getEmail(), $user->getFirstName().$user->getLastName())) {
  67.                 $this->addFlashMessage('error''profile_weak_psswd', [], 'controller');
  68.                 $psswdErr TRUE;
  69.             }
  70.             if($psswdErr){
  71.                 return $this->render(
  72.                     'frontend/registration.html.twig',
  73.                     array('form' => $form)
  74.                 );
  75.             }
  76.             //check for strength of password
  77.             // 3) Encode the password (you could also do this via Doctrine listener)
  78.             $password $passwordEncoder->hashPassword($user$user->getPlainPassword());
  79.             $user->setPassword($password);
  80.             //      $user->setUsername($user->getEmail());
  81.             //$user->setUsername($user->getEmail());
  82.             $user->setAuthRole('ROLE_USER');
  83.             $user->setCreatedAt(new \DateTime());
  84.             $user->setLastvisitAt(new \DateTime());
  85.             //$user->setLastmodAt(new \DateTime());  // nevim proc ale nefunguje auto current
  86.             $user->setUsers($user);
  87.             // 4) save the User!
  88.             $em $this->managerRegistry->getManager();
  89.             $em->persist($user);
  90.             $em->flush();
  91.             // ... do any other work - like sending them an email, etc
  92.             // maybe set a "flash" success message for the user
  93.             $this->addFlashMessage('notice''profile_created', [], 'controller');
  94.             // autologin https://stackoverflow.com/questions/5886713/automatic-post-registration-user-authentication
  95.             $token = new UsernamePasswordToken($user'main'$user->getRoles());
  96.             $this->usageTrackingTokenStorage->setToken($token);
  97.             $request->getSession()->set('_security_main'serialize($token));
  98.             $request->getSession()->set('player_id'$user->getId());
  99.             return $this->redirectToRoute('homepage');
  100.         } else {
  101.             $form->getErrors();
  102.         }
  103.         return $this->render(
  104.             'frontend/registration.html.twig',
  105.             array('form' => $form)
  106.         );
  107.     }
  108.     /**
  109.      * @param Request $request
  110.      * @param UserPasswordHasherInterface $passwordEncoder
  111.      * @return Response
  112.      * @throws OptimisticLockException
  113.      */
  114.     #[Route(path'/profile/edit/'name'user-edit'methods: ['GET''POST'])]
  115.     public function editAction(Request $requestUserPasswordHasherInterface $passwordEncoderUserManager $userManager)
  116.     {
  117.         $em $this->managerRegistry->getManager();
  118.         if(!$user $this->getUser()) {
  119.             return $this->redirectToRoute('login');
  120.         }
  121.         /* possible options - TextType?
  122.          "action", "allow_extra_fields", "attr", "auto_initialize", "block_name", "by_reference", "compound", "constraints", "csrf_field_name", "csrf_message", "csrf_protection", "csrf_token_id", "csrf_token_manager",
  123.         "data", "data_class", "disabled", "empty_data", "error_bubbling", "error_mapping", "extra_fields_message", "inherit_data", "invalid_message", "invalid_message_parameters",
  124.         "label", "label_attr", "label_format", "mapped", "method", "post_max_size_message", "property_path", "required", "translation_domain", "trim", "upload_max_size_message", "validation_groups".
  125.          */
  126.         $form $this->createForm(UsersEditType::class, $user);
  127.         $form->handleRequest($request);
  128.         if ($form->isSubmitted() && $form->isValid()) {
  129.             $user $form->getData();
  130.             $psswdErr FALSE;
  131.             $otherErr false;
  132.             if($user->getPlainPassword()) {
  133.                 if(!$userManager->isPasswordStrength($user->getPlainPassword(), $user->getUsername(), $user->getEmail(), $user->getFirstName().$user->getLastName())) {
  134.                     $this->addFlashMessage('error''profile_weak_psswd', [], 'controller');
  135.                     $psswdErr TRUE;
  136.                 }
  137.                 if(!$userManager->hasPasswordMinimalLength($user->getPlainPassword())) {
  138.                     $this->addFlashMessage('error''profile_short_psswd', [], 'controller');
  139.                     $psswdErr TRUE;
  140.                 }
  141.                 if($psswdErr) {
  142.                     //error password length
  143.                     $this->addFlashMessage('error''profile_short_psswd', [], 'controller');
  144.                 }
  145.                 $randomBytes random_bytes(32);
  146.                 $user->setSalt(bin2hex($randomBytes));
  147.                 $password $passwordEncoder->hashPassword($user$user->getPlainPassword());
  148.                 $user->setPassword($password);
  149.             }
  150.             if(strlen($user->getPersonalNumber()) > 64) {
  151.                 $this->addFlashMessage('error''error.profile_personal_number_too_long', [], 'controller');
  152.                 $otherErr TRUE;
  153.             }
  154.             if($psswdErr || $otherErr) {
  155.                 return $this->render('frontend/user_edit.html.twig', [
  156.                     'user' => $user,
  157.                     'form' => $form
  158.                 ]);
  159.             }
  160.             $user->setLastmodAt(new \DateTime());
  161.             $user->setUsers($user);
  162.             //$em->persist($user);
  163.             $em->flush($user);
  164.             $this->addFlashMessage('notice''user_update_success', [], 'controller');
  165.             return $this->redirectToRoute('user-detail');
  166.         } else {
  167.             // dump( $form->getErrors() );
  168.             if ($form->isSubmitted() && !$form->isValid()) {
  169.                 $form->getErrors();
  170.             }
  171.         }
  172.         return $this->render('frontend/user_edit.html.twig', [
  173.             'user' => $user,
  174.             'form' => $form
  175.         ]);
  176.     }
  177.     /**
  178.      * @param Request $request
  179.      * @param UserPasswordHasherInterface $passwordEncoder
  180.      * @return RedirectResponse|Response
  181.      */
  182.     #[Route(path'/profile'name'user-detail'methods: ['GET'])]
  183.     public function detailAction(UserPasswordHasherInterface $passwordEncoder)
  184.     {
  185.         if(!$user $this->getUser()) {
  186.             return $this->redirectToRoute('login');
  187.         }
  188.         $user $this->getUser();
  189.         return $this->render('frontend/user_detail.html.twig', [
  190.             'user' => $user
  191.         ]);
  192.     }
  193.     /**
  194.      * Check password strength
  195.      *
  196.      * @return Response
  197.      */
  198.     #[Route(path'/check-password'name'userPasswordCheck'methods: ['GET'])]
  199.     public function checkPasswordAction(Request $requestTranslatorInterface $translatorUserManager $userManager): Response
  200.     {
  201.         //
  202.         $password $request->query->get('password''');
  203.         $email $request->query->get('email''');
  204.         $userName $request->query->get('userName''');
  205.         $name $request->query->get('name''');
  206.         $isCorrect 0;
  207.         if (!$userManager->hasPasswordMinimalLength($password)) {
  208.             $message $translator->trans('profile_short_psswd', [], 'controller');
  209.         } elseif (!$userManager->isPasswordStrength($password$userName$email$name)) {
  210.             $message $translator->trans('profile_weak_psswd', [], 'controller');
  211.         } else {
  212.             $isCorrect 1;
  213.             $message $translator->trans('profile_ok_psswd', [], 'controller');
  214.         }
  215.         $response = new JsonResponse();
  216.         $response->setData(array(
  217.             'isCorrect' => $isCorrect,
  218.             'message' => $message,
  219.         ));
  220.         return $response;
  221.     }
  222. }