src/Security/AppPhcAuthenticator.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\{UserUserLoginHistory};
  4. use App\Repository\UserLoginHistoryRepository;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\{RedirectResponseRequestResponse};
  8. use Symfony\Component\Routing\RouterInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  10. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  11. use Symfony\Component\Security\Core\Exception\UserNotFoundException;
  12. use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
  13. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\{CsrfTokenBadgeRememberMeBadgeUserBadge};
  14. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  15. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  16. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  17. use App\Entity\UserLog;
  18. use Symfony\Component\Security\Core\Security;
  19. use Nzo\UrlEncryptorBundle\Encryptor\Encryptor;
  20. class AppPhcAuthenticator extends AbstractLoginFormAuthenticator
  21. {
  22.     use TargetPathTrait;
  23.     private $params;
  24.     private $encryptor;
  25.     public function __construct(private EntityManagerInterface $entityManager, private RouterInterface $routerEncryptor $encryptor)
  26.     {
  27.         $this->encryptor $encryptor;
  28.     }
  29.     public function supports(Request $request): bool
  30.     {
  31.         return 'app_login' === $request->attributes->get('_route') && $request->isMethod('POST');
  32.     }
  33.     public function verifyGoogleRecaptcha($token)
  34.     {
  35.         $ip2020 "";
  36.         if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  37.             $ip2020 $_SERVER['HTTP_CLIENT_IP'];
  38.         } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  39.             $ip2020 $_SERVER['HTTP_X_FORWARDED_FOR'];
  40.         } else {
  41.             $ip2020 $_SERVER['REMOTE_ADDR'];
  42.         }
  43.         $endpoint 'https://www.google.com/recaptcha/api/siteverify';
  44.         $secretKey $_ENV['GOOGLE_RECAPTCHA_SECRET_KEY'];
  45.         $arrParams "secret=$secretKey"&response=$token"&remoteip=$ip2020";
  46.         $ch = @curl_init();
  47.         @curl_setopt($chCURLOPT_POSTtrue);
  48.         @curl_setopt($chCURLOPT_POSTFIELDS$arrParams);
  49.         @curl_setopt($chCURLOPT_URL$endpoint);
  50.         @curl_setopt($chCURLOPT_HTTPHEADER, array(
  51.             'Content-Type: application/x-www-form-urlencoded'
  52.         ));
  53.         @curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  54.         $response    = @curl_exec($ch); //Log the response from HubSpot as needed.
  55.         @curl_close($ch);
  56.         return json_decode($responsetrue);
  57.     }
  58.     public function authenticate(Request $request): Passport
  59.     {
  60.         // $token = $request->request->get('g-recaptcha-response');
  61.         // $responses = $this->verifyGoogleRecaptcha($token);
  62.         // if (!$responses['success']) {
  63.         //     throw new UserNotFoundException();
  64.         // }
  65.         $username $request->request->get('_username');
  66.         $password $request->request->get('_password');
  67.         return new Passport(
  68.             new UserBadge($username, function ($userIdentifier) {
  69.                 $user $this->entityManager->getRepository(User::class)->findOneBy(['username' => $userIdentifier]);
  70.                 if (!$user) {
  71.                     throw new UserNotFoundException();
  72.                 }
  73.                 return $user;
  74.             }),
  75.             new PasswordCredentials($password),
  76.             [
  77.                 new CsrfTokenBadge(
  78.                     'authenticate',
  79.                     $request->request->get('_csrf_token')
  80.                 ),
  81.                 $request->request->has('_remember_me') ? (new RememberMeBadge())->enable() : new RememberMeBadge()
  82.             ]
  83.         );
  84.     }
  85.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  86.     {
  87.         /** @var User $user */
  88.         $user $token->getUser();
  89.         date_default_timezone_set('Asia/Kolkata');
  90.         $user->setLastLogin(new \DateTime());
  91.         $user->setIsActive(true);
  92.         $this->entityManager->persist($user);
  93.         $history = new UserLoginHistory();
  94.         $history
  95.             ->setUser($user)
  96.             ->setUserIp($request->getClientIp())
  97.             ->setLoginAttempts(0);
  98.         $this->entityManager->persist($history);
  99.         $this->entityManager->flush();
  100.         if ($targetPath $this->getTargetPath($request->getSession(), $firewallName)) {
  101.             return new RedirectResponse($targetPath);
  102.         }
  103.         $this->entityManager->getConnection()->setAutoCommit(false);
  104.         $this->entityManager->beginTransaction();
  105.         $currentDate = new \Datetime();
  106.         $uid $token->getUser()->getId();
  107.         $Filename $uid '_' date('d-m-Y') . '.csv';
  108.         $baseUrl $request->getBaseUrl();
  109.         $filePath $baseUrl '/uploads/activity_log/' $uid '/' $Filename;
  110.         $userLog = new UserLog();
  111.         $userLog->setUserId($user->getId());
  112.         $userLog->setAction($request->getMethod());
  113.         $userLog->setFilePath($Filename);
  114.         $userLog->setHospitalId($user->getProfile()->getHospital()->getId());
  115.         $userLog->setCreatedDate($currentDate);
  116.         $userLog->setUpdatedAt($currentDate);
  117.         $userLog->setCreatedDate($currentDate);
  118.         $this->entityManager->persist($userLog);
  119.         $this->entityManager->flush();
  120.         $this->entityManager->commit();
  121.         $role $token->getUser()->getRoles()[0];
  122.         $id $token->getUser()->getProfile()->getId();
  123.         if (($token->getUser()->getProfile()->getIsUpdate() != '' && $token->getUser()->getProfile()->getIsUpdate() == 0) && ($role != '' && $role == "ROLE_HR")) {
  124.             return new RedirectResponse($this->router->generate('staff_profile_edit', ['id' => $this->encryptor->encrypt($id)]));
  125.         }
  126.         return new RedirectResponse($this->router->generate('dashboard'));
  127.     }
  128.     public function onAuthenticationFailure(Request $requestAuthenticationException $exception): Response
  129.     {
  130.         $history = new UserLoginHistory();
  131.         $user = new User();
  132.         $failure 0;
  133.         $user $this->entityManager->getRepository(User::class)->findOneBy(['username' => $request->request->get('_username')]);
  134.         if ($request->request->get('_username')) {
  135.             $failure += 1;
  136.         }
  137.         if ($user) {
  138.             date_default_timezone_set('Asia/Kolkata');
  139.             $uID $user->getId();
  140.             $fileName $user->getId() . '_' date('d-m-Y') . '.csv';
  141.             if (!file_exists('../public/uploads/login_failure/' $uID)) {
  142.                 $userId mkdir('../public/uploads/login_failure/' $uID0777true);
  143.             } else {
  144.                 $userId $uID;
  145.             }
  146.             $filePath '../public/uploads/login_failure/' $userId '/' $fileName;
  147.             $failureFile fopen($filePath"a") or die('Unable to open file');
  148.             $dataArr = [
  149.                 'username' => $request->request->get('_username'),
  150.                 'login_attempts' => $failure,
  151.                 'client_ip' => $request->getClientIp(),
  152.                 'date/time' => date('d-m-Y h:i:s'),
  153.             ];
  154.             fputcsv($failureFile$dataArr);
  155.             fclose($failureFile);
  156.             $data $this->entityManager->getRepository(UserLoginHistory::class)->getLoginHistoryByUserId($user->getId());
  157.             $this->entityManager->getRepository(UserLoginHistory::class)->UpdateLoginHistoryByUserId($user->getId());
  158.             if ($data) {
  159.                 if ($data[0]['total'] >= 8) {
  160.                     $user->setIsActive(false);
  161.                 }
  162.             }
  163.             $history
  164.                 ->setUser($user)
  165.                 ->setLoginAttempts($failure)
  166.                 ->setUserIp($request->getClientIp())
  167.                 ->setFileUrl($fileName);
  168.             $this->entityManager->persist($history);
  169.             $this->entityManager->flush();
  170.         }
  171.         $request->getSession()->set(Security::AUTHENTICATION_ERROR$exception);
  172.         return new RedirectResponse($this->router->generate('app_login'));
  173.     }
  174.     protected function getLoginUrl(Request $request): string
  175.     {
  176.         return $this->router->generate('app_login');
  177.     }
  178. }