src/Controller/SecurityController.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Form\{ForgotPasswordTypeResetPasswordType};
  5. use App\Repository\UserRepository;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  8. use Symfony\Component\HttpFoundation\{RequestResponse};
  9. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  10. use Symfony\Component\Routing\Annotation\Route;
  11. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  12. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  13. use Symfony\Component\Security\Core\Exception\UserNotFoundException;
  14. class SecurityController extends AbstractController
  15. {
  16.     #[Route(path'/login'name'app_login')]
  17.     public function login(AuthenticationUtils $helper): Response
  18.     {
  19.         $this->redirectLoggedInUsers();
  20.         return $this->render('security/login.html.twig', [
  21.             'last_username' => $helper->getLastUsername(),
  22.             'error' => $helper->getLastAuthenticationError()
  23.         ]);
  24.     }
  25.     #[Route(path'/logout'name'app_logout'methods: ['GET'])]
  26.     public function logout(): void
  27.     {
  28.     }
  29.     #[Route(path'/forgot-password'name'app_forgot')]
  30.     public function forgotPassword(Request $requestUserRepository $userRepoEntityManagerInterface $entityManager): Response
  31.     {
  32.         $this->redirectLoggedInUsers();
  33.         if ($request->isMethod('POST')) {
  34.             $token $request->request->get('g-recaptcha-response');
  35.             $responses $this->verifyGoogleRecaptcha($token);
  36.             if (!$responses['success']) {
  37.                 throw new UserNotFoundException();
  38.             }
  39.         }
  40.         $form $this->createForm(ForgotPasswordType::class);
  41.         $form->handleRequest($request);
  42.         if ($form->isSubmitted() && $form->isValid()) {
  43.             $user $userRepo->findOneByEmail($form->get('email')->getData());
  44.             if (!$user) {
  45.                 $this->addFlash('success''An email with a link reset password is your email address!');
  46.                 return $this->redirectToRoute('app_login');
  47.             }
  48.             $user->setToken(bin2hex(random_bytes(32)));
  49.             $entityManager->persist($user);
  50.             $entityManager->flush();
  51.             $link $this->generateUrl('user_reset_password', ['token' => $user->getToken()], UrlGeneratorInterface::ABSOLUTE_URL);
  52.             $html '';
  53.             $html .= "<html>";
  54.             $html .= "<body style='background-color:#ffffff;color:black;font-family:Arial, 'Helvetica Neue',Helvetica, sans-serif;font-size: 13px;'>";
  55.             $html .= "Click <a href='" $link "' target='_blank'>here</a> to reset your password. This link is valid for 5 minutes.</body>";
  56.             $html .= "</html>";
  57.             $arrParams '{"personalizations":[{"to":[{"email":"' $form->get('email')->getData() . '"}],"subject":"Hospital Management System - Reset Password"}],"content": [{"type": "text/html charset=utf-8", "value": "' $html '"}],"from":{"email":"' $_ENV['EMAIL_NOREPLY'] . '",
  58.             "name":"' $_ENV['EMAIL_FROM_NAME'] . '"}}';
  59.             $endpoint $_ENV['CNMGTS_API_MAIL_URL'];
  60.             $APItoken 'Bearer ' $_ENV['CNMGTS_API_MAIL_PASSWORD'];
  61.             $ch = @curl_init();
  62.             @curl_setopt($chCURLOPT_POSTtrue);
  63.             @curl_setopt($chCURLOPT_POSTFIELDS$arrParams);
  64.             @curl_setopt($chCURLOPT_URL$endpoint);
  65.             @curl_setopt($chCURLOPT_HTTPHEADER, array(
  66.                 'Authorization:' $APItoken,
  67.                 'Content-Type: application/json',
  68.             ));
  69.             @curl_setopt($chCURLOPT_TIMEOUT400);
  70.             @curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  71.             $response = @curl_exec($ch); //Log the response from HubSpot as needed.
  72.             @curl_close($ch);
  73.             if ($response) {
  74.                 $this->addFlash('error''Please try again');
  75.                 return $this->redirectToRoute('app_forgot');
  76.             } else {
  77.                 $this->addFlash('success''An email with a link reset password is your email address!');
  78.                 return $this->redirectToRoute('app_login');
  79.             }
  80.         }
  81.         return $this->renderForm('security/forgot.html.twig', [
  82.             'form' => $form
  83.         ]);
  84.     }
  85.     #[Route(path'/reset-password/{token}'name'user_reset_password')]
  86.     public function resetPassword(Request $requestUser $userstring $tokenUserPasswordHasherInterface $hasherUserRepository $userRepoEntityManagerInterface $entityManager): Response
  87.     {
  88.         $this->redirectLoggedInUsers();
  89.         $user $userRepo->findOneBy(['token' => $token'isActive' => true]);
  90.         $form $this->createForm(ResetPasswordType::class, $user);
  91.         $form->handleRequest($request);
  92.         if ($user) {
  93.             $getDate $userRepo->ExpiryToken($token);
  94.             $newTime date('Y-m-d H:i:s'strtotime('+5 minutes'strtotime($getDate)));
  95.             $time time();
  96.             if ($time strtotime($newTime)) {
  97.                 $this->addFlash('danger''Link expired! Please try again.');
  98.                 return $this->redirectToRoute('app_forgot');
  99.             } else {
  100.                 if ($form->isSubmitted() && $form->isValid()) {
  101.                     $first $request->request->get('reset_password')['password']['first'];
  102.                     $second $request->request->get('reset_password')['password']['second'];
  103.                     $formData $form->getData();
  104.                     $newPassword $user->getPassword();
  105.                     if (empty($first) && empty($second)) {
  106.                         return $this->renderForm('security/reset.html.twig', [
  107.                             'form' => $form,
  108.                             'error' => 'Password is required'
  109.                         ]);
  110.                     }
  111.                     if (preg_match('/^(?=.*\d)(?=.*[@#\-_$%^&+=§!\?])(?=.*[a-z])(?=.*[A-Z])[0-9A-Za-z@#\-_$%^&+=§!\?]{8,20}$/'$user->getPassword())) {
  112.                         if ($user->getPasswordMd5() != '' && $user->getPasswordMd5() == md5($newPassword)) {
  113.                             return $this->renderForm('security/reset.html.twig', [
  114.                                 'form' => $form,
  115.                                 'error' => 'Password should not be older password. please try again'
  116.                             ]);
  117.                         } elseif ($user->getPasswordOld1() != '' && ($user->getPasswordOld1() == md5($newPassword))) {
  118.                             return $this->renderForm('security/reset.html.twig', [
  119.                                 'form' => $form,
  120.                                 'error' => 'Password should not be older password. please try again'
  121.                             ]);
  122.                         } elseif ($user->getPasswordOld2() != '' && $user->getPasswordOld2() == md5($newPassword)) {
  123.                             return $this->renderForm('security/reset.html.twig', [
  124.                                 'form' => $form,
  125.                                 'error' => 'Password should not be older password. please try again'
  126.                             ]);
  127.                         } else {
  128.                             $userRepo->UpdatePassword1($user->getPasswordMd5(), $user->getId());
  129.                             $userRepo->UpdatePassword2($user->getPasswordOld1(), $user->getId());
  130.                             $userRepo->UpdatePassword3($user->getPasswordOld2(), $user->getId());
  131.                             $user->setPassword($hasher->hashPassword($user$newPassword));;
  132.                             $user->setPasswordMd5(md5($newPassword));
  133.                             $user->setToken(null);
  134.                             $entityManager->persist($user);
  135.                             $entityManager->flush();
  136.                             $this->addFlash('success''Password updated successfully!');
  137.                             return $this->redirectToRoute('app_login');
  138.                         }
  139.                     } else {
  140.                         return $this->renderForm('security/reset.html.twig', [
  141.                             'form' => $form,
  142.                             'error' => 'Password is not valid. please try again'
  143.                         ]);
  144.                     }
  145.                 } else {
  146.                     return $this->renderForm('security/reset.html.twig', [
  147.                         'form' => $form,
  148.                         'error' => ''
  149.                     ]);
  150.                 }
  151.             }
  152.         }
  153.         return $this->redirectToRoute('app_forgot');
  154.     }
  155.     private function redirectLoggedInUsers()
  156.     {
  157.         if ($this->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
  158.             return $this->redirectToRoute('dashboard');
  159.         }
  160.     }
  161.     public function verifyGoogleRecaptcha($token)
  162.     {
  163.         $ip2020 "";
  164.         if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  165.             $ip2020 $_SERVER['HTTP_CLIENT_IP'];
  166.         } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  167.             $ip2020 $_SERVER['HTTP_X_FORWARDED_FOR'];
  168.         } else {
  169.             $ip2020 $_SERVER['REMOTE_ADDR'];
  170.         }
  171.         $endpoint 'https://www.google.com/recaptcha/api/siteverify';
  172.         $secretKey $_ENV['GOOGLE_RECAPTCHA_SECRET_KEY'];
  173.         $arrParams "secret=$secretKey"&response=$token"&remoteip=$ip2020";
  174.         $ch = @curl_init();
  175.         @curl_setopt($chCURLOPT_POSTtrue);
  176.         @curl_setopt($chCURLOPT_POSTFIELDS$arrParams);
  177.         @curl_setopt($chCURLOPT_URL$endpoint);
  178.         @curl_setopt($chCURLOPT_HTTPHEADER, array(
  179.             'Content-Type: application/x-www-form-urlencoded'
  180.         ));
  181.         @curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  182.         $response    = @curl_exec($ch); //Log the response from HubSpot as needed.
  183.         @curl_close($ch);
  184.         return json_decode($responsetrue);
  185.     }
  186. }