src/Controller/AuthController.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  8. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  9. use App\Form\ForgotPasswordForm;
  10. use App\Form\ResetPasswordForm;
  11. use App\Repository\UserRepository;
  12. use App\Entity\UserForgot;
  13. use App\Service\FunctionService;
  14. use Doctrine\ORM\EntityManagerInterface;
  15. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  16. #[Route('/auth')]
  17. class AuthController extends AbstractController
  18. {
  19.     use TargetPathTrait;
  20.     #[Route('/'name'auth_login')]
  21.     public function login(Request $requestAuthenticationUtils $helper): Response
  22.     {
  23.         $this->saveTargetPath($request->getSession(), 'main'$this->generateUrl('dashboard_index'));
  24.         $error $helper->getLastAuthenticationError();
  25.         if($this->getUser()){
  26.             if (in_array('ROLE_ADMIN'$this->getUser()->getRoles(), true
  27.                 && $this->getUser()->getIsActive() == 1) {
  28.                 return $this->redirectToRoute('dashboard_index');
  29.             }else{
  30.                 $error 'Something went wrong. Please try again later.';
  31.             }
  32.         }
  33.         return $this->render('auth/login.html.twig', [
  34.             'last_username' => $helper->getLastUsername(),
  35.             'error' => $error,
  36.         ]);
  37.     }
  38.     /**
  39.      * This is the route the user can use to logout.
  40.      *
  41.      * But, this will never be executed. Symfony will intercept this first
  42.      * and handle the logout automatically. See logout in config/packages/security.yaml
  43.      */
  44.     #[Route('/logout'name'auth_logout')]
  45.     public function logout(): Response
  46.     {
  47.        // throw new \Exception('This should never be reached!');
  48.        return $this->redirectToRoute('auth', [], Response::HTTP_SEE_OTHER);
  49.         //return new RedirectResponse($this->urlGenerator->generate('app_homepage'))
  50.     }
  51.    /*  #[Route('/forgot-password', name: 'auth_forgot_password' , methods: ['GET','POST']) ]
  52.     public function forgotPassword(Request $request,UserRepository $usersRepository,FunctionService $functionService,EntityManagerInterface $entityManager, AuthenticationUtils $helper): Response
  53.     {
  54.         // if user is already logged in, don't display the login page again
  55.         if ($this->getUser() ) {
  56.             throw $this->createNotFoundException('Page not found');
  57.         }
  58.         $formSubmited = false;
  59.        // $userForgot = new UserForgot();
  60.         $form = $this->createForm(ForgotPasswordForm::class);
  61.         $form->handleRequest($request);
  62.         if ($form->isSubmitted() && $form->isValid()) {
  63.             //echo 'hi';exit;
  64.             $email = $form->get('email')->getData();
  65.             
  66.             if(!$usersRepository->loadUserByIdentifier($email)){
  67.                 $form->get('email')->addError(new \Symfony\Component\Form\FormError('No record found'));
  68.             }else {
  69.                 if ($this->isCsrfTokenValid('forgot-password', $request->request->get('_csrf_token'))) {
  70.                    // echo 'hi';exit;
  71.                     $userForgot = new \App\Entity\UserForgot();
  72.                     $user = $usersRepository->loadUserByIdentifier($email);
  73.                 // print_r($user);exit;
  74.                     $resetToken = $functionService->getRandCode(120);
  75.                     $userForgot->setUserId($user->getUserId());
  76.                     $userForgot->setCode($resetToken);
  77.                     $userForgot->setIsExpired(0);
  78.                     $userForgot->setCreatedAt(new \DateTime());
  79.                     $entityManager->persist($userForgot);
  80.                     $entityManager->flush();
  81.                     $formSubmited = true;
  82.                     //return $this->render('auth/forgot-password-message.html.twig');
  83.                 }
  84.                 
  85.                 
  86.             }
  87.         }
  88.         return $this->render('auth/forgot-password.html.twig', [
  89.             'form' => $form->createView(),
  90.             'formSubmitted' => $formSubmited,
  91.             'last_username' => $helper->getLastUsername(),
  92.         ]);
  93.     } */
  94.     #[Route('/reset-password/{token}'name'auth_reset_password'methods: ['GET','POST'])]
  95.     public function resetPassword($tokenRequest $request,UserRepository $usersRepository,FunctionService $functionService,EntityManagerInterface $entityManagerUserPasswordHasherInterface $passwordHasher): Response
  96.     {
  97.         // if user is already logged in, don't display the login page again
  98.         /* $user = $this->getUser();
  99.         if ($this->getUser() ) {
  100.             throw $this->createNotFoundException('Page not found');
  101.         } */
  102.         if ($this->getUser() ) {
  103.             throw $this->createNotFoundException('Page not found');
  104.         }
  105.         
  106.         //echo 'hi'; exit;
  107.         //$token = $request->query->get('token');
  108.         //$em = $this->getDoctrine()->getManager();
  109.         /* $tokenRepo = $em->getRepository(\App\Entity\UserForgot::class);*/
  110.         $userRepo $entityManager->getRepository(\App\Entity\User::class);
  111.         $user null;
  112.         $userforgot=$entityManager->getRepository(\App\Entity\UserForgot::class)->findOneBy(array('code' => $token));
  113.         if(!$userforgot) {
  114.             return $this->redirect($this->generateUrl('auth_login'));
  115.         }
  116.         //$authToken = $tokenRepo->findOneBy(['code' => $token]);
  117.         if (is_object($userforgot)) {
  118.             $user $userRepo->findOneBy(['userId' => $userforgot->getUserId(), 'isApproved' => true]);
  119.         }
  120.         
  121.         if (!is_object($user)) {
  122.             throw $this->createNotFoundException('Page not found');
  123.         }
  124.        // print_r($user);exit;
  125.         $formSubmited false;
  126.         //$form = $this->createForm(ResetPasswordForm::class);
  127.         $form $this->createForm(ResetPasswordForm::class);
  128.         $form->handleRequest($request);
  129.         if ($request->getMethod() == 'POST'){
  130.             $data $form->getData();
  131.            if(empty($data)){
  132.             $errors 'Passwords do not match';
  133.             return $this->render('auth/reset-password.html.twig',
  134.                     array('errors' => $errors
  135.                     'form' => $form->createView(), 
  136.                     'formSubmitted' => $formSubmited,
  137.                     'token' => $token,
  138.                 ));
  139.            }else{
  140.                 if ($form->isSubmitted() && $form->isValid()) {
  141.                     $password $form->get('password')->getData();
  142.                     $password $passwordHasher->hashPassword($user$password);
  143.                     $user->setPassword($password);
  144.                     // save the user
  145.                     $entityManager->persist($user);
  146.                     $entityManager->remove($userforgot);
  147.                     $entityManager->flush();
  148.                     $formSubmited true;
  149.                 }
  150.            }
  151.     
  152.             
  153.         }
  154.         //print_r($form);exit;
  155.        
  156.         return $this->render('auth/reset-password.html.twig', [
  157.             'form' => $form->createView(),
  158.             'formSubmitted' => $formSubmited,
  159.             'token' => $token,
  160.             'errors' => ''
  161.         ]);
  162.     }
  163. }