LoginController.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpFoundation\Session\Session;
  8. use Symfony\Component\Routing\Annotation\Route;
  9. use Symfony\Component\Form\Extension\Core\Type\TextType;
  10. use Symfony\Component\Form\Extension\Core\Type\PasswordType;
  11. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  12. class LoginController extends AbstractController
  13. {
  14. /**
  15. * @Route("/login", name="login")
  16. */
  17. public function index(Request $request, UserPasswordEncoderInterface $encoder): Response
  18. {
  19. $session = $this->get('session');
  20. if (null !== $session->get('user')) {
  21. $session->save();
  22. return $this->redirectToRoute('profile', ['id' => $session->get('user')]);
  23. }
  24. // $profile = new User();
  25. // Instanciation du fromBuilder
  26. $formBuilder = $this->createFormBuilder(); //$profile);
  27. // Ajout des champs
  28. $formBuilder
  29. ->add('identifiant', TextType::class)
  30. ->add('mot_de_passe', PasswordType::class)
  31. ->setAction($this->generateUrl('login'));
  32. // Génération du formulaire
  33. $form = $formBuilder->getForm();
  34. if ($request->getMethod() == 'POST') {
  35. $form->handleRequest($request);
  36. if ($form->isValid()) {
  37. $id = $form->get("identifiant")->getData();
  38. $passwd = $form->get('mot_de_passe')->getData();
  39. $em = $this->getDoctrine()->getManager();
  40. $repository_profile = $em->getRepository(User::class);
  41. $profile = $repository_profile->findOneBy(array('username' => $id));
  42. if ($profile) {
  43. if ($encoder->isPasswordValid($profile, $passwd)) {
  44. $session->set('user', $id);
  45. return $this->redirectToRoute('profile', ['username' => $session->get('user')]);
  46. }
  47. }
  48. return $this->render('login/index.html.twig', [
  49. 'message' => "Utilisateur ou mot de passe incorrect",
  50. 'form' => $form->createView()
  51. ]);
  52. }
  53. }
  54. return $this->render('login/index.html.twig', [
  55. 'form' => $form->createView(),
  56. 'message' => ""
  57. ]);
  58. }
  59. }