vendor/nen/kennisbank-platform/src/Nen/Security/NenAuthenticator.php line 32

Open in your IDE?
  1. <?php
  2. namespace Nen\Bundle\KennisbankPlatformBundle\Security;
  3. use App\Entity\User;
  4. use Carbon\Carbon;
  5. use DateTime;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  8. use Lexik\Bundle\JWTAuthenticationBundle\Exception\JWTDecodeFailureException;
  9. use Lexik\Bundle\JWTAuthenticationBundle\TokenExtractor\QueryParameterTokenExtractor;
  10. use Nen\Bundle\KennisbankPlatformBundle\Entity\PartnerLoginUser;
  11. use Nen\Bundle\KennisbankPlatformBundle\Repository\UserRepository;
  12. use Symfony\Component\HttpFoundation\Cookie;
  13. use Symfony\Component\HttpFoundation\JsonResponse;
  14. use Symfony\Component\HttpFoundation\RedirectResponse;
  15. use Symfony\Component\HttpFoundation\Request;
  16. use Symfony\Component\HttpFoundation\Response;
  17. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  18. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  19. use Symfony\Component\Security\Core\Security;
  20. use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
  21. use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
  22. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
  23. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\PasswordUpgradeBadge;
  24. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  25. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  26. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  27. use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
  28. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  29. class NenAuthenticator extends AbstractLoginFormAuthenticator
  30. {
  31.     use TargetPathTrait;
  32.     public const LOGIN_ROUTE 'login';
  33.     private UrlGeneratorInterface $urlGenerator;
  34.     private EntityManagerInterface $em;
  35.     private JWTEncoderInterface $jwtEncoder;
  36.     private UserRepository $repository;
  37.     public function __construct(
  38.         UrlGeneratorInterface $urlGenerator,
  39.         EntityManagerInterface $entityManager,
  40.         JWTEncoderInterface $jwtEncoder,
  41.         UserRepository $repository
  42.     ) {
  43.         $this->urlGenerator $urlGenerator;
  44.         $this->em $entityManager;
  45.         $this->jwtEncoder $jwtEncoder;
  46.         $this->repository $repository;
  47.     }
  48.     public function supports(Request $request): bool
  49.     {
  50.         if (self::LOGIN_ROUTE !== $request->attributes->get('_route')) {
  51.             return false;
  52.         }
  53.         if (!$request->isMethod('POST')) {
  54.             return false;
  55.         }
  56.         return true;
  57.     }
  58.     public function authenticate(Request $request): PassportInterface
  59.     {
  60.         $credentials = [
  61.             'username' => $request->request->get('username'''),
  62.             'password' => $request->request->get('password''')
  63.         ];
  64.         $request->getSession()->set(Security::LAST_USERNAME$credentials['username']);
  65.         return new Passport(
  66.             new UserBadge($credentials['username']),
  67.             new PasswordCredentials($credentials['password']),
  68.             [
  69.                 new CsrfTokenBadge('authenticate'$request->get('_csrf_token')),
  70.                 new PasswordUpgradeBadge($credentials['password'], $this->repository),
  71.             ]
  72.         );
  73.     }
  74.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  75.     {
  76.         $this->updateLoginInformation($token);
  77.         $this->handleJwtToken($request$token);
  78.         if ($targetPath $this->getTargetPath($request->getSession(), $firewallName)) {
  79.             $continue $targetPath;
  80.         } else {
  81.             $continue $this->urlGenerator->generate('mijnomgeving_index');
  82.         }
  83.         if ($request->isXmlHttpRequest()) {
  84.             $response = new JsonResponse(['url' => $continue]);
  85.         } else {
  86.             $response = new RedirectResponse($continue);
  87.         }
  88.         $this->handleRememberUsername($request$response);
  89.         return $response;
  90.     }
  91.     private function updateLoginInformation(TokenInterface $token): void
  92.     {
  93.         /** @var User $user */
  94.         $user $token->getUser();
  95.         $user->setLoginAt(new DateTime());
  96.         $this->em->flush();
  97.     }
  98.     private function handleJwtToken(Request $requestTokenInterface $token): void
  99.     {
  100.         $extractor = new QueryParameterTokenExtractor('jwt');
  101.         $jwtToken $extractor->extract($request);
  102.         if ($jwtToken === false) {
  103.             return;
  104.         }
  105.         try {
  106.             $data $this->jwtEncoder->decode($jwtToken);
  107.         } catch (JWTDecodeFailureException $e) {
  108.             return;
  109.         }
  110.         $repository $this->em->getRepository(PartnerLoginUser::class);
  111.         $partnerLogin $repository->findOneBy(
  112.             [
  113.                 'partnerName' => $data['clientName'],
  114.                 'partnerUserId' => $data['userId'],
  115.             ]
  116.         );
  117.         if ($partnerLogin !== null) {
  118.             return;
  119.         }
  120.         /** @var User $user */
  121.         $user $token->getUser();
  122.         $partnerLoginUser = new PartnerLoginUser();
  123.         $partnerLoginUser->setPartnerName($data['clientName']);
  124.         $partnerLoginUser->setPartnerUserId($data['userId']);
  125.         $partnerLoginUser->setUser($user);
  126.         $this->em->persist($partnerLoginUser);
  127.         $this->em->flush();
  128.     }
  129.     private function handleRememberUsername(Request $requestResponse $response): void
  130.     {
  131.         if (!$request->request->getBoolean('remember_username')) {
  132.             $response->headers->removeCookie('wmn_username');
  133.             return;
  134.         }
  135.         $cookie = new Cookie('wmn_username'$request->request->get('username'), Carbon::now()->addYear());
  136.         $response->headers->setCookie($cookie);
  137.     }
  138.     protected function getLoginUrl(Request $request): string
  139.     {
  140.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  141.     }
  142.     public function getPassword($credentials): ?string
  143.     {
  144.         return $credentials['password'];
  145.     }
  146. }