src/Controller/SecurityController.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\CBRCResetPassword;
  4. use App\Entity\CBRCUser;
  5. use App\Form\Type\AddUserRoleType;
  6. use App\Form\Type\ResetPassword1Type;
  7. use App\Form\Type\ResetPassword2Type;
  8. use App\Utilities\Secure;
  9. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  10. use Symfony\Component\Form\FormError;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  16. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  17. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  18. use App\Utilities\Mail;
  19. class SecurityController extends AbstractController
  20. {
  21.     /**
  22.      * @Route("/connexion", name="app_login")
  23.      */
  24.     public function login(AuthenticationUtils $authenticationUtils): Response
  25.     {
  26.         /*if ($this->getUser()) {
  27.             return $this->redirectToRoute('home');
  28.         }*/
  29.         // get the login error if there is one
  30.         $error $authenticationUtils->getLastAuthenticationError();
  31.         // last username entered by the user
  32.         $lastUsername $authenticationUtils->getLastUsername();
  33.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  34.     }
  35.     /**
  36.      * @Route("/logout", name="app_logout")
  37.      */
  38.     public function logout()
  39.     {
  40.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  41.     }
  42.     /**
  43.      * @Route("/admin/acces", name="app_accessmanager")
  44.      */
  45.     public function ShowAccessManager(Request $request)
  46.     {
  47.         $this->denyAccessUnlessGranted('ROLE_ADMIN');
  48.         $adminusers $this->getDoctrine()->getRepository(CBRCUser::class)->findByRole('ROLE_ADMIN');
  49.         $writterusers $this->getDoctrine()->getRepository(CBRCUser::class)->findByRole('ROLE_WRITER');
  50.         $formaddrole $this->createForm(AddUserRoleType::class);
  51.         $formaddrole->handleRequest($request);
  52.         if($formaddrole->isSubmitted() && $formaddrole->isValid())
  53.         {
  54.             $email=$formaddrole->get('email')->getData();
  55.             $role $formaddrole->get('role')->getData();
  56.             $user$this->getDoctrine()->getRepository(CBRCUser::class)->findOneBy(['email'=>$email]);
  57.             if($user==null) {
  58.                 $this->addFlash('danger''L\'utilisateur n\'existe pas');
  59.                 return $this->redirect($request->getUri());
  60.             }
  61.             $user->setRoles(array($role));
  62.             $em=$this->getDoctrine()->getManager();
  63.             $em->persist($user);
  64.             $em->flush();
  65.             return $this->redirect($request->getUri());
  66.         }
  67.         if ($formaddrole->isSubmitted() && !$formaddrole->isValid()) {
  68.             foreach ($formaddrole->getErrors(true) as $error)
  69.                 $this->addFlash('danger'"(" $error->getOrigin()->getName() . ") " $error->getMessage());
  70.             $formaddrole->clearErrors(true);
  71.         }
  72.         return $this->render('security/adminaccessmanager.html.twig',[
  73.             'adminusers' => $adminusers,
  74.             'writterusers' => $writterusers,
  75.             'formrole' => $formaddrole->createView(),
  76.             'idactive' => 7
  77.         ]);
  78.     }
  79.     /**
  80.      * @Route("/security/resetpassword" , name="app_resetpassword")
  81.      */
  82.     public function ResetPassword(Request $request)
  83.     {
  84.         $formreset $this->createForm(ResetPassword1Type::class);
  85.         $formreset->handleRequest($request);
  86.         if($formreset->isSubmitted() && $formreset->isValid()){
  87.             $email=$formreset->getData()['email'];
  88.             //get the user
  89.             $user=$this->getDoctrine()->getRepository(CBRCUser::class)->findOneBy(array('email'=>$email));
  90.             if($user==null)
  91.             {
  92.                 $formreset->get('email')->addError(new FormError('Email inconnu'));
  93.             }
  94.             else
  95.             {
  96.                 $this->ClearUserResetPassword($user);
  97.                 $datetime = new \DateTime();
  98.                 $datetime->add(new \DateInterval("P1D")); //add 1day
  99.                 $resetpassword = new CBRCResetPassword();
  100.                 $resetpassword->setUser($user);
  101.                 $resetpassword->setToken($this->GetUniqueToken());
  102.                 $resetpassword->setValiditydate($datetime);
  103.                 $entityManager $this->getDoctrine()->getManager();
  104.                 $entityManager->persist($resetpassword);
  105.                 $entityManager->flush($resetpassword);
  106.                 //Send mail
  107.                 $link $this->generateUrl('app_resetpassword_token', ['token'=>$resetpassword->getToken()], UrlGeneratorInterface::ABSOLUTE_URL);
  108.                 $txtmessage "Pour reinitialier votre mot de passe rendez vous sur: ".$link;
  109.                 $subject "Reinitialiser le mot de passe";
  110.                 $htmlmessage $this->render('mail/resetpasswordmail.html.twig', [
  111.                     'subject' => $subject,
  112.                     'link' => $link,
  113.                 ]);
  114.                 $return Mail::SendMailToMail($email$subject$htmlmessage$txtmessage);
  115.                 if($return ==false)
  116.                 {
  117.                     $this->addFlash('danger''Erreur lors de l\'envoi du mail');
  118.                 }
  119.                 return $this->render('security/resetpasswordconfirmation.html.twig', [
  120.                     'passwordchanged' => false,
  121.                 ]);
  122.             }
  123.         }
  124.         if($formreset->isSubmitted() && !$formreset->isValid())
  125.         {
  126.             foreach($formreset->getErrors(true) as $error)
  127.                 $this->addFlash('danger'"(".$error->getOrigin()->getName().") ".$error->getMessage());
  128.             return $this->redirect($request->getUri());
  129.         }
  130.         return $this->render('security/resetpassword.html.twig', [
  131.             'formreset' => $formreset->createView(),
  132.         ]);
  133.     }
  134.     /**
  135.      * @Route("/security/resetpassword/{token}", name="app_resetpassword_token")
  136.      */
  137.     public function ResetPasswordWithToken($tokenRequest $requestUserPasswordEncoderInterface $passwordEncoder)
  138.     {
  139.         $resetpassword $this->getDoctrine()->getRepository(CBRCResetPassword::class)->findOneBy(array('token'=>$token));
  140.         $entityManager $this->getDoctrine()->getManager();
  141.         if($resetpassword->getValiditydate()< new \DateTime())
  142.         {
  143.             $entityManager->remove($resetpassword);
  144.             $entityManager->flush();
  145.             $resetpassword=null;
  146.         }
  147.         if($resetpassword==null)
  148.         {
  149.             return $this->redirectToRoute("app_resetpassword");
  150.         }
  151.         $formreset $this->createForm(ResetPassword2Type::class);
  152.         $formreset->handleRequest($request);
  153.         if($formreset->isSubmitted() && $formreset->isValid()){
  154.             $email=$formreset->getData()['email'];
  155.             $user=$resetpassword->getUser();
  156.             //check email with bfresetpassworduser email
  157.             if($email != $resetpassword->getUser()->getEmail())
  158.             {
  159.                 $formreset->get('email')->addError(new FormError('Email inconnu'));
  160.             }
  161.             else
  162.             {
  163.                 $password $passwordEncoder->encodePassword($user$formreset->getData()['plainPassword']);
  164.                 $user->setPassword($password);
  165.                 // 4) save the User!
  166.                 $entityManager $this->getDoctrine()->getManager();
  167.                 $entityManager->persist($user);
  168.                 $entityManager->flush();
  169.                 //remove the resetpasswordrequest
  170.                 $entityManager->remove($resetpassword);
  171.                 $entityManager->flush();
  172.                 return $this->render('security/resetpasswordconfirmation.html.twig', [
  173.                     'passwordchanged' => true,
  174.                 ]);
  175.             }
  176.         }
  177.         if($formreset->isSubmitted() && !$formreset->isValid())
  178.         {
  179.             foreach($formreset->getErrors(true) as $error)
  180.                 $this->addFlash('danger'"(".$error->getOrigin()->getName().") ".$error->getMessage());
  181.             return $this->redirect($request->getUri());
  182.         }
  183.         return $this->render('security/resetpassword.html.twig', [
  184.             'formreset' => $formreset->createView(),
  185.         ]);
  186.     }
  187.     /**
  188.      * @Route ("/security/account/removerole/{role}/{userid}", name="app_removeuserrole")
  189.      */
  190.     public function RemoveRoleFromUser(string $roleint $userid)
  191.     {
  192.         $this->denyAccessUnlessGranted('ROLE_ADMIN');
  193.         $user$this->getDoctrine()->getRepository(CBRCUser::class)->find($userid);
  194.         if(!$user)
  195.             throw new NotFoundHttpException();
  196.         $roles $user->getRoles();
  197.         if (($key array_search($role$roles)) !== false) {
  198.             unset($roles[$key]);
  199.         }
  200.         $user->setRoles($roles);
  201.         $em $this->getDoctrine()->getManager();
  202.         $em->persist($user);
  203.         $em->flush();
  204.         $this->addFlash('success''Les accès ont été retirés à l\'utilisateur');
  205.         return $this->redirectToRoute('app_accessmanager');
  206.     }
  207.     /**
  208.      * @Route ("/security/account/superadmin/setdefault", name="app_superadmin_setdefault")
  209.      */
  210.     public function SetDefaultSuperAdmin(Request $request): \Symfony\Component\HttpFoundation\RedirectResponse
  211.     {
  212.         $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
  213.         //Check if there is an role_super_admin in the database
  214.         $userrepository =$this->getDoctrine()->getRepository(CBRCUser::class);
  215.         $superadmins $userrepository->findByRole('ROLE_SUPER_ADMIN');
  216.         if(count($superadmins)<=1)
  217.         {
  218.             //set the first user
  219.             $firstuser $userrepository->findFirst();
  220.             $firstuser->setRoles(array('ROLE_SUPER_ADMIN'));
  221.             $entityManager $this->getDoctrine()->getManager();
  222.             $entityManager->persist($firstuser);
  223.             $entityManager->flush();
  224.             $this->addFlash('primary''Super admin role add default');
  225.         }
  226.         return $this->redirectToRoute('account');
  227.     }
  228.     /**
  229.      * @Route ("/security/account/superadmin/add/{email}", name="app_superadmin_add")
  230.      */
  231.     public function AddSuperAdmin($emailRequest $request): \Symfony\Component\HttpFoundation\RedirectResponse
  232.     {
  233.         $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
  234.         //Check if there is an role_super_admin in the database
  235.         $user =$this->getDoctrine()->getRepository(CBRCUser::class)->findOneBy(['email'=>$email]);
  236.         if($user!=null)
  237.         {
  238.             //set the first user
  239.             $user->setRoles(array('ROLE_SUPER_ADMIN'));
  240.             $entityManager $this->getDoctrine()->getManager();
  241.             $entityManager->persist($user);
  242.             $entityManager->flush();
  243.             $this->addFlash('primary''Super admin role add');
  244.         }
  245.         return $this->redirectToRoute('account');
  246.     }
  247.     /**
  248.      * @Route ("/security/account/superadmin/remove/{email}", name="app_superadmin_remove")
  249.      */
  250.     public function RemoveSuperAdmin($emailRequest $request): \Symfony\Component\HttpFoundation\RedirectResponse
  251.     {
  252.         $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN');
  253.         //Check if there is an role_super_admin in the database
  254.         $user =$this->getDoctrine()->getRepository(CBRCUser::class)->findOneBy(['email'=>$email]);
  255.         if($user!=null)
  256.         {
  257.             //set the first user
  258.             $user->setRoles(array(''));
  259.             $entityManager $this->getDoctrine()->getManager();
  260.             $entityManager->persist($user);
  261.             $entityManager->flush();
  262.             $this->addFlash('primary''Super admin role remove');
  263.         }
  264.         return $this->redirectToRoute('account');
  265.     }
  266.     private function ClearUserResetPassword(CBRCUser $user)
  267.     {
  268.         //get bfreset from user id
  269.         $resetpassword $this->getDoctrine()->getRepository(CBRCResetPassword::class)->findOneBy(['user'=>$user]);
  270.         if($resetpassword!=null)
  271.         {
  272.             $entityManager $this->getDoctrine()->getManager();
  273.             $entityManager->remove($resetpassword);
  274.             $entityManager->flush();
  275.         }
  276.     }
  277.     private function GetUniqueToken()
  278.     {
  279.         $randomstring="";
  280.         $unique=false;
  281.         $resetrepository $this->getDoctrine()->getRepository(CBRCResetPassword::class);
  282.         while(!$unique)
  283.         {
  284.             $randomstring Secure::GenerateKey(20);
  285.             $resetpassword $resetrepository->findOneBy(array('token'=>$randomstring));
  286.             $unique=($resetpassword==null);
  287.         }
  288.         return $randomstring;
  289.     }
  290. }