src/Controller/SecurityController.php line 40

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Annotation\CmsComponent;
  4. use App\Entity\User;
  5. use App\Form\ProfileType;
  6. use App\Form\UserChangePasswordType;
  7. use App\Form\UserProfileType;
  8. use App\Form\UserType;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  11. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  12. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  13. use Symfony\Component\Form\Extension\Core\Type\TextType;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. use Symfony\Component\Routing\Annotation\Route;
  17. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  18. class SecurityController extends AbstractController
  19. {
  20.     public function __construct(protected EntityManagerInterface $em, protected UserPasswordHasherInterface $hasher) {}
  21.     // //////////////////////////////////
  22.     // CMS USER PAGES
  23.     // ///////////////////////////////////
  24.     #[Route(path'/takeflight/login'name'control_login')]
  25.     public function login(AuthenticationUtils $authenticationUtils): \Symfony\Component\HttpFoundation\Response
  26.     {
  27.         // get the login error if there is one
  28.         $error $authenticationUtils->getLastAuthenticationError();
  29.         if ($error) {
  30.             $this->addFlash('error''Invalid Username or Password');
  31.         }
  32.         // last username entered by the user
  33.         $lastUsername $authenticationUtils->getLastUsername();
  34.         return $this->render('takeflight/login-control.html.twig', [
  35.             'last_username' => $lastUsername,
  36.         ]);
  37.     }
  38.     #[Route(path'/forgot-cms-password'name'forgot_cms_password')]
  39.     public function forgotCMSPassword(Request $request): \Symfony\Component\HttpFoundation\Response
  40.     {
  41.         $error null;
  42.         $data = [];
  43.         $form $this->createFormBuilder($data)
  44.             ->add('email'TextType::class, ['label' => 'Email Address''attr' => ['placeholder' => 'Email']])
  45.             ->getForm()
  46.         ;
  47.         $form->handleRequest($request);
  48.         if ($form->isSubmitted() && $form->isValid()) {
  49.             $data $form->getData();
  50.             $user $this->em->getRepository(User::class)->findOneByEmail($data['email']);
  51.             if ($user) {
  52.                 $url_encrypt substr(md5(random_int(0999).'5h0rtt3rmm3m0ry1055?'.random_int(0999)), 020);
  53.                 $user->setEmailresetkey($url_encrypt);
  54.                 $this->em->persist($user);
  55.                 $this->em->flush();
  56.                 $message = (new \Swift_Message())
  57.                     ->setSubject('CMS Password reset request for '.$this->getParameter('sitename'))
  58.                     ->setFrom($this->getParameter('email_norely'))
  59.                     ->setTo($user->getEmail())
  60.                     ->setBody(
  61.                         $this->renderView('takeflight/email-password-reset.html.twig', [
  62.                             'url_encrypt' => $url_encrypt,
  63.                             'user' => $user,
  64.                         ]),
  65.                         'text/html'
  66.                     )
  67.                 ;
  68.                 $this->get('mailer')->send($message);
  69.             }
  70.             $this->addFlash('success''If an account is found with that email address then instructions to reset your password will be sent ');
  71.         }
  72.         return $this->render('takeflight/admin-forgot.html.twig', [
  73.             'form' => $form->createView(),
  74.             'error' => $error,
  75.         ]);
  76.     }
  77.     #[Route(path'/password-cms-reset/{url_encrypt}'name'password_cms_reset')]
  78.     public function passwordCMSReset(Request $requestmixed $url_encrypt)
  79.     {
  80.         $user $this->em->getRepository(User::class)->findOneByEmailresetkey($url_encrypt);
  81.         if (!$user) {
  82.             $this->addFlash('error''Email reset key not valid or has expired - please try to reset your password again.');
  83.             return $this->redirectToRoute('forgot_password');
  84.         }
  85.         if ($user) {
  86.             $error null;
  87.             $data = [];
  88.             $form $this->createFormBuilder($data)
  89.                 ->add('plainPassword'RepeatedType::class, [
  90.                     'type' => PasswordType::class,
  91.                     'invalid_message' => 'The password fields must match.',
  92.                     'first_options' => ['label' => 'Password'],
  93.                     'second_options' => ['label' => 'Repeat Password'],
  94.                 ])
  95.                 ->getForm()
  96.             ;
  97.             $form->handleRequest($request);
  98.             if ($form->isSubmitted() && $form->isValid()) {
  99.                 $data $form->getData();
  100.                 $password $this->hasher->hashPassword($user$data['plainPassword']);
  101.                 $user->setEmailresetkey(null);
  102.                 $user->setPassword($password);
  103.                 $this->em->persist($user);
  104.                 $this->em->flush();
  105.                 $this->addFlash('success''Your password has been reset');
  106.                 return $this->redirectToRoute('control_login');
  107.             }
  108.             return $this->render('takeflight/admin-reset.html.twig', [
  109.                 'form' => $form->createView(),
  110.                 'error' => $error,
  111.                 'url_encrypt' => $url_encrypt,
  112.             ]);
  113.         }
  114.     }
  115.     #[Route(path'/takeflight/user/create'name'admin_create')]
  116.     public function adminCreate(Request $request)
  117.     {
  118.         $user = new User();
  119.         $form $this->createForm(UserType::class, $user);
  120.         $form->handleRequest($request);
  121.         if ($form->isSubmitted() && $form->isValid()) {
  122.             $password $this->hasher->hashPassword($user$user->getPlainPassword());
  123.             $user->setPassword($password);
  124.             $user->setRoles([
  125.                 'ROLE_ADMIN',
  126.             ]);
  127.             $this->em->persist($user);
  128.             $this->em->flush();
  129.             $this->addFlash('success''User Created Successfully');
  130.             return $this->redirectToRoute('control_dash');
  131.         }
  132.         return $this->render('takeflight/admin-create.html.twig', [
  133.             'form' => $form->createView(),
  134.         ]);
  135.     }
  136.     #[Route(path'/takeflight/user/profile'name'control_profile')]
  137.     public function adminProfile(Request $request)
  138.     {
  139.         // 1) build the form
  140.         $user $this->getUser();
  141.         $form $this->createForm(ProfileType::class, $user);
  142.         // 2) handle the submit (will only happen on POST)
  143.         $form->handleRequest($request);
  144.         if ($form->isSubmitted() && $form->isValid()) {
  145.             // $user->resizeImage($this->get('image.handling'));
  146.             $this->em->persist($user);
  147.             $this->em->flush();
  148.             $this->addFlash('success''Profile Updated Successfully');
  149.             return $this->redirectToRoute('control_profile');
  150.         }
  151.         return $this->render('takeflight/admin-profile.html.twig', [
  152.             'form' => $form->createView(),
  153.             'user' => $user,
  154.         ]);
  155.     }
  156.     #[Route(path'/takeflight/admin_check'name'control_check')]
  157.     public function adminCheck() {}
  158.     // route is handled by the Security system
  159.     // //////////////////////////////////
  160.     // MEMBER PAGES
  161.     // ///////////////////////////////////
  162.     /**
  163.      * @CmsComponent("User Login", active=false, routeName="member_login")
  164.      */
  165.     #[Route(path'/member-login'name'member_login')]
  166.     public function loginMember(): \Symfony\Component\HttpFoundation\Response
  167.     {
  168.         $authenticationUtils $this->get('security.authentication_utils');
  169.         // get the login error if there is one
  170.         $error $authenticationUtils->getLastAuthenticationError();
  171.         // last username entered by the user
  172.         $lastUsername $authenticationUtils->getLastUsername();
  173.         return $this->render('@theme/members/members-login.html.twig', [
  174.             'last_username' => $lastUsername,
  175.             'error' => $error,
  176.         ]);
  177.     }
  178.     #[Route(path'/members/member_check'name'member_check')]
  179.     public function memberCheck() {}
  180.     // route is handled by the Security system
  181.     /**
  182.      * @CmsComponent("User Register", active=false, routeName="member_register")
  183.      */
  184.     #[Route(path'/member-register'name'member_register')]
  185.     public function userRegister(Request $request)
  186.     {
  187.         $user = new User();
  188.         $form $this->createForm(UserType::class, $user);
  189.         $form->handleRequest($request);
  190.         if ($form->isSubmitted() && $form->isValid()) {
  191.             $password $this->hasher->hashPassword($user$user->getPlainPassword());
  192.             $user->setPassword($password);
  193.             $user->setRoles(['ROLE_USER']);
  194.             $this->em->persist($user);
  195.             $this->em->flush();
  196.             $this->addFlash('success''User Created Successfully');
  197.             return $this->redirect('/');
  198.         }
  199.         return $this->render('@theme/members/members-register.html.twig', [
  200.             'form' => $form->createView(),
  201.         ]);
  202.     }
  203.     /**
  204.      * @CmsComponent("Member Password Reset", active=false, routeName="member_forgot_password")
  205.      */
  206.     #[Route(path'/member-forgot-password'name'member_forgot_password')]
  207.     public function forgotPassword(Request $request): \Symfony\Component\HttpFoundation\Response
  208.     {
  209.         $error null;
  210.         $data = [];
  211.         $form $this->createFormBuilder($data)
  212.             ->add('email'TextType::class, ['label' => 'Email Address''attr' => ['placeholder' => 'Email']])
  213.             ->getForm()
  214.         ;
  215.         $form->handleRequest($request);
  216.         if ($form->isSubmitted() && $form->isValid()) {
  217.             $data $form->getData();
  218.             $user $this->em->getRepository(User::class)->findOneByEmail($data['email']);
  219.             if (!$user) {
  220.                 $this->addFlash('error''Email Address not found');
  221.             }
  222.             if ($user) {
  223.                 $url_encrypt substr(md5(random_int(0999).'5h0rtt3rmm3m0ry1055?'.random_int(0999)), 020);
  224.                 $user->setEmailresetkey($url_encrypt);
  225.                 $this->em->persist($user);
  226.                 $this->em->flush();
  227.                 $resetUrl '/member-password-reset';
  228.                 $message = (new \Swift_Message())
  229.                     ->setSubject('Password reset request for '.$this->getParameter('sitename'))
  230.                     ->setFrom($this->getParameter('email_norely'))
  231.                     ->setTo($user->getEmail())
  232.                     ->setBody(
  233.                         $this->renderView('@theme/emails/forgot-password.html.twig', [
  234.                             'resetUrl' => $resetUrl,
  235.                             'url_encrypt' => $url_encrypt,
  236.                             'user' => $user,
  237.                         ]),
  238.                         'text/html'
  239.                     )
  240.                 ;
  241.                 $this->get('mailer')->send($message);
  242.                 $this->addFlash('success''An email has been sent with instructions to reset your password');
  243.             }
  244.             // return $this->redirect('/');
  245.         }
  246.         return $this->render('@theme/members/members-forgot.html.twig', [
  247.             'form' => $form->createView(),
  248.             'error' => $error,
  249.         ]);
  250.     }
  251.     #[Route(path'/member-password-reset/{url_encrypt}'name'member_password_reset')]
  252.     public function passwordReset(Request $requestmixed $url_encrypt)
  253.     {
  254.         $user $this->em->getRepository(User::class)->findOneByEmailresetkey($url_encrypt);
  255.         if (!$user) {
  256.             $this->addFlash('error''Email reset key not valid or has expired - please try to reset your password again.');
  257.             return $this->redirectToRoute('forgot_password');
  258.         }
  259.         if ($user) {
  260.             $error null;
  261.             $data = [];
  262.             $form $this->createFormBuilder($data)
  263.                 ->add('plainPassword'RepeatedType::class, [
  264.                     'type' => PasswordType::class,
  265.                     'invalid_message' => 'The password fields must match.',
  266.                     'first_options' => ['label' => 'Password'],
  267.                     'second_options' => ['label' => 'Repeat Password'],
  268.                 ])
  269.                 ->getForm()
  270.             ;
  271.             $form->handleRequest($request);
  272.             if ($form->isSubmitted() && $form->isValid()) {
  273.                 $data $form->getData();
  274.                 $password $this->hasher->hashPassword($user$data['plainPassword']);
  275.                 $user->setEmailresetkey(null);
  276.                 $user->setPassword($password);
  277.                 $this->em->persist($user);
  278.                 $this->em->flush();
  279.                 $this->addFlash('success''Your password has been reset');
  280.                 return $this->redirectToRoute('member_login');
  281.             }
  282.             return $this->render('@theme/members/members-reset.html.twig', [
  283.                 'form' => $form->createView(),
  284.                 'error' => $error,
  285.                 'url_encrypt' => $url_encrypt,
  286.             ]);
  287.         }
  288.     }
  289.     #[Route(path'/member/profile'name'member_profile')]
  290.     public function memberProfile(Request $request)
  291.     {
  292.         $user $this->getUser();
  293.         $form $this->createForm(ProfileType::class, $user);
  294.         $form->handleRequest($request);
  295.         if ($form->isSubmitted() && $form->isValid()) {
  296.             $this->em->persist($user);
  297.             $this->em->flush();
  298.             $this->addFlash('success''Profile Updated Successfully');
  299.             return $this->redirectToRoute('member_profile');
  300.         }
  301.         return $this->render('@theme/members/members-profile.html.twig', [
  302.             'form' => $form->createView(),
  303.             'user' => $user,
  304.         ]);
  305.     }
  306.     // /////////////////////////////////////////
  307.     // SECONDARY USER (MEMBER) PAGES : Seperated from admin and member users!
  308.     // Uses a completly different firewall setup
  309.     // Only used in very few circumstances - uses a seperate user table.
  310.     // I took the liberty to setup multiple security providers just in case we
  311.     // ever needed them - i think theres only been a couple of
  312.     // instances where this feature could of been used.
  313.     // THIS IS NOT FOR CMS USERS SO DONT MIX THEM WITH ADMIN OR MEMBER USERS!
  314.     //
  315.     // This should only be used for seperate public access to a site,
  316.     // i.e comments section profiles, register-to-access content or shop customers
  317.     // USE ONLY FOR NON CMS USERS - (due to foreign key constraints)
  318.     // ////////////////////////////////////////
  319.     #[Route(path'/user/user-check'name'user_login_check')]
  320.     public function loginCheck() {}
  321.     #[Route(path'/user/profile'name'user_profile')]
  322.     public function userProfile(Request $request)
  323.     {
  324.         $user $this->getUser();
  325.         $form $this->createForm(UserProfileType::class, $user);
  326.         $form->handleRequest($request);
  327.         if ($form->isSubmitted() && $form->isValid()) {
  328.             $this->em->persist($user);
  329.             $this->em->flush();
  330.             $this->addFlash('success''Profile Updated Successfully');
  331.             return $this->redirectToRoute('user_profile');
  332.         }
  333.         return $this->render('@theme/user/user-profile.html.twig', [
  334.             'form' => $form->createView(),
  335.             'user' => $user,
  336.         ]);
  337.     }
  338.     #[Route(path'/user/edit-password'name'user_edit_password')]
  339.     public function userEditPassword(Request $requestUserPasswordHasherInterface $hasher)
  340.     {
  341.         $user $this->getUser();
  342.         $editForm $this->createForm(UserChangePasswordType::class, $user);
  343.         $editForm->handleRequest($request);
  344.         if ($editForm->isSubmitted()) {
  345.             if ($editForm->isValid()) {
  346.                 $data $editForm->getData();
  347.                 $password $hasher->hashPassword($user$data->getPlainPassword());
  348.                 // @var User $user
  349.                 $user->setEmailresetkey(null);
  350.                 $user->setPassword($password);
  351.                 $this->em->persist($user);
  352.                 $this->em->flush();
  353.                 $this->addFlash('success''Success - User Credentials updated');
  354.                 return $this->redirectToRoute('user_profile');
  355.             }
  356.             $this->addFlash('error''Error - User not saved');
  357.         }
  358.         return $this->render('@theme/user/user-password.html.twig', [
  359.             'user' => $user,
  360.             'form' => $editForm->createView(),
  361.         ]);
  362.     }
  363.     #[Route(path'/logout'name'logout')]
  364.     public function logout() {}
  365.     // route is handled by the Security system
  366. }