src/Controller/SecurityController.php line 48

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Daikin\BaseBundle\Entity\Logs;
  4. use App\Daikin\BaseBundle\Entity\User;
  5. use App\Security\Exception\EmailNotApprovedException;
  6. use App\Service\Security\UserCommunicationService;
  7. use App\Service\Security\UserCredentialsService;
  8. use DateTime;
  9. use Doctrine\ORM\EntityManagerInterface;
  10. use LogicException;
  11. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  12. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  13. use Symfony\Component\Form\Extension\Core\Type\EmailType;
  14. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  15. use Symfony\Component\HttpFoundation\RedirectResponse;
  16. use Symfony\Component\HttpFoundation\Request;
  17. use Symfony\Component\HttpFoundation\Response;
  18. use Symfony\Component\Routing\Annotation\Route;
  19. use Symfony\Component\Security\Core\Security;
  20. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  21. use Symfony\Component\Validator\Constraints as Assert;
  22. class SecurityController extends AbstractController
  23. {
  24.     /**
  25.      * @Route("/login", name="app_login")
  26.      */
  27.     public function login(Request $requestAuthenticationUtils $authenticationUtils): Response
  28.     {
  29.         if ($this->getUser()) {
  30.             return $this->redirectToRoute('homepage');
  31.         }
  32. //        if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
  33. //            $error = $request->attributes->get(Security::AUTHENTICATION_ERROR);
  34. //        } else {
  35. //            $error = $request->getSession()->get(Security::AUTHENTICATION_ERROR);
  36. //            $request->getSession()->remove(Security::AUTHENTICATION_ERROR);
  37. //        }
  38.         $error $authenticationUtils->getLastAuthenticationError();
  39.         $lastUsername $authenticationUtils->getLastUsername();
  40.         $targetPathService '';
  41.         $targetPath $request->getSession()->get('_security.main.target_path');
  42.         if ($targetPath && strpos($targetPath'authedapi') !== false){
  43.             $targetPathService $targetPath;
  44.         }
  45.         return $this->render('security/login.html.twig', [
  46.             'last_username' => $lastUsername,
  47.             'error' => $error,
  48.             'targetPathService' => $targetPathService,
  49.             'not_enabled' => ($error instanceof EmailNotApprovedException)
  50.         ]);
  51.     }
  52.     /**
  53.      * @Route("/logout", name="app_logout")
  54.      */
  55.     public function logout(): void
  56.     {
  57.         throw new LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
  58.     }
  59.     /**
  60.      * @Route("/login_check", name="app_login_check")
  61.      */
  62.     public function securityCheckAction(): RedirectResponse
  63.     {
  64.         return $this->redirectToRoute('app_login');
  65.     }
  66.     /**
  67.      * @Route("/login/resend-verification/{email?}", name="security_resend_verification")
  68.      * @param Request $request
  69.      * @param EntityManagerInterface $em
  70.      * @param UserCredentialsService $credentialsService
  71.      * @param UserCommunicationService $communicationService
  72.      * @param string|null $email
  73.      * @return Response
  74.      */
  75.     public function resendVerificationCode(Request $requestEntityManagerInterface $emUserCredentialsService $credentialsServiceUserCommunicationService $communicationService, ?string $email=null): Response
  76.     {
  77.         $form $this->createFormBuilder(null, ['attr' => ['id' => 'register_form']])
  78.             ->add('email'EmailType::class, ['label' => 'E-Mail''required' => true'data' => $email])
  79.             ->add('submit'SubmitType::class, ['label' => 'Submit'])
  80.             ->getForm()
  81.             ->handleRequest($request)
  82.         ;
  83.         $success false;
  84.         if ($form->isSubmitted() && $form->isValid()) {
  85.             $data $form->getData();
  86.             /** @var $user ?User */
  87.             $user $em->getRepository(User::class)->findOneBy(['email' => $data['email'], 'approved_email' => 0]);
  88.             if ($user && $user->hasRole('ROLE_ADMIN_COMPANY')) {
  89.                 $plaintextPassword $credentialsService->updatePasswordForUser($usernull);
  90.                 $em->persist($user);
  91.                 $em->flush($user);
  92.                 $communicationService->sendVerificationMail($user$plaintextPassword);
  93.                 $this->addFlash('success''Verification mail has been resent.');
  94.                 $success true;
  95.             } else {
  96.                 $this->addFlash('error''Cannot send a new verification mail for this email address. Either it is unknown, it is already enabled or it does not belong company administrator. To resend the verification link for a user account, please contact your company administrator.');
  97.             }
  98.         }
  99.         return $this->render('@DaikinBase/Forms/resendverification.html.twig', [
  100.             'form' => $form->createView(),
  101.             'success' => $success
  102.         ]);
  103.     }
  104.     /**
  105.      * VerificationAction
  106.      *
  107.      * @Route("/login/verification/{email}/{codepass}", name="security_login_verification")
  108.      * @param Request $request
  109.      * @param string $email
  110.      * @param string $codepass
  111.      * @param EntityManagerInterface $em
  112.      * @return Response
  113.      */
  114.     public function verificationAction(Request $requeststring $emailstring $codepassEntityManagerInterface $em): Response
  115.     {
  116.         $message = [
  117.             'title' => 'Verification failed.',
  118.             'message' => 'We could not verify your request. Please make sure you submit the verification link completely.',
  119.             'msgType' => 'error',
  120.             'toLogin' => false,
  121.         ];
  122.         if ($user $em->getRepository(User::class)->findOneBy(['email' => $email'deletestatus' => 0])) {
  123.             if ($user->isEmailApproved()) {
  124.                 $message = [
  125.                     'title' => 'Email address already verified.',
  126.                     'message' => 'You have already verified your email address earlier.',
  127.                     'msgType' => 'warning',
  128.                     'toLogin' => true,
  129.                 ];
  130.             } elseif ($codepass == $user->getVerificationCode()) {
  131.                 $logs = new Logs($user->getId(), 'User''User approved his E-mail.');
  132.                 $em->persist($logs);
  133.                 $user->setApprovedEmail(1);
  134.                 $em->persist($user);
  135.                 $em->flush();
  136.                 $message = [
  137.                     'title' => 'Verification successful.',
  138.                     'message' => 'Thank you. You have successfully verified your email address.',
  139.                     'msgType' => 'success',
  140.                     'toLogin' => true,
  141.                 ];
  142.             }
  143.             if ($message['toLogin']) {
  144.                 $request->getSession()->set(
  145.                     Security::LAST_USERNAME,
  146.                     $user->getUserIdentifier()
  147.                 );
  148.                 $this->addFlash$message['msgType'], $message['message']);
  149.                 return $this->redirectToRoute('app_login');
  150.             }
  151.         }
  152.         return $this->render('@DaikinBase/default/messages.html.twig'$message);
  153.     }
  154.     /**
  155.      * @Route("/login/forgot_password", name="_security_login_forgot")
  156.      * @param Request $request
  157.      * @param EntityManagerInterface $em
  158.      * @param UserCommunicationService $communicationService
  159.      * @param UserCredentialsService $credentialsService
  160.      * @return Response
  161.      */
  162.     public function forgotPassAction(Request $requestEntityManagerInterface $emUserCommunicationService $communicationServiceUserCredentialsService $credentialsService): Response
  163.     {
  164.         $form $this->createFormBuilder()
  165.             ->add('email'EmailType::class, [
  166.                 'constraints' => [
  167.                     new Assert\NotBlank(),
  168.                     new Assert\Email(),
  169.                 ]
  170.             ])
  171.             ->getForm()
  172.             ->handleRequest($request)
  173.         ;
  174.         $message '';
  175.         if ($form->isSubmitted() && $form->isValid()) {
  176.             $data $form->getData();
  177.             $user $em->getRepository(User::class)->findOneBy(['email' => $data['email'], 'deletestatus' => 0]);
  178.             if ($user) {
  179.                 if (!$user->getApprovedEmail()) {
  180.                     $credentialsService->updatePasswordForUser($usernull);
  181.                     $communicationService->sendVerificationMail($user$user->getPPassword(), $user->getPassword());
  182.                 } else {
  183.                     $user->setResetRequestedAt(new DateTime());
  184.                     $user->setResetRequestHash(md5(uniqid() . time()));
  185.                     $communicationService->sendForgotPasswordMail($user);
  186.                 }
  187.                 $em->persist($user);
  188.                 $em->flush();
  189.             }
  190.             // Dont let attacker check for mails
  191.             $message 'On Your mailbox was sent new password and link for Your account verification.';
  192.         }
  193.         return $this->render('@DaikinBase/Forms/forgotpassword.html.twig', [
  194.             'message' => $message,
  195.             'message_error' => false,
  196.             'form' => $form->createView(),
  197.         ]);
  198.     }
  199.     /**
  200.      * @Route("/login/reset-password/{hash}", name="resetpassword")
  201.      * @param string $hash
  202.      * @param EntityManagerInterface $em
  203.      * @param UserCommunicationService $communicationService
  204.      * @param ParameterBagInterface $parameterBag
  205.      * @param UserCredentialsService $credentialsService
  206.      * @return Response
  207.      */
  208.     public function resetPasswordAction(string $hashEntityManagerInterface $emUserCommunicationService $communicationServiceParameterBagInterface $parameterBagUserCredentialsService $credentialsService): Response
  209.     {
  210.         $error '';
  211.         $message '';
  212.         if ($user $em->getRepository(User::class)->findOneBy(['reset_request_hash' => $hash])) {
  213.             if ($user->getResetRequestedAt() && ( $user->getResetRequestedAt()->getTimestamp() + $parameterBag->get('password_reset_valid') * 3600 time() )) {
  214.                 $logs = new Logs($user->getId(), 'User''User password Recovery.');
  215.                 $em->persist($logs);
  216.                 $credentialsService->updatePasswordForUser($usernull);
  217.                 $user->resetResetRequest();
  218.                 $communicationService->sendPasswordResetMail($user);
  219.                 $em->persist($user);
  220.                 $em->flush();
  221.                 $message 'Password reset successful. We have sent you a new password to your email address.';
  222.             } else {
  223.                 $error 'Reset request link not valid any more.';
  224.                 $user->resetResetRequest();
  225.                 $em->persist($user);
  226.                 $em->flush();
  227.             }
  228.         } else
  229.             $error 'Password reset hash invalid.';
  230.         return $this->render('@DaikinBase/default/reset_password.html.twig', [
  231.             'message' => $message,
  232.             'error' => $error,
  233.         ]);
  234.     }
  235. }