src/Controller/SecurityController.php line 77

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use App\Repository\ShopRepository;
  5. use App\Repository\UserRepository;
  6. use App\Security\EmailVerifier;
  7. use App\Service\UserService;
  8. use Doctrine\ORM\EntityManagerInterface;
  9. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  10. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Request;;
  13. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
  16. use Symfony\Component\Mailer\MailerInterface;
  17. use Symfony\Component\Mime\Address;
  18. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  19. use Symfony\Component\Routing\Annotation\Route;
  20. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  21. use Symfony\Contracts\Translation\TranslatorInterface;
  22. use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
  23. use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
  24. use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
  25. /**
  26.  * @Route("/{_locale<%app.supported_locales%>}/")
  27.  */
  28. class SecurityController extends AbstractController
  29. {
  30.     use ResetPasswordControllerTrait;
  31.     private $resetPasswordHelper;
  32.     private $entityManager;
  33.     private $translator;
  34.     private $mailer;
  35.     private $mailer_sender;
  36.     private EmailVerifier $emailVerifier;
  37.     public function __construct(ResetPasswordHelperInterface $resetPasswordHelperParameterBagInterface $paramsTranslatorInterface $translatorMailerInterface $mailerEmailVerifier $emailVerifier)
  38.     {
  39.         $this->translator=$translator;
  40.         $this->mailer=$mailer;
  41.         $this->resetPasswordHelper $resetPasswordHelper;
  42.         $this->emailVerifier $emailVerifier;
  43.         //$this->entityManager = $entityManager;
  44.         $this->mailer_sender $params->get('app.mailer_sender');
  45.     }
  46.     /**
  47.      * @Route("login", name="app_login")
  48.      */
  49.     public function login(AuthenticationUtils $authenticationUtilsRequest $request): Response
  50.     {
  51.         // if ($this->getUser()) {
  52.         //     return $this->redirectToRoute('target_path');
  53.         // }
  54.         // get the login error if there is one
  55.         $error $authenticationUtils->getLastAuthenticationError();
  56.         // last username entered by the user
  57.         $lastUsername $authenticationUtils->getLastUsername();
  58.         return $this->render('security/login.html.twig', ['last_username' => $lastUsername'error' => $error]);
  59.     }
  60.     /**
  61.      * @Route("activation", name="app_activation")
  62.      */
  63.     public function activation(AuthenticationUtils $authenticationUtilsRequest $request): Response
  64.     {
  65.         return $this->render('security/activation.html.twig');
  66.     }
  67.     /**
  68.      * @Route("logout", name="app_logout")
  69.      */
  70.     public function logout(): void
  71.     {
  72.         throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  73.     }
  74.     /**
  75.      * @Route("login/activation", name="app_login_with_token")
  76.      */
  77.     public function loginWithToken(
  78.         AuthenticationUtils $authenticationUtils,
  79.         ShopRepository $shopRepository,
  80.         UserRepository $userRepository,
  81.         UserPasswordHasherInterface $userPasswordHasher,
  82.         Request $request,
  83.         UserService $userService
  84.         ): Response
  85.     {
  86.         if($token $request->request->get('token') ) {
  87.             if($shop=$shopRepository->findOneByLoginHash($token)) {
  88.                 //echo $shop->getName();
  89.                 $email=$request->request->get('email');
  90.                 if(!$user=$userRepository->findOneByEmail($email)) {
  91.                     $randomtime()."_".$rand substr(uniqid(''true), -5);;
  92.                     $temp_user=new User();
  93.                     //$temp_user->setFirstname($shop->getName()."_".$random);
  94.                     //$temp_user->setLastname($shop->getName()."_".$random);
  95.                     $temp_user->setEmail($email);
  96.                     $temp_user->setShop($shop);
  97.                     $temp_user->addShop($shop);
  98.                     $temp_user->setRoles(array('ROLE_USER'));
  99.                     $temp_user->setPassword(
  100.                         $userPasswordHasher->hashPassword(
  101.                             $temp_user,
  102.                             $random
  103.                         )
  104.                     );
  105.                     $userRepository->add($temp_user);
  106.                     //$this->processSendingPasswordResetEmail($temp_user);
  107.                     $userService->authenticate($temp_user$request);
  108.                     $resetToken $this->resetPasswordHelper->generateResetToken($temp_user);
  109.                     $this->emailVerifier->sendEmailConfirmation('app_verify_email'$temp_user,
  110.                         (new TemplatedEmail())
  111.                             ->from(new Address('support@bak2.com''Bak2'))
  112.                             ->to($temp_user->getEmail())
  113.                             ->subject('Please Confirm your Email')
  114.                             ->htmlTemplate('registration/confirmation_email.html.twig')
  115.                             ->context([
  116.                                 'resetToken' => $resetToken,
  117.                             ])
  118.                     );
  119.                     return $this->redirectToRoute('app_stock_index');
  120.                 }
  121.                 else {
  122.                     $this->addFlash('error'$this->translator->trans("Vous avez déja activé votre compte"));
  123.                     return $this->redirectToRoute('app_login');
  124.                     //user exists
  125.                 }
  126.             }
  127.             else {
  128.                 //unknown token
  129.                 $this->addFlash('error'$this->translator->trans("Code d'activation inconnu"));
  130.                 return $this->redirectToRoute('app_login');
  131.             }
  132.         }
  133.         else {
  134.             $this->addFlash('error'$this->translator->trans("Code d'activation inconnu"));
  135.             return $this->redirectToRoute('app_login');
  136.             // no token
  137.             //throw new CustomUserMessageAuthenticationException('Unknown token');
  138.         }
  139.         return $this->redirectToRoute('app_login');
  140.     }
  141.     /**
  142.      * @Route("login/{shopName}/{hash}", name="app_login_auto")
  143.      */
  144.     public function autoLogin($shopName$hashShopRepository $shopRepositoryUserRepository $userRepositoryUserPasswordHasherInterface $userPasswordHasherRequest $requestUserService $userService): Response
  145.     {
  146.         if($shop=$shopRepository->findOneByName($shopName)) {
  147.             if($shop->getLoginHash() && $shop->getLoginHash()==$hash) {
  148.                 $randomtime()."_".$rand substr(uniqid(''true), -5);;
  149.                 $temp_user=new User();
  150.                 $temp_user->setFirstname($shop->getName()."_".$random);
  151.                 $temp_user->setLastname($shop->getName()."_".$random);
  152.                 $temp_user->setEmail($shop->getMachineName().".".$random."@bak2.com");
  153.                 $temp_user->setShop($shop);
  154.                 $temp_user->addShop($shop);
  155.                 $temp_user->setRoles(array('ROLE_USER'));
  156.                 $temp_user->setPassword(
  157.                     $userPasswordHasher->hashPassword(
  158.                         $temp_user,
  159.                         $random
  160.                     )
  161.                 );
  162.                 $userRepository->add($temp_user);
  163.                 $userService->authenticate($temp_user$request);
  164. /*
  165.                 $request->request->set('email',$temp_user->getEmail());
  166.                 $request->request->set('password',$random);
  167.                 $loginFormAuthenticator->authenticate(
  168.                     $request
  169.                 );
  170. */
  171.                 //$loginService->login($temp_user, $request);
  172.                 //Security::login();
  173.             }
  174.         }
  175. //die();
  176.         return $this->redirectToRoute('app_stock_index');
  177.     }
  178.     private function processSendingPasswordResetEmail(User $user)
  179.     {
  180.         // Do not reveal whether a user account was found or not.
  181.         if (!$user) {
  182.             return $this->redirectToRoute('app_login');
  183.         }
  184.         try {
  185.             $resetToken $this->resetPasswordHelper->generateResetToken($user);
  186.         } catch (ResetPasswordExceptionInterface $e) {
  187.             // If you want to tell the user why a reset email was not sent, uncomment
  188.             // the lines below and change the redirect to 'app_forgot_password_request'.
  189.             // Caution: This may reveal if a user is registered or not.
  190.             //
  191.             $this->addFlash('reset_password_error'sprintf(
  192.                 '%s - %s',
  193.                 $this->translator->trans(ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, [], 'ResetPasswordBundle'),
  194.                 $this->translator->trans($e->getReason(), [], 'ResetPasswordBundle')
  195.             ));
  196.             return $this->redirectToRoute('app_check_email');
  197.         }
  198.         $email = (new TemplatedEmail())
  199.             ->from(new Address($this->mailer_sender'Bak2'))
  200.             ->to($user->getEmail())
  201.             ->subject('Account created, please change your password')
  202.             ->htmlTemplate('reset_password/email.html.twig')
  203.             ->context([
  204.                 'resetToken' => $resetToken,
  205.             ])
  206.         ;
  207.         try {
  208.             $this->mailer->send($email);
  209.         } catch (TransportExceptionInterface $e) {
  210.             var_dump($e);
  211.             // some error prevented the email sending; display an
  212.             // error message or try to resend the message
  213.         }
  214.         // Store the token object in session for retrieval in check-email route.
  215.         $this->setTokenObjectInSession($resetToken);
  216.        //return $this->redirectToRoute('app_check_email');
  217.     }
  218. }