vendor/nen/kennisbank-platform/src/Nen/Controller/SecurityController.php line 43

Open in your IDE?
  1. <?php
  2. namespace Nen\Bundle\KennisbankPlatformBundle\Controller;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;
  5. use Nen\Bundle\KennisbankPlatformBundle\Entity\BoltPage;
  6. use App\Entity\Company;
  7. use App\Entity\User;
  8. use Nen\Bundle\KennisbankPlatformBundle\Exceptions\IncompleteTokenRequestException;
  9. use Nen\Bundle\KennisbankPlatformBundle\Exceptions\InvalidPartnerException;
  10. use Nen\Bundle\KennisbankPlatformBundle\Exceptions\TokenRequestException;
  11. use Nen\Bundle\KennisbankPlatformBundle\Form\LoginType;
  12. use Nen\Bundle\KennisbankPlatformBundle\NenConnect\NenConnectException;
  13. use Nen\Bundle\KennisbankPlatformBundle\NenConnect\NenConnectSingleSignOn;
  14. use Nen\Bundle\KennisbankPlatformBundle\Repository\PartnerLoginUserRepository;
  15. use Nen\Bundle\KennisbankPlatformBundle\Repository\UserRepository;
  16. use Nen\Bundle\KennisbankPlatformBundle\Security\GlobalUserLoginFormFactory;
  17. use Nen\Bundle\KennisbankPlatformBundle\Security\ManualUserLogin;
  18. use Nen\Bundle\KennisbankPlatformBundle\Support\CodeGeneratorInterface;
  19. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
  20. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  21. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  22. use Symfony\Component\Form\FormError;
  23. use Symfony\Component\HttpFoundation\JsonResponse;
  24. use Symfony\Component\HttpFoundation\RedirectResponse;
  25. use Symfony\Component\HttpFoundation\Request;
  26. use Symfony\Component\HttpFoundation\Response;
  27. use Symfony\Component\Routing\Annotation\Route;
  28. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  29. use Symfony\Component\Security\Core\Exception\AccountExpiredException;
  30. use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;
  31. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  32. use function Symfony\Component\Translation\t;
  33. class SecurityController extends AbstractController
  34. {
  35.     /**
  36.      * @Route("/inloggen", name="login")
  37.      *
  38.      * @Entity("page", expr="repository.findOneBySystemSectionAndSlug('inloggen')")
  39.      */
  40.     public function login(Request $requestBoltPage $pageAuthenticationUtils $utils): Response
  41.     {
  42.         $data = ['page' => $page];
  43.         $form $this->createForm(LoginType::class, [
  44.            'username' => $utils->getLastUsername() ?: $request->cookies->get('wmn_username')
  45.         ]);
  46.         $form->handleRequest($request);
  47.         $error $utils->getLastAuthenticationError();
  48.         if ($error !== null) {
  49.             if ($error instanceof CustomUserMessageAccountStatusException) {
  50.                 $data['expired'] = $error->getMessage();
  51.             } else {
  52.                 $form->addError(new FormError('Ongeldige combinatie van e-mailadres en wachtwoord.'));
  53.             }
  54.         }
  55.         $data['form'] = $form->createView();
  56.         if ($request->isXmlHttpRequest()) {
  57.             return $this->render('@KennisbankPlatform/security/modal/login.html.twig'$data);
  58.         }
  59.         return $this->render('@KennisbankPlatform/security/login.html.twig'$data);
  60.     }
  61.     /**
  62.      * @Route("/inloggen/partner/token", name="partner_login_token_request")
  63.      *
  64.      * @param Request $request
  65.      * @return Response
  66.      */
  67.     public function partnerLoginTokenRequest(
  68.         Request $request,
  69.         JWTEncoderInterface $JWTEncoder,
  70.         PartnerLoginUserRepository $partnerLoginUserRepository
  71.     ) {
  72.         $clientName null;
  73.         $clientId   null;
  74.         $secret     null;
  75.         $userId     null;
  76.         $missingParameters = [];
  77.         $parameters = [
  78.             'client_name' => 'clientName',
  79.             'client_id'   => 'clientId',
  80.             'secret'      => 'secret',
  81.             'user_id'     => 'userId',
  82.         ];
  83.         foreach ($parameters as $key => $value) {
  84.             if (empty(${$value} = $request->query->get($key))) {
  85.                 $missingParameters[] = $key;
  86.             }
  87.         }
  88.         try {
  89.             if (count($missingParameters)) {
  90.                 throw new IncompleteTokenRequestException(implode(', '$missingParameters));
  91.             }
  92.             $partners $this->getParameter('partner_login');
  93.             if (!array_key_exists($clientName$partners)) {
  94.                 throw new InvalidPartnerException();
  95.             }
  96.             if ($partners[$clientName]['id'] !== $clientId || $partners[$clientName]['secret'] !== $secret) {
  97.                 throw new InvalidPartnerException();
  98.             }
  99.             //request is valid
  100.             $redirect $this->generateUrl('home', [], UrlGeneratorInterface::ABSOLUTE_URL);
  101.             //lookup user
  102.             $user $partnerLoginUserRepository->findOneBy(
  103.                 [
  104.                     'partnerName'   => $clientName,
  105.                     'partnerUserId' => $userId,
  106.                 ]
  107.             );
  108.             $tokenData = [
  109.                 'exp' => time() + 300
  110.                 // 5 min expiration. User should be redirected immediately, so no need for long exp time
  111.             ];
  112.             //user not found, set redirect to login page
  113.             if (!$user) {
  114.                 $tokenData['username']   = '';
  115.                 $tokenData['clientName'] = $clientName;
  116.                 $tokenData['userId']     = $userId;
  117.                 $tokenData['exp']        = time() + 3600// 1 hour expiration so there is enough time to create an account
  118.             } else {
  119.                 $tokenData['username'] = $user->getUser()->getUsername();
  120.             }
  121.             //create JWT
  122.             $token $JWTEncoder->encode($tokenData);
  123.         } catch (TokenRequestException $e) {
  124.             return new JsonResponse(['error' => $e->getMessage()], 400);
  125.         }
  126.         //return JWT
  127.         return new JsonResponse(['token' => $token]);
  128.     }
  129.     /**
  130.      * @Route("/nen-connect", name="security_nen_connect_sso")
  131.      *
  132.      * @IsGranted("ROLE_USER")
  133.      *
  134.      * @param NenConnectSingleSignOn $sso
  135.      * @return RedirectResponse
  136.      */
  137.     public function nenConnectSso(NenConnectSingleSignOn $sso)
  138.     {
  139.         /** @var User $user */
  140.         $user $this->getUser();
  141.         try {
  142.             $url $sso->getSingleSignOnUrl($user);
  143.         } catch (NenConnectException $e) {
  144.             $this->addFlash('error't('Op dit moment is het niet mogelijk om in te loggen via NEN Connect. Probeer het later nog een keer.'));
  145.             return $this->redirectToRoute('home');
  146.         }
  147.         return $this->redirect($url);
  148.     }
  149. }