src/Controller/SecurityController.php line 76

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Repository\UserRepository;
  4. use App\Services\OktaApiService;
  5. use Psr\Log\LoggerInterface;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  8. use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
  9. use Symfony\Component\HttpFoundation\RedirectResponse;
  10. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  11. use Symfony\Component\Routing\Annotation\Route;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  14. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  15. use App\Entity\User;
  16. use App\Form\UserType;
  17. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  18. class SecurityController extends AbstractController
  19. {
  20.     private $session;
  21.     private $okta;
  22.     private $userRepository;
  23.     public function __construct(
  24.         SessionInterface $session,
  25.         OktaApiService $okta,
  26.         UserRepository $UserRepository)
  27.     {
  28.         $this->session $session;
  29.         $this->okta $okta;
  30.         $this->userRepository $UserRepository;
  31.     }
  32.     /**
  33.      * @Route("/login", name="login", methods={"GET", "POST"})
  34.      */
  35.     public function login(AuthenticationUtils $authenticationUtils)
  36.     {
  37.         // get the login error if there is one
  38.         $error $authenticationUtils->getLastAuthenticationError();
  39.         // last username entered by the user
  40.         $lastUsername $authenticationUtils->getLastUsername();
  41.         return $this->render('security/login.html.twig', [
  42.             'last_username' => $lastUsername,
  43.             'error'         => $error,
  44.         ]);
  45.     }
  46.     /**
  47.      * @Route("/sso", name="sso", methods={"GET", "POST"})
  48.      */
  49.     public function sso(
  50.         AuthenticationUtils $authenticationUtils,
  51.         Request $request,
  52.         LoggerInterface $logger
  53.     )
  54.     {
  55. //        $logger->debug(
  56. //            sprintf(
  57. //                "%s",
  58. //                $request->attributes->get('_route')
  59. //            ), $request->query->all()
  60. //        );
  61.         return $this->redirect($this->okta->buildAuthorizeUrl());
  62.     }
  63.     /**
  64.      * @Route("/authorization-code/callback", name="callback")
  65.      */
  66.     public function callback(
  67.         Request $request,
  68.         LoggerInterface $logger
  69.     )
  70.     {
  71.         $token $this->okta->authorizeUser();
  72.         if (!$token) {
  73.             return $this->redirectToRoute('homepage');
  74.         }
  75.         $email $token->email;
  76.         $user $this->userRepository->findOneByEmail($email);
  77.         if (! $user) {
  78.             $user = new User();
  79.         }
  80.         // Manually authenticate the user
  81.         $token = new UsernamePasswordToken($usernull'main'$user->getRoles());
  82.         $this->get('security.token_storage')->setToken($token);
  83.         $this->get('session')->set('_security_main'serialize($token));
  84.         $user->setEmail($email);
  85.         $user->setToken($token);
  86.         $em $this->getDoctrine()->getManager();
  87.         $em->persist($user);
  88.         $em->flush();
  89.         $logger->debug(
  90.             sprintf(
  91.                 "%s by %s",
  92.                 $request->attributes->get('_route'),
  93.                 $this->getUser()->getUsername()
  94.             )
  95.         );
  96.         return $this->redirectToRoute('homepage');
  97.     }
  98.     /**
  99.      * @Route("/logout", name="app_logout", methods={"GET"})
  100.      */
  101.     public function logout() {
  102.         // Build logout url
  103.         $url $this->okta->logout();
  104.         // Empty sessions
  105.         $this->session->clear();
  106.         $this->session->invalidate();
  107.         // Empty security token. Without this the user can go back end browse NJ without beeing authenticated on Okta
  108.         $this->get('security.token_storage')->setToken(NULL);
  109.         return new RedirectResponse($url);
  110.         // controller can be blank: it will never be executed!
  111. //        throw new \Exception('Don\'t forget to activate logout in security.yaml');
  112.     }
  113.     /**
  114.      * @Route("/users", name="users", methods={"GET"})
  115.      */
  116.     public function users() {
  117.         $this->denyAccessUnlessGranted('ROLE_ADMIN');
  118.         $entityManager $this->getDoctrine()->getManager();
  119.         $users $entityManager->getRepository(User::class)->findAll();
  120.         return $this->render('security/users.html.twig', [
  121.             'users' => $users
  122.         ]);
  123.     }
  124.     /**
  125.      * @Route("/users/edit/{id}", name="users_edit", methods={"GET", "POST"})
  126.      */
  127.     public function edit($idRequest $requestUserPasswordEncoderInterface $passwordEncoder) {
  128.         $this->denyAccessUnlessGranted('ROLE_ADMIN');
  129.         // 1) build the form
  130.         if( $id == ) {
  131.             $user = new User();
  132.         } else {
  133.             $entityManager $this->getDoctrine()->getManager();
  134.             $user $entityManager->getRepository(User::class)->find($id);
  135.         }
  136.         $form $this->createForm(UserType::class, $user);
  137.         if( $id != ) {
  138.             $form->add('plainPassword'RepeatedType::class, array(
  139.                 'type' => PasswordType::class,
  140.                 'first_options'  => array('label' => 'Password'),
  141.                 'second_options' => array('label' => 'Repeat Password'),
  142.                 'required' => false,
  143.             ));
  144.         }
  145.         // 2) handle the submit (will only happen on POST)
  146.         $form->handleRequest($request);
  147.         if ($form->isSubmitted() && $form->isValid()) {
  148.             if( $id == || !empty($form['plainPassword']->getData()) ) {
  149.                 // 3) Encode the password (you could also do this via Doctrine listener)
  150.                 $password $passwordEncoder->encodePassword($user$user->getPlainPassword());
  151.                 $user->setPassword($password);
  152.             }
  153.             // 4) save the User!
  154.             $entityManager $this->getDoctrine()->getManager();
  155.             $entityManager->persist($user);
  156.             $entityManager->flush();
  157.             // ... do any other work - like sending them an email, etc
  158.             // maybe set a "flash" success message for the user
  159.             return $this->redirectToRoute('users');
  160.         }
  161.         return $this->render(
  162.             'security/edit.html.twig',
  163.             array('form' => $form->createView())
  164.         );
  165.     }
  166. }