src/Controller/Business/RegistrationController.php line 108

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Business;
  3. use App\Entity\PackageOrder;
  4. use App\Entity\User;
  5. use App\Form\ChangePasswordFormType;
  6. use App\Form\ForgottenFormType;
  7. use App\Form\RegistrationFormType;
  8. use App\Repository\PackageRecipeRepository;
  9. use App\Repository\UserRepository;
  10. use App\Security\LoginFormAuthenticator;
  11. use App\Services\Mailer\PingyMailer;
  12. use App\Services\Package\PackageOrderFactory;
  13. use Exception;
  14. use JMS\Serializer\Tests\Fixtures\Order;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  16. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  17. use Symfony\Component\HttpFoundation\RedirectResponse;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\HttpFoundation\Session\Flash\FlashBag;
  21. use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
  22. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  25. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  26. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  27. use Symfony\Component\Security\Core\User\UserProviderInterface;
  28. use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
  29. use function array_diff;
  30. class RegistrationController extends AbstractController
  31. {
  32.     /**
  33.      * @Route("/verify/{id}/{hash}", name="app_registration_verify")
  34.      *
  35.      * @param \Symfony\Component\HttpFoundation\Request $request
  36.      * @return \Symfony\Component\HttpFoundation\Response
  37.      */
  38.     public function verify(Request $request,
  39.                            UserRepository $userRepository,
  40.                            UserProviderInterface $userProvider,
  41.                            GuardAuthenticatorHandler $guardHandler,
  42.                            LoginFormAuthenticator $authenticator,
  43.                            PingyMailer $pingyMailer,
  44.                            TokenStorageInterface $tokenStorage,
  45.                            $id,
  46.                            $hash)
  47.     {
  48.         $user $userRepository->findOneBy([
  49.             'validationhash' => $hash,
  50.             'id' => (int)$id,
  51.             'approved' => User::WAITING_FOR_APPROVING
  52.         ]);
  53.         if(!$user){
  54.             return $this->redirectToRoute('shoppingmall_index', []);
  55.         }
  56.         // Do not get the User's Id or Email Address from the Request object
  57.         try {
  58.             $userHash $user->getValidationhash();
  59.             if ($userHash === $hash){
  60.                 $user->setRoles(['ROLE_USER'])
  61.                 ->setApproved(User::IS_APPROVED);
  62.                 $this->getDoctrine()->getManager()->flush();
  63.                 $orders $user->getPackageOrders();
  64.                 /** @var PackageOrder $order */
  65.                 foreach ($orders as $order) {
  66.                     if ($order->getStatus() == PackageOrder::WAITING_FOR_CONFIRM_ACCOUNT) {
  67.                         //return new RedirectResponse($this->generateUrl('packages_billing_info'));
  68.                         $request->getSession()->set('_security.main.target_path'$this->generateUrl('packages_billing_info'));
  69.                     }
  70.                 }
  71.                 return $guardHandler->authenticateUserAndHandleSuccess(
  72.                     $user,
  73.                     $request,
  74.                     $authenticator,
  75.                     'main' // firewall name in security.yaml
  76.                 );
  77.             }else{
  78.                 throw new Exception('Validation hash error');
  79.             }
  80.         } catch (\Exception $e) {
  81.             $this->addFlash('error'$e->getMessage());
  82.             return $this->redirectToRoute('app_register');
  83.         }
  84.     }
  85.     /**
  86.      * @Route("/register", name="app_register")
  87.      * @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
  88.      */
  89.     public function register(
  90.         Request $request,
  91.         UserPasswordEncoderInterface $passwordEncoder,
  92.         GuardAuthenticatorHandler $guardHandler,
  93.         LoginFormAuthenticator $authenticator,
  94.         PingyMailer $pingyMailer): Response
  95.     {
  96.         $user = new User();
  97.         $form $this->createForm(RegistrationFormType::class, $user);
  98.         $form->handleRequest($request);
  99.         if ($form->isSubmitted() && $form->isValid()) {
  100.             // encode the plain password
  101.             $user->setPassword(
  102.                 $passwordEncoder->encodePassword(
  103.                     $user,
  104.                     $form->get('plainPassword')->getData()
  105.                 )
  106.             );
  107.             $hash md5(rand(010000) . rand(010000));
  108.             $user->setValidationhash($hash);
  109.             // User is registered, but not allowed like common user
  110.             $user->setRoles(['ROLE_REGISTERED']);
  111.             $entityManager $this->getDoctrine()->getManager();
  112.             $entityManager->persist($user);
  113.             $entityManager->flush();
  114.             $pingyMailer->registered($user->getEmail(), [
  115.                 'userId' => $user->getId(),
  116.                 'hash' => $user->getValidationhash()
  117.             ]);
  118.             // do anything else you need here, like send an email
  119.             return $guardHandler->authenticateUserAndHandleSuccess(
  120.                 $user,
  121.                 $request,
  122.                 $authenticator,
  123.                 'main' // firewall name in security.yaml
  124.             );
  125.         }
  126.         return $this->render('admin/registration/register.html.twig', [
  127.             'registrationForm' => $form->createView(),
  128.             'errors' => $form->getErrors(true),
  129.             'error' => false
  130.         ]);
  131.     }
  132.     /**
  133.      * @Route("/createXYZ", name="app_register_xyz")
  134.      * @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
  135.      */
  136.     public function registerxyz(
  137.         Request $request,
  138.         UserPasswordEncoderInterface $passwordEncoder,
  139.         GuardAuthenticatorHandler $guardHandler,
  140.         LoginFormAuthenticator $authenticator,
  141.         PackageOrderFactory $packageOrderFactory,
  142.         PackageRecipeRepository $packageRecipeRepository,
  143.         UserRepository $userRepository,
  144.         PingyMailer $pingyMailer): Response
  145.     {
  146. //        $user = new User();
  147. //        $password = "H4#!?f_34";
  148. //        $email = 'lara_mkdad@deichmann.com';
  149. //
  150. //        $user->setEmail($email);
  151. ////        $form = $this->createForm(RegistrationFormType::class, $user);
  152. ////        $form->handleRequest($request);
  153. //
  154. //        //if ($form->isSubmitted() && $form->isValid()) {
  155. //            // encode the plain password
  156. //            $user->setPassword(
  157. //                $passwordEncoder->encodePassword(
  158. //                    $user,
  159. //                    $password
  160. //                )
  161. //            );
  162. //
  163. //            $hash = md5(rand(0, 10000) . rand(0, 10000));
  164. //            $user->setValidationhash($hash);
  165. //            // User is registered, but not allowed like common user
  166. //            $user->setRoles(['ROLE_USER']);
  167. //            $user->setAgree(true);
  168. //            $user->setApproved(User::IS_APPROVED);
  169. //
  170. //            $entityManager = $this->getDoctrine()->getManager();
  171. //            $entityManager->persist($user);
  172. //            $entityManager->flush();
  173.             $user $userRepository->findOneBy(['id' => 101]);
  174.             $recipeCodes = [
  175.                 'FreePackage',
  176.                 'GermanyPackage',
  177.                 'CzechiaPackage',
  178.                 'AustriaPackage',
  179.                 'SlovakiaPackage',
  180.                 'SwitzerlandPackage',
  181.                 'OutletsPackage',
  182.                 'PolandPackage',
  183.                 'DenmarkPackage',
  184.             ];
  185.             $recipes $packageRecipeRepository->findBy(['class_name' => $recipeCodes]);
  186.             $recipeIds = [];
  187.             foreach($recipes as $oneRec){
  188.                 $recipeIds[] = $oneRec->getId();
  189.             }
  190.             $packageOrder $packageOrderFactory->createByPackageIds($recipeIdsnull);
  191.             $packageOrder->setOrderNumber(time().rand(09999));
  192.             $packageOrder->setStatus(PackageOrder::PAID);
  193.             $user->addPackageOrder($packageOrder);
  194.             $this->getDoctrine()->getManager()->flush();
  195.             //$pingyMailer->confirmedOrder($user->getEmail());
  196. //            $pingyMailer->registered($user->getEmail(), [
  197. //                'userId' => $user->getId(),
  198. //                'hash' => $user->getValidationhash()
  199. //            ]);
  200. //            echo $password."<br />";
  201. //            echo $email;
  202.             exit('');
  203.             // do anything else you need here, like send an email
  204. //            return $guardHandler->authenticateUserAndHandleSuccess(
  205. //                $user,
  206. //                $request,
  207. //                $authenticator,
  208. //                'main' // firewall name in security.yaml
  209. //            );
  210. //        //}
  211. //
  212. //        return $this->render('admin/registration/register.html.twig', [
  213. //            'registrationForm' => $form->createView(),
  214. //            'errors' => $form->getErrors(true),
  215. //            'error' => false
  216. //        ]);
  217.     }
  218.     /**
  219.      * @Route("/change-password", name="app_change_password")
  220.      */
  221.     public function changePassword(Request $requestUserPasswordEncoderInterface $passwordEncoderGuardAuthenticatorHandler $guardHandlerLoginFormAuthenticator $authenticator): Response
  222.     {
  223.         $form $this->createForm(ChangePasswordFormType::class);
  224.         $form->handleRequest($request);
  225.         if ($form->isSubmitted() && $form->isValid()) {
  226.             $user $this->getUser();
  227.             if(!$user)
  228.                 return $this->redirectToRoute('app_login');
  229.             // encode the plain password
  230.             $user->setPassword(
  231.                 $passwordEncoder->encodePassword(
  232.                     $user,
  233.                     $form->get('plainPassword')->getData()
  234.                 )
  235.             );
  236.             // User is registered, but not allowed like common user
  237.             $currRoles $user->getRoles();
  238.             $newRoles array_diff($currRoles, ['ROLE_RESET_PASSWORD']);
  239.             $user->setRoles($newRoles);
  240.             $entityManager $this->getDoctrine()->getManager();
  241.             $entityManager->flush();
  242.             // do anything else you need here, like send an email
  243.             return $this->redirectToRoute('app_logout');
  244.         }
  245.         return $this->render('admin/security/changePassword.html.twig', [
  246.             'changePasswordForm' => $form->createView(),
  247.             'errors' => $form->getErrors(true),
  248.             'error' => false
  249.         ]);
  250.     }
  251.     /**
  252.      * @Route("/forgotten-password", name="app_forgotten_password")
  253.      * @IsGranted("IS_AUTHENTICATED_ANONYMOUSLY")
  254.      */
  255.     public function forgottenPassword(Request $requestPingyMailer $pingyMailerUserPasswordEncoderInterface $passwordEncoder): Response
  256.     {
  257.         $form $this->createForm(ForgottenFormType::class);
  258.         $form->handleRequest($request);
  259.         if ($form->isSubmitted() && $form->isValid()) {
  260.             $data $form->getData();
  261.             $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  262.                 'email' => $data['email']
  263.             ]);
  264.             if(!$user)
  265.                 throw new Exception('User has not been found');
  266.             $randomPassword substr(sha1(random_bytes(10)), 08);
  267.             $user->setPassword(
  268.                 $passwordEncoder->encodePassword(
  269.                     $user,
  270.                     $randomPassword
  271.                 )
  272.             );
  273.             $roles $user->getRoles();
  274.             $roles[] = 'ROLE_RESET_PASSWORD';
  275.             $user->setRoles($roles);
  276.             $em $this->getDoctrine()->getManager();
  277.             $em->flush();
  278.             // encode the plain password
  279.             try {
  280.                 $pingyMailer->forgottenPassword($user->getEmail(), ['password' => $randomPassword]);
  281.             }catch (Exception $e){
  282.             }
  283.             $this->addFlash('INFO''Your password has been reset. Check your email address.');
  284.             return $this->redirectToRoute('app_login');
  285.         }
  286.         return $this->render('admin/security/forgotten.html.twig', [
  287.             'forgottenForm' => $form->createView(),
  288.             'errors' => $form->getErrors(true),
  289.             'error' => false
  290.         ]);
  291.     }
  292.     /**
  293.      * @Route("/registered", name="app_registered")
  294.      *
  295.      * @param \Symfony\Component\HttpFoundation\Request $request
  296.      * @return \Symfony\Component\HttpFoundation\Response
  297.      */
  298.     public function registered(Request $requestSessionInterface $sessionPackageOrderFactory $packageOrderFactoryPingyMailer $pingyMailer){
  299.         $roles $this->getUser()->getRoles();
  300.         if(in_array('ROLE_USER'$roles)){
  301.             return $this->redirectToRoute('shoppingmall_index');
  302.         }
  303.         $recipeIds $session->get(PackagesController::ORDERED_PACKAGES, []);
  304.         if(count($recipeIds) > 0){
  305.             // bylo objednano balicky - udelam objednavku do statusu waiting - nasledne bude prevedeno po potvrzeni uctu
  306.             $recipeIds $session->get(PackagesController::ORDERED_PACKAGES, []);
  307.             $packageOrder $packageOrderFactory->createByPackageIds($recipeIds);
  308.             $packageOrder->setOrderNumber(time().rand(09999));
  309.             $packageOrder->setStatus(PackageOrder::WAITING_FOR_CONFIRM_ACCOUNT);
  310.             $this->getUser()->addPackageOrder($packageOrder);
  311.             $this->getDoctrine()->getManager()->flush();
  312.             $session->set(PackagesController::ORDERED_PACKAGES, []);
  313. //            $pingyMailer->confirmedOrder($this->getUser()->getEmail());
  314.         }
  315.         return $this->render('admin/registration/registered.html.twig');
  316.     }
  317. }