src/StartPlatz/Bundle/UserBundle/Controller/AuthenticationController.php line 231

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\StartPlatz\Bundle\UserBundle\Controller;
  3. use App\StartPlatz\Bundle\MemberBundle\Entity\Member;
  4. use App\StartPlatz\Bundle\StartupBundle\Entity\Application;
  5. use App\StartPlatz\Bundle\StartupBundle\Entity\Batch;
  6. use App\StartPlatz\Bundle\UserBundle\Form\SetPasswordFormType;
  7. use App\StartPlatz\Bundle\WebsiteBundle\Utility\Utility;
  8. use Doctrine\DBAL\Driver\Connection;
  9. use Exception;
  10. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  11. use Symfony\Component\Mailer\MailerInterface;
  12. use Symfony\Component\Mime\Address;
  13. use Symfony\Component\Mime\Email;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  16. use App\StartPlatz\Bundle\FeedbackBundle\CallbackService;
  17. use App\StartPlatz\Bundle\UserBundle\Entity\User;
  18. use App\StartPlatz\Bundle\UserBundle\Entity\UserRepository;
  19. use App\StartPlatz\Bundle\UserBundle\Form\LoginFormType;
  20. use App\StartPlatz\Bundle\UserBundle\Form\LostPasswordFormType;
  21. use App\StartPlatz\Bundle\UserBundle\Form\RegistrationFormType;
  22. use App\StartPlatz\Bundle\UserBundle\Security\LoginLink\Token;
  23. use Startplatz\Bundle\WordpressIntegrationBundle\Annotation\WordpressResponse;
  24. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  25. use Symfony\Component\HttpFoundation\RedirectResponse;
  26. use Symfony\Component\HttpFoundation\Request;
  27. use Symfony\Component\HttpFoundation\Response;
  28. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  29. use Symfony\Component\Routing\RouterInterface;
  30. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  31. use Symfony\Component\Security\Core\Security as SymfonySecurity;
  32. class AuthenticationController extends AbstractController
  33. {
  34.     public function __construct(private readonly SessionInterface             $session, private readonly RouterInterface              $router, private readonly UserPasswordEncoderInterface $encoder, private readonly MailerInterface              $mailer, private readonly CallbackService              $callbackService, private readonly Connection                   $connection)
  35.     {
  36.     }
  37.     /**
  38.      * @Route("/usfb/{md5}", name="unsubscribe_user_bulkmail")
  39.      * @param $md5
  40.      * @return RedirectResponse|Response
  41.      */
  42.     public function unsubscribeUserBulkmailAction($md5)
  43.     {
  44.         $em $this->getDoctrine()->getManager();
  45.         if (!$user $em->getRepository(User::class)->findOneBy(['salt' => $md5])) {
  46.             return new Response('sorry, not found ');
  47.         }
  48.         if (!$user->getisOnBlacklist()) {
  49.             $member $em->getRepository(Member::class)->find($user->getMemberId());
  50.             $em->getRepository(Member::class)->addTag('blacklist'$member$user->getEmail(), $logText 'User has unsubscribed');
  51.         }
  52.         $redirect '/x/feed';
  53.         $hash Token::createHash($user->getEmail(), $redirect);
  54.         $this->session->getFlashBag()->add('notice''SUCCESS you have been unsubscribed ');
  55.         return $this->redirect($this->generateUrl('login_email_check', [
  56.             'email' => $user->getEmail(),
  57.             'hash' => $hash,
  58.             'redirect' => $redirect,
  59.         ]));
  60.     }
  61.     /**
  62.      * @Route("/authentication/magic-link", name="login_magic_link")
  63.      */
  64.     public function magicLinkAction(Request $request)
  65.     {
  66.         // Prüfe die Anfragemethode
  67.         if (!$request->isMethod('POST')) {
  68.             return new Response('Invalid request.'405);
  69.         }
  70.         $em $this->getDoctrine()->getManager();
  71.         $email strtolower((string) $request->get('email'));
  72.         /** @var Member $member */
  73.         if (!$member $em->getRepository(Member::class)->findOneBy(['email' => $email])) {
  74.             return new Response(''400);
  75.         }
  76.         /*
  77.         if (!$user = $this->getUser()){
  78.             $toEmail = 'lorenz.graef@startplatz.de';
  79.             $mailText = "Member mit E-Mail {$member->getEmail()} und firstName {$member->getFirstName()} und lastName {$member->getLastName()} versucht sich einzuloggen" ;
  80.             $mailSubject = 'Login Versuch';
  81.             $fromEmail = "lorenz.graef@startplatz.de";
  82.             $fromName = "System per Allmeda - SOS";
  83.             $bodyType = 'html';
  84.             $sendResult = Utility::sendAlertMailPerN8N( $toEmail, $mailText, $mailSubject, $fromEmail, $fromName, $bodyType);
  85.             return new Response('please try later', 400);
  86.         }
  87.         */
  88.         if ($redirect $request->request->get('targetPath')) {
  89.             if ($redirect[0] != "/") {
  90.                 $redirect "/" $redirect;
  91.             }
  92.         } elseif ($redirect $request->get('targetPath')) {
  93.             ## do nothing
  94.         } else {
  95.             $redirect "/x/home";
  96.         }
  97.         if (!$action $request->get('action')) {
  98.             $action 'setPassword';
  99.         }
  100.         $hash Token::createHash($email$redirect);
  101.         $data = ['email' => $email'redirect' => $redirect];
  102.         $loginLink $this->generateUrl('login_email_check', ['email' => $data['email'], 'hash' => $hash'redirect' => $data['redirect'], 'action' => $action]);
  103.         $loginLink $request->getSchemeAndHttpHost() . $loginLink;
  104.         $payload json_encode([
  105.             'memberFirstName' => $member->getFirstName(),
  106.             'memberName' => $member->getName(),
  107.             'memberEmail' => $member->getEmail(),
  108.             'magicLink' => $loginLink,
  109.         ]);
  110.         $callbackUrl "https://hooks.zapier.com/hooks/catch/1872803/2qid0ji/";
  111.         $this->callbackService->curl_callback($callbackUrl$payload);
  112.         return new Response('SUCCESS Magic Link sent to ' $email);
  113.     }
  114.     /**
  115.      * @Route("/authentication/magic-link-defense", name="login_magic_defense_link")
  116.      * @Security("is_granted('ROLE_USER')")
  117.      */
  118.     public function magicLinkDefenseAction(Request $request)
  119.     {
  120.         $em $this->getDoctrine()->getManager();
  121.         $email strtolower((string) $request->get('email'));
  122.         /** @var Member $member */
  123.         if (!$member $em->getRepository(Member::class)->findOneBy(['email' => $email])) {
  124.             return new Response(''400);
  125.         }
  126.         if ($redirect $request->request->get('targetPath')) {
  127.             if ($redirect[0] != "/") {
  128.                 $redirect "/" $redirect;
  129.             }
  130.         } elseif ($redirect $request->get('targetPath')) {
  131.             ## do nothing
  132.         } else {
  133.             $redirect "/x/home";
  134.         }
  135.         if (!$action $request->get('action')) {
  136.             $action 'setPassword';
  137.         }
  138.         $hash Token::createHash($email$redirect);
  139.         $data = ['email' => $email'redirect' => $redirect];
  140.         $loginLink $this->generateUrl('login_email_check', ['email' => $data['email'], 'hash' => $hash'redirect' => $data['redirect'], 'action' => $action]);
  141.         $loginLink $request->getSchemeAndHttpHost() . $loginLink;
  142.         $payload json_encode([
  143.             'memberFirstName' => $member->getFirstName(),
  144.             'memberName' => $member->getName(),
  145.             'memberEmail' => $member->getEmail(),
  146.             'magicLink' => $loginLink,
  147.         ]);
  148.         $callbackUrl "https://hooks.zapier.com/hooks/catch/1872803/2qid0ji/";
  149.         $this->callbackService->curl_callback($callbackUrl$payload);
  150.         return new Response('SUCCESS Magic Link sent to ' $email);
  151.     }
  152.     /* Gerrit stash membership 11.4.23
  153.         /**
  154.          * @Route("/x/membership/finalize/{account}/{productNumber}/{customerHash}", name="x_membership_booked")
  155.          *
  156.         public function newMembershipLogin(Request $request, $customerHash, $account, $productNumber = 0)
  157.         {
  158.             if (!$redirect = json_decode(base64_decode($request->get('redirect')))) {
  159.                 $redirect = json_decode(json_encode(array('path' => 'x_membership_first-steps', 'parameters' => array('productNumber' => $productNumber, 'account' => $account))));
  160.             }
  161.             $redirectUrl = $this->generateUrl($redirect->path, (array)$redirect->parameters);
  162.             //logged in
  163.             if ($user = $this->getUser()) {
  164.                 if (!ctype_digit($user->getPassword())) $this->redirect($redirectUrl);
  165.                 $form = $this->createSetPasswordForm($redirectUrl);
  166.                 $form->handleRequest($request);
  167.                 if ($form->isSubmitted() && $form->isValid()) {
  168.                     $em = $this->getDoctrine()->getManager();
  169.                     $user = $this->getUser();
  170.                     $data = $form->getData();
  171.                     $password = $data['new_password'];
  172.                     $newPasswordEncoded = $this->getUserPasswordEncoder()->encodePassword($user, $password);
  173.                     $user->setPassword($newPasswordEncoded);
  174.                     $em->getRepository(User::class)->add($user);
  175.                     return $this->redirect($redirectUrl);
  176.                 }
  177.                 //logged in, set password
  178.                 return $this->render('@StartPlatzAlphaBundle/Default/new.membership.login.html.twig', array(
  179.                     'setPasswordForm' => $form->createView(),
  180.                     'setPassword' => true,
  181.                     'redirect' => base64_encode(json_encode($redirect)),
  182.                 ));
  183.             }
  184.             //Not logged in, ask for email to send link.
  185.             return $this->render('@StartPlatzAlphaBundle/Default/new.membership.login.html.twig', array(
  186.                 'setPassword' => false,
  187.                 'targetPath' => $this->generateUrl($redirect->path, (array)$redirect->parameters),
  188.             ));
  189.         }
  190.     */
  191.     /**
  192.      * @Route("/login/", name="login")
  193.      */
  194.     public function loginAction(Request $request)
  195.     {
  196.         if ($targetPath $request->query->get('targetPath')) {
  197.             $parts parse_url((string) $targetPath);
  198.             $redirect $parts['path'];
  199.         } elseif ($targetPath $request->getSession()->get('_security.secured_area.target_path')) {
  200.             $parts parse_url((string) $targetPath);
  201.             $redirect $parts['path'];
  202.         } else {
  203.             $redirect $this->generateUrl('x_home');
  204.         }
  205.         return $this->showLogin($redirect$request);
  206.     }
  207.     protected function showLogin($redirect$request$registrationFormData = [], $forms = [])
  208.     {
  209.         $redirectRouteName null;
  210.         $session $request->getSession();
  211.         try {
  212.             $routingParameter $this->router->match($redirect);
  213.             $redirectRouteName $routingParameter['_route'];
  214.         } catch (Exception) {
  215.         }
  216.         if ($this->getUser()) {
  217.             return $this->redirect($redirect ?: $this->generateUrl('x_home'));
  218.         }
  219.         if ($request->attributes->has(SymfonySecurity::AUTHENTICATION_ERROR)) {
  220.             $error $request->attributes->get(SymfonySecurity::AUTHENTICATION_ERROR);
  221.         } else {
  222.             $error $session->get(SymfonySecurity::AUTHENTICATION_ERROR);
  223.             $session->remove(SymfonySecurity::AUTHENTICATION_ERROR);
  224.         }
  225.         if ($error) {
  226.             $session->getFlashBag()->add('notice'$this->renderView('@StartPlatzUserBundle/Authentication/loginErrorFlash.html.twig'));
  227.         }
  228.         if (!array_key_exists('registrationForm'$forms)) {
  229.             $forms['registrationForm'] = $this->createRegistrationForm($redirect$registrationFormData);
  230.         }
  231.         if (!array_key_exists('pwlostForm'$forms)) {
  232.             $forms['pwlostForm'] = $this->createPwlostForm($redirect$registrationFormData);
  233.         }
  234.         $template "@StartPlatzUserBundle/Authentication/login.html.twig";
  235.         return $this->render($template, ['redirectRouteName' => $redirectRouteName'redirect' => $redirect'loginForm' => $this->createLoginForm($redirect)->createView(), 'registrationForm' => $forms['registrationForm']->createView(), 'pwlostForm' => $forms['pwlostForm']->createView()]);
  236.     }
  237.     protected function createRegistrationForm($redirect null$data = [])
  238.     {
  239.         if ($redirect) {
  240.             $data['redirect'] = $redirect;
  241.         }
  242.         return $this->createForm(
  243.             RegistrationFormType::class,
  244.             $data
  245.         );
  246.     }
  247.     protected function createPwlostForm($redirect null$data = [])
  248.     {
  249.         if ($redirect) {
  250.             $data['redirect'] = $redirect;
  251.         }
  252.         return $this->createForm(
  253.             LostPasswordFormType::class,
  254.             $data
  255.         );
  256.     }
  257.     protected function createLoginForm($redirect)
  258.     {
  259.         return $this->createForm(
  260.             LoginFormType::class,
  261.             ['target_path' => $redirect]
  262.         );
  263.     }
  264.     protected function createSetPasswordForm($redirect)
  265.     {
  266.         return $this->createForm(
  267.             SetPasswordFormType::class,
  268.             ['target_path' => $redirect]
  269.         );
  270.     }
  271.     /**
  272.      * @Route("/login/facebook", name="login_facebook")
  273.      */
  274.     public function loginFacebookAction(): void
  275.     {
  276.     }
  277.     /**
  278.      * @Route("/login/facebook/check", name="login_facebook_check")
  279.      */
  280.     public function loginFacebookCheckAction(): void
  281.     {
  282.     }
  283.     /**
  284.      * @Route("/login/google", name="login_google")
  285.      */
  286.     public function loginGoogleAction(): void
  287.     {
  288.     }
  289.     /**
  290.      * @Route("/login/google/check", name="login_google_check")
  291.      */
  292.     public function loginGoogleCheckAction(): void
  293.     {
  294.     }
  295.     /**
  296.      * @Route("/login/password/check", name="login_password_check")
  297.      */
  298.     public function loginPasswordCheckAction(): void
  299.     {
  300.     }
  301.     /** @return UserRepository */
  302.     protected function getUserRepository()
  303.     {
  304.         return $this->getDoctrine()->getRepository(User::class);
  305.     }
  306.     /**
  307.      * @return UserPasswordEncoderInterface
  308.      */
  309.     protected function getUserPasswordEncoder()
  310.     {
  311.         return $this->encoder;
  312.     }
  313.     protected function createEmailHash($salt$email)
  314.     {
  315.         return Token::createHash($salt$email);
  316.     }
  317.     /**
  318.      * @Route("/login/link/create/{redirect}", name="login_link_create")
  319.      * @Security("is_granted('ROLE_USER')")
  320.      */
  321.     public function loginLinkCreateAction(Request $request$redirect)
  322.     {
  323.         $url $this->generateUrl($redirect);
  324.         $this->generateLoginLink($url);
  325.         $request->getSession()->getFlashBag()->add('notice''loginlink zu ' $url ' erstellt');
  326.         return $this->redirect($this->generateUrl('community_home'));
  327.     }
  328.     protected function generateLoginLink($redirect '/x')
  329.     {
  330.         /** @var User $user */
  331.         $user $this->getUser();
  332.         $message = new Email();
  333.         $message->to($user->getEmail());
  334.         $message->from(new Address('info@startplatz.de''Startplatz - Webseite'));
  335.         $message->subject('login-link for startplatz.de');
  336.         $message->text(
  337.             $this->renderView(
  338.                 '@StartPlatzUserBundle/Mails/sendLoginLink.txt.twig',
  339.                 ['email' => $user->getEmail(), 'name' => $user->getName(), 'hash' => Token::createHash($user->getEmail(), $redirect), 'redirect' => $redirect]
  340.             )
  341.         );
  342.         $this->mailer->send($message);
  343.         return true;
  344.     }
  345.     /**
  346.      * @Route("/login/link/lg/create/{redirect}", name="login_link_create_lg")
  347.      */
  348.     public function createLoginLinkLg(Request $request$redirect)
  349.     {
  350.         $url $this->generateUrl($redirect);
  351.         $this->generateLoginLinkLg($url);
  352.         $request->getSession()->getFlashBag()->add('notice''loginlink zu ' $url ' erstellt');
  353.         return $this->redirect($this->generateUrl('community_home'));
  354.     }
  355.     protected function generateLoginLinkLg($redirect '/crm/contacts')
  356.     {
  357.         $email 'lorenz.graef@startplatz.de';
  358.         $message = new Email();
  359.         $message->to($email);
  360.         $message->from(new Address('info@startplatz.de''Startplatz - Webseite'));
  361.         $message->subject('login-link for startplatz.de');
  362.         $message->text(
  363.             $this->renderView(
  364.                 '@StartPlatzUserBundle/Mails/sendLoginLink.txt.twig',
  365.                 ['email' => $email'name' => 'lorenz''hash' => Token::createHash($email$redirect), 'redirect' => $redirect]
  366.             )
  367.         );
  368.         $this->mailer->send($message);
  369.         return true;
  370.     }
  371.     /**
  372.      * @Route("/lost-pw/", name="lost_pw", methods={"POST"})
  373.      * @Template("@StartPlatzUserBundle/Authentication/login.html.twig")
  374.      */
  375.     public function lostPwAction(Request $request)
  376.     {
  377.         $form $this->createPwlostForm();
  378.         $form->handleRequest($request);
  379.         $data $form->getData();
  380.         if ($form->isSubmitted() && $form->isValid()) {
  381.             $reset $this->resetPassword($data);
  382.             if ($reset) {
  383.                 $request->getSession()->getFlashBag()->add('notice'$this->renderView('@StartPlatzUserBundle/Authentication/passwordEmailFlash.html.twig'$data));
  384.                 return $this->redirect($this->generateUrl('login'));
  385.             } else {
  386.                 $request->getSession()->getFlashBag()->add('notice'$this->renderView('@StartPlatzUserBundle/Authentication/passwordEmailErrorFlash.html.twig'$data));
  387.                 return $this->showLogin($data['redirect'], $request$data, ['pwlostForm' => $form]);
  388.             }
  389.         } else {
  390.             return $this->showLogin($data['redirect'], $request$data, ['pwlostForm' => $form]);
  391.         }
  392.     }
  393.     protected function resetPassword($data)
  394.     {
  395.         $password substr(base_convert(sha1(uniqid((string)random_int(0mt_getrandmax()), true)), 1636), 08);
  396.          /** @var User $user */
  397.         if (!($user $this->getUserRepository()->loadUser($data))) {
  398.             return false;
  399.         }
  400.         $user->setPassword($this->getUserPasswordEncoder()->encodePassword($user$password));
  401.         $this->getUserRepository()->add($user);
  402.         //$password= $user->getPassword();
  403.         $message = new Email();
  404.         $message->to($data['email']);
  405.         $message->from(new Address('info@startplatz.de''Startplatz - Webseite'));
  406.         $message->subject('Dein Passwort für startplatz.de!');
  407.         $message->text(
  408.             $this->renderView(
  409.                 '@StartPlatzUserBundle/Mails/login-password.txt.twig',
  410.                 ['email' => $user->getEmail(), 'name' => $user->getName(), 'hash' => Token::createHash($data['email'], $data['redirect']), 'redirect' => $data['redirect'], 'password' => $password]
  411.             )
  412.         );
  413.         $this->mailer->send($message);
  414.         return true;
  415.     }
  416.     /**
  417.      * @Route("/profile/send-new-password/", name="user_profile_send_new_password")
  418.      * @Security("is_granted('ROLE_USER')")
  419.      */
  420.     public function sendNewPasswordAction(Request $request)
  421.     {
  422.         $user $this->getUser();
  423.         $data['email'] = $user->getEmail();
  424.         $data['redirect'] = '/profile/set-password/';
  425.         $reset $this->resetPassword($data);
  426.         if ($reset) {
  427.             $request->getSession()->getFlashBag()->add('notice'$this->renderView('@StartPlatzUserBundle/Authentication/passwordEmailFlash.html.twig'$data));
  428.         } else {
  429.             $request->getSession()->getFlashBag()->add('notice'$this->renderView('@StartPlatzUserBundle/Authentication/passwordEmailErrorFlash.html.twig'$data));
  430.         }
  431.         return $this->redirect($this->generateUrl('user_profil_change_password'));
  432.     }
  433.     /**
  434.      * @Route("/login/link/check/{email}/{hash}/to{redirect}", name="login_email_check", requirements={"redirect"=".+"})
  435.      */
  436.     public function loginLinkCheckAction(Request $request$redirect '/'$hash "")
  437.     {
  438.         if ($user $this->getUser()) {
  439.             $em $this->getDoctrine()->getManager();
  440.             $em->getRepository(User::class)->writeActivity($user);
  441.             if ($batches $em->getRepository(Batch::class)->findByExtended(['settings' => 'validateEmail'])) {
  442.                 foreach ($batches as $batch) {
  443.                     $batchId $batch->getId();
  444.                     if ($application $em->getRepository(Application::class)->findOneBy(['batchId' => $batchId'memberId'=>$user->getMemberId()])) {
  445.                         $application->setHasEmailValidated(true);
  446.                         $em->persist($application);
  447.                         $em->flush();
  448.                     }
  449.                 }
  450.             }
  451.             if ($request->get('action') == 'setPassword') {
  452.                 return $this->redirect($this->generateUrl('x_home', ['hash' => $hash]));
  453.             }
  454.             return $this->redirect($redirect);
  455.         } else {
  456.             $this->session->getFlashBag()->add('notice''ERROR: no user found');
  457.             return $this->redirect($this->generateUrl('x_home'));
  458.         }
  459.     }
  460.     /**
  461.      * @Route("/login/confirm/{email}/{hash}/to{redirect}", name="login_confirm_email", requirements={"redirect"=".+"})
  462.      */
  463.     public function confirmLinkCheckAction(Request $request$email$hash$redirect '/login')
  464.     {
  465.         $em $this->getDoctrine()->getManager();
  466.         $action $request->get('action');
  467.         if (!$user $this->getUserRepository()->findUserByConfirm($hash)) {
  468.             if ($this->getUserRepository()->findOneBy(['email' => $email])) {
  469.                 $this->session->getFlashBag()->add('notice''ERROR email already confirmed. Please login.');
  470.             } else {
  471.                 $this->session->getFlashBag()->add('notice''ERROR not matching any user');
  472.             }
  473.             return $this->redirect('/logout');
  474.         }
  475.         if (!$user->getIsEmailConfirmed()) {
  476.             $user->setIsEmailConfirmed(true);
  477.             $user->setEmail($user->getToConfirmEmail());
  478.             $user->setConfirmEmail(null);
  479.             $user->setToConfirmEmail(null);
  480.             $this->getUserRepository()->add($user);
  481.             if ($memberId $user->getMemberId()) {
  482.                 $em->getRepository(Member::class)->changeEmailByMemberId($memberId$user->getEmail(), $user->getEmail());
  483.             }
  484.         }
  485.         return $this->redirect($this->getLoginLink($user->getEmail(), $redirect$action));
  486.     }
  487.     private function getLoginLink($email$redirect '/x'$action null)
  488.     {
  489.         $hash Token::createHash($email$redirect);
  490.         if ($action) {
  491.             $loginLink $this->generateUrl('login_email_check', ['email' => $email'hash' => $hash'redirect' => $redirect'action' => $action]);
  492.         } else {
  493.             $loginLink $this->generateUrl('login_email_check', ['email' => $email'hash' => $hash'redirect' => $redirect]);
  494.         }
  495.         return $loginLink;
  496.     }
  497.     /**
  498.      * @Route("/logout/", name="logout")
  499.      */
  500.     public function logoutAction(): void
  501.     {
  502.     }
  503.     /**
  504.      * @Template
  505.      */
  506.     public function loginStatusAction()
  507.     {
  508.         return [];
  509.     }
  510. }