src/Controller/SecurityController.php line 24

Open in your IDE?
  1. <?php
  2. // src/Controller/SecurityController.php
  3. namespace App\Controller;
  4. use App\Entity\User;
  5. use App\Form\LoginType;
  6. use App\Form\Model\ChangePassword;
  7. use App\Form\Type\ChangePasswordType;
  8. use App\Repository\LoginAttemptRepository;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\Routing\Annotation\Route;
  13. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  14. /**
  15.  * @see https://symfony.com/doc/current/security.html
  16.  */
  17. class SecurityController extends AbstractController
  18. {
  19.     /**
  20.      * @Route("/login", name="login", methods={"GET", "POST"})
  21.      */
  22.     public function login(AuthenticationUtils $authenticationUtils): Response
  23.     {
  24.         // Redirect if a User is already authenticated
  25.         if ($this->getUser()) {
  26.            $this->redirectToRoute('target_path');
  27.         }
  28.         // Create the form
  29.         $form $this->createForm(LoginType::class, [
  30.             '_username' => $authenticationUtils->getLastUsername(),
  31.         ], [
  32.             'method' => "POST",
  33.             'action' => $this->generateUrl('login_check'),
  34.         ]);
  35.         return $this->render('security/login.html.twig', [
  36.             'form_login' => $form->createView(),
  37.             'error' => $authenticationUtils->getLastAuthenticationError()
  38.         ]);
  39.     }
  40.     /**
  41.      * @Route("/login_check", name="login_check", methods={"POST"})
  42.      */
  43.     public function check()
  44.     {
  45.         throw new \RuntimeException('You must configure the check_path to be handled by the firewall using form_login in your security firewall configuration.');
  46.     }
  47.     /**
  48.      * @Route("/logout", name="logout")
  49.      *
  50.      * @see https://symfony.com/doc/current/security.html#logging-out
  51.      */
  52.     public function logout()
  53.     {
  54.         // controller can be blank: it will never be executed!
  55.         throw new \Exception('Don\'t forget to activate logout in security.yaml');
  56.     }
  57.     /**
  58.      * @Route("/register", name="register")
  59.      */
  60.     public function register(Request $request)
  61.     {
  62.         $user = new User();
  63.         $form $this->createForm(UserType::class, $user);
  64.         $form->handleRequest($request);
  65.         if ($form->isSubmitted() && $form->isValid()) {
  66.             $entityManager $this->getDoctrine()->getManager();
  67.             $entityManager->persist($user);
  68.             $entityManager->flush();
  69.             $this->addFlash('success''Welcome '.$user->getEmail());
  70.             // Automatic login after successful registration
  71.             return $this->get('security.authentication.guard_handler')->authenticateUserAndHandleSuccess(
  72.                 $user,
  73.                 $request,
  74.                 $this->get('app.security.login_form_authenticator'),
  75.                 'main'
  76.             );
  77.         }
  78.         return $this->render('security/register.html.twig', [
  79.             'form' => $form->createView(),
  80.         ]);
  81.     }
  82.     /**
  83.      * @Route("/change-password", name="change_password", methods={"GET","POST"})
  84.      */
  85.     public function changePassword(Request $request)
  86.     {
  87.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  88.         $user $this->getUser();
  89.         $form $this->createForm(ChangePasswordType::class, new ChangePassword, [
  90.             'action' => $this->generateUrl($request->get('_route')),
  91.             'method' => "POST",
  92.         ]);
  93.         $form->handleRequest($request);
  94.         if ($form->isSubmitted() && $form->isValid()) {
  95.             try {
  96.                 $user->setPlainPassword($form->getData()->getNewPassword());
  97.                 $this->getDoctrine()->getManager()->flush();
  98.             } catch (\Throwable $e) {
  99.                 $this->addFlash('danger''Could not change your password!');
  100.             }
  101.             $this->addFlash('success''Your password has been changed successfully!');
  102.             return $this->redirectToRoute('logout');
  103.         }
  104.         return $this->render('security/password_change.html.twig', [
  105.             'form' => $form->createView(),
  106.         ]);
  107.     }
  108.     /**
  109.      * @Route("/.well-known/change-password", methods={"GET","POST"})
  110.      *
  111.      * @see https://web.dev/change-password-url/
  112.      * @see https://w3c.github.io/webappsec-change-password-url/
  113.      */
  114.     public function wellKnownChangePassword(Request $request)
  115.     {
  116.         return $this->redirectToRoute('change_password');
  117.     }
  118.     /**
  119.      * @Route("/login-attempts", name="login_attempts", methods={"GET"})
  120.      */
  121.     public function loginAttempts(LoginAttemptRepository $loginAttempts)
  122.     {
  123.         $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
  124.         return $this->json($loginAttempts->getRecentAttempts());
  125.     }
  126.     /**
  127.      * @Route("/maintenance", name="maintenance", methods={"GET","POST"})
  128.      */
  129.     public function maintenance(Request $request)
  130.     {
  131.         $ipFile $this->getParameter('kernel.project_dir').'/config/whitelist';
  132.         if ($request->get('maintenance')) {
  133.             $form $request->get('maintenance');
  134.             if(!isset($form['activated'])){
  135.                 @unlink($this->getParameter('kernel.project_dir').'/0_MAINTENANCE');
  136.             }else{
  137.                 fopen($this->getParameter('kernel.project_dir').'/0_MAINTENANCE'"w");
  138.             }
  139.             $ipfile fopen($ipFile"w");
  140.             $ipList array_unique(explode(PHP_EOL,$form['iplist']));
  141.             foreach($ipList as $ip){
  142.                 $ip trim($ip);
  143.                 if (filter_var($ipFILTER_VALIDATE_IP)) {
  144.                     fwrite($ipfile,$ip.PHP_EOL);
  145.                 }
  146.             }
  147.             return $this->redirectToRoute('maintenance');
  148.         }
  149.         $maintenanceMode = ($_ENV["MAINTENANCE"] == "ENABLED") ? true false;
  150.         $ipList implode("\n",file($ipFileFILE_IGNORE_NEW_LINES));
  151.         return $this->render('security/maintenance.html.twig', [
  152.             'maintenanceMode' => $maintenanceMode,
  153.             'ipList' => $ipList
  154.         ]);
  155.     }
  156. }