src/Controller/SecurityController.php line 48

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace App\Controller;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  16. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  17. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  18. use App\Entity\User;
  19. use App\Repository\UserRepository;
  20. use Doctrine\Persistence\ManagerRegistry;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Symfony\Component\Security\Core\Security;
  23. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  24. use Symfony\Component\Mailer\MailerInterface;
  25. use Symfony\Component\Mime\Email;
  26. /**
  27.  * Controller used to manage the application security.
  28.  * See https://symfony.com/doc/current/security/form_login_setup.html.
  29.  *
  30.  * @author Ryan Weaver <weaverryan@gmail.com>
  31.  * @author Javier Eguiluz <javier.eguiluz@gmail.com>
  32.  */
  33. class SecurityController extends AbstractController {
  34.     use TargetPathTrait;
  35.     private $security;
  36.     public function __construct(Security $security) {
  37.         $this->security $security;
  38.     }
  39.     #[Route('/login'name'security_login')]
  40.     public function login(Request $requestAuthenticationUtils $helperUserPasswordHasherInterface $passwordHasherManagerRegistry $entityManager): Response {
  41.         // if user is already logged in, don't display the login page again
  42.         if ($this->getUser()) {
  43. //            if ($this->security->isGranted('ROLE_ADMIN')) {
  44.             return $this->redirectToRoute('dashboard');
  45. //            }
  46.         }
  47.         $users $entityManager->getRepository(User::class)->findAll();
  48.         // create the user and hash its password
  49. //        $user = new User();
  50. //        $user->setFullName("Visitor");
  51. //        $user->setUsername("user");
  52. //        $user->setEmail("visitor@evenews.com");
  53. //        $user->setRoles(['ROLE_USER']);
  54. //        $user->setEnabled('1');
  55. //
  56. //        $hashedPassword = $passwordHasher->hashPassword($user, '123456');
  57. //        $user->setPassword($hashedPassword);
  58. //
  59. //        $entityManager->persist($user);
  60. //        $entityManager->flush();
  61.         ///end create the user
  62.         // this statement solves an edge-case: if you change the locale in the login
  63.         // page, after a successful login you are redirected to a page in the previous
  64.         // locale. This code regenerates the referrer URL whenever the login page is
  65.         // browsed, to ensure that its locale is always the current one.
  66.         $this->saveTargetPath($request->getSession(), 'main'$this->generateUrl('dashboard'));
  67.         return $this->render('security/login.html.twig', [
  68.                     // last username entered by the user (if any)
  69.                     'last_username' => $helper->getLastUsername(),
  70.                     // last authentication error (if any)
  71.                     'error' => $helper->getLastAuthenticationError(),
  72.                     'users' => $users,
  73.         ]);
  74.     }
  75.     /**
  76.      * This is the route the user can use to logout.
  77.      *
  78.      * But, this will never be executed. Symfony will intercept this first
  79.      * and handle the logout automatically. See logout in config/packages/security.yaml
  80.      */
  81.     #[Route('/logout'name'security_logout')]
  82.     public function logout(): void {
  83.         throw new \Exception('This should never be reached!');
  84.     }
  85.     #[Route('/pwForgotten'name'security_pw_forgotten')]
  86.     public function pwForgotten(Request $request): Response {
  87.         // if user is already logged in, don't display the login page again
  88.         return $this->render('security/pwForgotten.html.twig', [
  89.         ]);
  90.     }
  91.     #[Route('/pwForgotten/send'name'security_pw_forgotten_send'methods: ['POST'])]
  92.     public function pwForgottenSend(Request $requestMailerInterface $mailerUserRepository $usersEntityManagerInterface $entityManager): Response {
  93.         $user $users->findOneByEmail($request->get('email'));
  94.         if ($user) {
  95.             $this->addFlash('success''An email to reset your password has been sent to your inbox : ' $request->get('email'));
  96.             if ($user->getTokenreset() != null) {
  97.                 $token $user->getTokenreset();
  98.             } else {
  99.                 $str 'A=u_cs3Lmn' $user->getId();
  100.                 $token str_shuffle($str);
  101. //                dump($user);die;
  102.                 $user->setTokenreset($token);
  103.                 $entityManager->persist($user);
  104.                 $entityManager->flush();
  105.             }
  106.             $email = (new TemplatedEmail())
  107.                     ->from('no-reply@evenews.com')
  108.                     ->to($request->get('email'))
  109.                     ->subject('Evenews registration')
  110.                     // path of the Twig template to render
  111.                     ->htmlTemplate('emails/pwForgotten.html.twig')
  112.                     // pass variables (name => value) to the template
  113.                     ->context([
  114.                 'token' => $token,
  115.                 'user' => $user,
  116.                     ])
  117.             ;
  118.             $mailer->send($email);
  119.         } else {
  120.             $this->addFlash('warning''No account with this email: ' $request->get('email'));
  121.         }
  122.         return $this->redirectToRoute('security_pw_forgotten');
  123.     }
  124.     #[Route('/reset/tk-{token}/password'name'security_pw_reset')]
  125.     public function resetPassword(Request $request$tokenUserRepository $users): Response {
  126.         // if user is already logged in, don't display the login page again
  127.         $user $users->findOneByTokenreset($token);
  128.         if ($user) {
  129.             
  130.         } else {
  131.             $this->addFlash('warning''Request expired, please try again...');
  132.             return $this->redirectToRoute('security_pw_forgotten');
  133.         }
  134.         return $this->render('security/resetPw.html.twig', [
  135.                     'user' => $user
  136.         ]);
  137.     }
  138.     #[Route('/'name'security_pw_reset_send'methods: ['POST'])]
  139.     public function resetPasswordSend(Request $requestUserRepository $usersUserPasswordHasherInterface $passwordHasherEntityManagerInterface $entityManager) {
  140.         $user $users->findOneByTokenreset($request->get('_token'));
  141.         if ($user) {
  142.             $this->addFlash('success''Your password has been changed with success.');
  143.             $hashedPassword $passwordHasher->hashPassword($user$request->get('_password'));
  144.             $user->setPassword($hashedPassword);
  145.             $user->setTokenreset(null);
  146.             $entityManager->persist($user);
  147.             $entityManager->flush();
  148. //            $message = \Swift_Message::newInstance()
  149. //                    ->setSubject('Evenews: New Password')
  150. //                    ->setFrom(['contact@evenews.com' => 'Evenews'])
  151. //                    ->setTo($user->getEmail())
  152. //                    ->setBody(
  153. //                    $this->renderView('emails/pwforgotten.html.twig', array('email' => $request->get('email'), 'token' => $token)
  154. //                    ), 'text/html'
  155. //            );
  156. //            $this->get('mailer')->send($message);
  157.         } else {
  158.             $this->addFlash('warning''Request expired, please try again');
  159.         }
  160.         return $this->redirectToRoute('security_login');
  161.     }
  162.     #[Route('/email/verification'name'security_email_verification')]
  163.     public function emailVerification(Request $requestUserRepository $usersEntityManagerInterface $entityManager) {
  164.         $user $this->getUser();
  165.         if ($user->getEmailVerification() != "1") {
  166.             $str 'Au_5B3L_mxXbn' $user->getId();
  167.             $token str_shuffle($str);
  168.             $user->setEmailVerification($token);
  169.             $entityManager->persist($user);
  170.             $entityManager->flush();
  171. //            $message = \Swift_Message::newInstance()
  172. //                    ->setSubject('Email confirmation')
  173. //                    ->setFrom('contact@evenews.com')
  174. //                    ->setTo($user->getEmail())
  175. //                    ->setBody(
  176. //                    $this->renderView('emails/accountCreated.html.twig', array('user' => $user, 'token' => $token)
  177. //                    ), 'text/html'
  178. //            );
  179. //            $this->get('mailer')->send($message);
  180.             $this->addFlash('warning''An email has been sent to confirm your adress ' $user->getEmail());
  181.         } else {
  182.             $this->addFlash('warning''Email already verified');
  183.         }
  184.         if ($this->security->isGranted('ROLE_USER')) {
  185.             return $this->redirectToRoute('dashboard');
  186.         } else {
  187.             return $this->redirectToRoute('security_login');
  188.         }
  189.     }
  190.     #[Route('/email/confirmation/tk/{token}'name'security_email_confirmation')]
  191.     public function emailConfirmation(Request $request$tokenUserRepository $usersEntityManagerInterface $entityManager) {
  192.         $user $users->findOneByEmailVerification($token);
  193.         if ($user->getEmailVerification() != "1") {
  194.             $user->setEmailVerification('1');
  195.             $entityManager->persist($user);
  196.             $entityManager->flush();
  197. //            $message = \Swift_Message::newInstance()
  198. //                    ->setSubject('Email confirmation')
  199. //                    ->setFrom('contact@evenews.com')
  200. //                    ->setTo($user->getEmail())
  201. //                    ->setBody(
  202. //                    $this->renderView('emails/accountCreated.html.twig', array('user' => $user, 'token' => $token)
  203. //                    ), 'text/html'
  204. //            );
  205. //            $this->get('mailer')->send($message);
  206.             $this->addFlash('success''Email confirmed with success' $user->getEmail());
  207.         } else {
  208.             $this->addFlash('info''Email already confirmed');
  209.         }
  210.         return $this->render('security/emailConfirmed.html.twig', [
  211.                     'user' => $user
  212.         ]);
  213.     }
  214. }