vendor/appaydin/pd-user/Controller/SecurityController.php line 44

Open in your IDE?
  1. <?php
  2. /**
  3.  * This file is part of the pd-admin pd-user package.
  4.  *
  5.  * @package     pd-user
  6.  * @license     LICENSE
  7.  * @author      Ramazan APAYDIN <apaydin541@gmail.com>
  8.  * @link        https://github.com/appaydin/pd-user
  9.  */
  10. namespace Pd\UserBundle\Controller;
  11. use Pd\UserBundle\Configuration\ConfigInterface;
  12. use Pd\UserBundle\Event\UserEvent;
  13. use Pd\UserBundle\Model\GroupInterface;
  14. use Pd\UserBundle\Model\UserInterface;
  15. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  16. use Symfony\Component\Form\Exception\InvalidArgumentException;
  17. use Symfony\Component\Form\FormError;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpFoundation\Response;
  20. use Symfony\Component\Mailer\MailerInterface;
  21. use Symfony\Component\Mime\Address;
  22. use Symfony\Component\Mime\Email;
  23. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  24. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  25. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  26. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  27. use Symfony\Contracts\Translation\TranslatorInterface;
  28. class SecurityController extends AbstractController
  29. {
  30.     public function __construct(
  31.         private TranslatorInterface $translator,
  32.         private MailerInterface $mailer,
  33.         private EventDispatcherInterface $dispatcher)
  34.     {
  35.     }
  36.     /**
  37.      * Login.
  38.      */
  39.     public function login(AuthenticationUtils $authenticationUtils): Response
  40.     {
  41.         // Check Auth
  42.         if ($this->checkAuth()) {
  43.             return $this->redirectToRoute($this->getParameter('login_redirect'));
  44.         }
  45.         // Render
  46.         return $this->render($this->getParameter('template_path') . '/security/login.html.twig', [
  47.             'last_username' => $authenticationUtils->getLastUsername(),
  48.             'error' => $authenticationUtils->getLastAuthenticationError(),
  49.             'user_registration' => $this->getParameter('user_registration'),
  50.         ]);
  51.     }
  52.     /**
  53.      * Registration.
  54.      */
  55.     public function register(Request $requestUserPasswordHasherInterface $hasher): Response
  56.     {
  57.         // Check Auth
  58.         if ($this->checkAuth()) {
  59.             return $this->redirectToRoute($this->getParameter('login_redirect'));
  60.         }
  61.         // Check Disable Register
  62.         if (!$this->getParameter('user_registration')) {
  63.             $this->addFlash('error'$this->translator->trans('security.registration_disable'));
  64.             return $this->redirectToRoute('security_login');
  65.         }
  66.         // Create User
  67.         $user $this->getParameter('user_class');
  68.         $user = new $user();
  69.         if (!$user instanceof UserInterface) {
  70.             throw new InvalidArgumentException();
  71.         }
  72.         // Dispatch Register Event
  73.         if ($response $this->dispatcher->dispatch(new UserEvent($user), UserEvent::REGISTER_BEFORE)->getResponse()) {
  74.             return $response;
  75.         }
  76.         // Create Form
  77.         $form $this->createForm($this->getParameter('register_type'), $user);
  78.         // Handle Form Submit
  79.         $form->handleRequest($request);
  80.         if ($form->isSubmitted() && $form->isValid()) {
  81.             // Get Doctrine
  82.             $em $this->getDoctrine()->getManager();
  83.             // Encode Password
  84.             $password $hasher->hashPassword($user$form->get('plainPassword')->getData());
  85.             $user->setPassword($password);
  86.             // User Confirmation
  87.             if ($this->getParameter('email_confirmation')) {
  88.                 // Disable User
  89.                 $user->setActive(false);
  90.                 // Create Confirmation Token
  91.                 if (empty($user->getConfirmationToken()) || null === $user->getConfirmationToken()) {
  92.                     $user->createConfirmationToken();
  93.                 }
  94.                 // Send Confirmation Email
  95.                 $emailBody = [
  96.                     'confirmationUrl' => $this->generateUrl('security_register_confirm',
  97.                         ['token' => $user->getConfirmationToken()],
  98.                         UrlGeneratorInterface::ABSOLUTE_URL),
  99.                 ];
  100.                 $this->sendEmail($user'email.account_confirmation''register'$emailBody);
  101.             } elseif ($this->getParameter('welcome_email')) {
  102.                 // Send Welcome
  103.                 $this->sendEmail($user'email.registration_complete''welcome');
  104.             }
  105.             // User Add Default Group
  106.             if ($group $this->getParameter('default_group')) {
  107.                 $getGroup $em->getRepository($this->getParameter('group_class'))->find($group);
  108.                 if ($getGroup instanceof GroupInterface) {
  109.                     $user->addGroup($getGroup);
  110.                 }
  111.             }
  112.             // Save User
  113.             $em->persist($user);
  114.             $em->flush();
  115.             // Dispatch Register Event
  116.             if ($response $this->dispatcher->dispatch(new UserEvent($user), UserEvent::REGISTER)->getResponse()) {
  117.                 return $response;
  118.             }
  119.             // Register Success
  120.             return $this->render($this->getParameter('template_path') . '/registration/registerSuccess.html.twig', [
  121.                 'user' => $user,
  122.             ]);
  123.         }
  124.         // Render
  125.         return $this->render($this->getParameter('template_path') . '/registration/register.html.twig', [
  126.             'form' => $form->createView(),
  127.         ]);
  128.     }
  129.     /**
  130.      * Registration Confirm Token.
  131.      */
  132.     public function registerConfirm(MailerInterface $mailerstring $token): Response
  133.     {
  134.         // Get Doctrine
  135.         $em $this->getDoctrine()->getManager();
  136.         // Find User
  137.         $user $em->getRepository($this->getParameter('user_class'))->findOneBy(['confirmationToken' => $token]);
  138.         if (null === $user) {
  139.             throw $this->createNotFoundException(sprintf($this->translator->trans('security.token_notfound'), $token));
  140.         }
  141.         // Enabled User
  142.         $user->setConfirmationToken(null);
  143.         $user->setActive(true);
  144.         // Send Welcome
  145.         if ($this->getParameter('welcome_email')) {
  146.             $this->sendEmail($user'email.registration_complete''welcome');
  147.         }
  148.         // Update User
  149.         $em->persist($user);
  150.         $em->flush();
  151.         // Dispatch Register Event
  152.         if ($response $this->dispatcher->dispatch(new UserEvent($user), UserEvent::REGISTER_CONFIRM)->getResponse()) {
  153.             return $response;
  154.         }
  155.         // Register Success
  156.         return $this->render($this->getParameter('template_path') . '/registration/registerSuccess.html.twig', [
  157.             'user' => $user,
  158.         ]);
  159.     }
  160.     /**
  161.      * Resetting Request.
  162.      */
  163.     public function resetting(Request $request): Response
  164.     {
  165.         // Check Auth
  166.         if ($this->checkAuth()) {
  167.             return $this->redirectToRoute($this->getParameter('login_redirect'));
  168.         }
  169.         // Build Form
  170.         $form $this->createForm($this->getParameter('resetting_type'));
  171.         // Handle Form Submit
  172.         $form->handleRequest($request);
  173.         if ($form->isSubmitted() && $form->isValid()) {
  174.             // Get Doctrine
  175.             $em $this->getDoctrine()->getManager();
  176.             // Find User
  177.             $user $em->getRepository($this->getParameter('user_class'))->findOneBy(['email' => $form->get('username')->getData()]);
  178.             if (null === $user) {
  179.                 $form->get('username')->addError(new FormError($this->translator->trans('security.user_not_found')));
  180.             } else {
  181.                 // Create TTL
  182.                 if ($user->isPasswordRequestNonExpired($this->getParameter('resetting_request_time'))) {
  183.                     $form->get('username')->addError(new FormError($this->translator->trans('security.resetpw_wait_resendig', ['%s' => ($this->getParameter('resetting_request_time') / 3600)])));
  184.                 } else {
  185.                     // Create Confirmation Token
  186.                     if (empty($user->getConfirmationToken()) || null === $user->getConfirmationToken()) {
  187.                         $user->createConfirmationToken();
  188.                         $user->setPasswordRequestedAt(new \DateTime());
  189.                     }
  190.                     // Send Resetting Email
  191.                     $emailBody = [
  192.                         'confirmationUrl' => $this->generateUrl('security_resetting_password',
  193.                             ['token' => $user->getConfirmationToken()],
  194.                             UrlGeneratorInterface::ABSOLUTE_URL
  195.                         ),
  196.                     ];
  197.                     $this->sendEmail($user'email.account_password_resetting''resetting'$emailBody);
  198.                     // Update User
  199.                     $em->persist($user);
  200.                     $em->flush();
  201.                     // Dispatch Register Event
  202.                     if ($response $this->dispatcher->dispatch(new UserEvent($user), UserEvent::RESETTING)->getResponse()) {
  203.                         return $response;
  204.                     }
  205.                     // Render
  206.                     return $this->render($this->getParameter('template_path') . '/resetting/resettingSuccess.html.twig', [
  207.                         'sendEmail' => true,
  208.                     ]);
  209.                 }
  210.             }
  211.         }
  212.         // Render
  213.         return $this->render($this->getParameter('template_path') . '/resetting/resetting.html.twig', [
  214.             'form' => $form->createView(),
  215.         ]);
  216.     }
  217.     /**
  218.      * Reset Password Form.
  219.      */
  220.     public function resettingPassword(Request $requestUserPasswordEncoderInterface $encoderstring $token): Response
  221.     {
  222.         // Get Doctrine
  223.         $em $this->getDoctrine()->getManager();
  224.         // Find User
  225.         $user $em->getRepository($this->getParameter('user_class'))->findOneBy(['confirmationToken' => $token]);
  226.         if (null === $user) {
  227.             throw $this->createNotFoundException(sprintf($this->translator->trans('security.token_notfound'), $token));
  228.         }
  229.         // Build Form
  230.         $form $this->createForm($this->getParameter('resetting_password_type'), $user);
  231.         // Handle Form Submit
  232.         $form->handleRequest($request);
  233.         if ($form->isSubmitted() && $form->isValid()) {
  234.             // Encode Password & Set Token
  235.             $password $encoder->encodePassword($user$form->get('plainPassword')->getData());
  236.             $user->setPassword($password)
  237.                 ->setConfirmationToken(null)
  238.                 ->setPasswordRequestedAt(null);
  239.             // Save User
  240.             $em->persist($user);
  241.             $em->flush();
  242.             // Dispatch Register Event
  243.             if ($response $this->dispatcher->dispatch(new UserEvent($user), UserEvent::RESETTING_COMPLETE)->getResponse()) {
  244.                 return $response;
  245.             }
  246.             // Send Resetting Complete
  247.             $this->sendEmail($user'email.password_resetting_completed''resetting-complete');
  248.             // Render Success
  249.             return $this->render($this->getParameter('template_path') . '/resetting/resettingSuccess.html.twig', [
  250.                 'sendEmail' => false,
  251.             ]);
  252.         }
  253.         // Render
  254.         return $this->render($this->getParameter('template_path') . '/resetting/resettingPassword.html.twig', [
  255.             'token' => $token,
  256.             'form' => $form->createView(),
  257.         ]);
  258.     }
  259.     /**
  260.      * Check User Authorized.
  261.      */
  262.     private function checkAuth(): bool
  263.     {
  264.         return $this->isGranted('IS_AUTHENTICATED_FULLY') || $this->isGranted('IS_AUTHENTICATED_REMEMBERED');
  265.     }
  266.     /**
  267.      * Send Mail.
  268.      */
  269.     private function sendEmail(UserInterface $userstring $subjectstring $templateId, array $data = []): void
  270.     {
  271.         // Create Email
  272.         $email = (new Email())
  273.             ->from(new Address($this->getParameter('mail_sender_address'), $this->getParameter('mail_sender_name')))
  274.             ->to($user->getEmail())
  275.             ->subject($this->translator->trans($subject))
  276.             ->html($this->renderView($this->getParameter('template_path') . "/email/{$templateId}.html.twig"array_merge(['user' => $user], $data)));
  277.         // Send
  278.         $this->mailer->send($email);
  279.     }
  280.     /**
  281.      * Override Parameters
  282.      */
  283.     protected function getParameter(string $name)
  284.     {
  285.         return $this->has('app.params') ? $this->get('app.params')->get($name) : parent::getParameter($name);
  286.     }
  287.     /**
  288.      * Add Custom Services
  289.      */
  290.     public static function getSubscribedServices()
  291.     {
  292.         return array_merge([
  293.             'app.params' => '?' ConfigInterface::class,
  294.         ], parent::getSubscribedServices());
  295.     }
  296. }