src/Mm/Beton/Planungsatlas/AtlasBundle/Controller/UserController.php line 209

Open in your IDE?
  1. <?php
  2. namespace Mm\Beton\Planungsatlas\AtlasBundle\Controller;
  3. use Doctrine\Persistence\ManagerRegistry;
  4. use Mm\Beton\Planungsatlas\AtlasBundle\Repository\UserRepository;
  5. use Mm\Beton\Planungsatlas\AtlasBundle\Form\ChangePasswordType;
  6. use Mm\Beton\Planungsatlas\AtlasBundle\Form\Model\ChangePassword;
  7. use Mm\Beton\Planungsatlas\AtlasBundle\Form\Model\ResetPassword;
  8. use Mm\Beton\Planungsatlas\AtlasBundle\Form\ResetPasswordType;
  9. use Mm\Beton\Planungsatlas\AtlasBundle\Service\GenerationService;
  10. use Mm\Beton\Planungsatlas\AtlasBundle\Entity\User\User;
  11. use Mm\Beton\Planungsatlas\AtlasBundle\Form\RegisterType;
  12. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  13. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  14. use Symfony\Component\Routing\Annotation\Route;
  15. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  16. use Symfony\Component\HttpFoundation\JsonResponse;
  17. use Symfony\Component\HttpFoundation\Request;
  18. use Symfony\Component\HttpFoundation\Response;
  19. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  20. use Symfony\Contracts\Translation\TranslatorInterface;
  21. class UserController extends AbstractAuthenticatedController
  22. {
  23.     private $managerRegistry;
  24.     public function __construct(ManagerRegistry $managerRegistry)
  25.     {
  26.         $this->managerRegistry $managerRegistry;
  27.     }
  28.     /**
  29.      * @Route("/login", name="login")
  30.      */
  31.     public function loginAction(TranslatorInterface $translator)
  32.     {
  33.         $this->addFlash('error'$translator->trans('Please login'));
  34.         return $this->redirectToRoute('home');
  35.     }
  36.     /**
  37.      * @Route("/user-delete", name="user_delete")
  38.      * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
  39.      */
  40.     public function deleteAction(Request $requestTranslatorInterface $translatorTokenStorageInterface $tokenStorage)
  41.     {
  42.         $user $this->getUser();
  43.         $entityManager $this->managerRegistry->getManager('user');
  44.         $entityManager->remove($user);
  45.         $entityManager->flush();
  46.         unset($_SESSION['userinfo']);
  47.         $tokenStorage->setToken(null);
  48.         $request->getSession()->invalidate();
  49.         $this->addFlash('success'$translator->trans('Your profile was removed'));
  50.         $response = [
  51.             'state' => 1
  52.         ];
  53.         return new JsonResponse$response );
  54.     }
  55.     /**
  56.      * @Route("/ajax-login", name="ajax_login")
  57.      */
  58.     public function ajaxLoginAction()
  59.     {
  60.         //everything happens in service
  61.     }
  62.     /**
  63.      * @Route(
  64.      *   "/logout",
  65.      *   name="logout"
  66.      * )
  67.      *
  68.      * @return Response
  69.      */
  70.     public function logoutAction()
  71.     {
  72.         unset($_SESSION['userinfo']);
  73.         session_destroy();
  74.         return $this->render('index.html.twig');
  75.     }
  76.     /**
  77.      * @Route("/register", name="user_registration")
  78.      */
  79.     public function registerAction(
  80.         Request $request,
  81.         ParameterBagInterface $parameterBag,
  82.         GenerationService $generationService,
  83.         UserPasswordHasherInterface $encoder,
  84.         TranslatorInterface $translator,
  85.         \Swift_Mailer $mailer
  86.     )
  87.     {
  88.         $user = new User();
  89.         $form $this->createForm(RegisterType::class, $user);
  90.         $form->handleRequest($request);
  91.         if ($form->isSubmitted() && $form->isValid()) {
  92.             $generatedPassword $generationService->generatePassword(8);
  93.             $password $encoder->hashPassword($user$generatedPassword);
  94.             $hash $generationService->generateHash();
  95.             $user->setPassword($password);
  96.             $user->setHash($hash);
  97.             $date = new \DateTime();
  98.             $user->setRegisteredAt($date);
  99.             $user->setLastLoginAt($date);
  100.             // save the User
  101.             $entityManager $this->managerRegistry->getManager('user');
  102.             $entityManager->persist($user);
  103.             $entityManager->flush();
  104.             // send DOI email
  105.             $this->sendDOIEmail(
  106.                 $request,
  107.                 $translator,
  108.                 $mailer,
  109.                 $user
  110.             );
  111.             //  send new user notify email
  112.             $this->sendNewUserNotifyEmail(
  113.                 $translator,
  114.                 $mailer,
  115.                 $user,
  116.                 $parameterBag->get('notifyNewUserEmail'),
  117.                 $parameterBag->get('brand_name')
  118.             );
  119.             // success flash message
  120.             $this->addFlash('success'$translator->trans('Check your email and approve it by link'));
  121.             return $this->redirectToRoute('home');
  122.         }
  123.         return $this->render(
  124.             'user/register.html.twig', [
  125.                 'form' => $form->createView(),
  126.                 'loggedIn' => false
  127.             ]
  128.         );
  129.     }
  130.     /**
  131.      * @Route("/doi/{hash}", name="doi_check")
  132.      */
  133.     public function doiAction(
  134.         TranslatorInterface $translator,
  135.         GenerationService $generationService,
  136.         UserPasswordHasherInterface $encoder,
  137.         \Swift_Mailer $mailer,
  138.         $hash
  139.     )
  140.     {
  141.         $entityManager $this->managerRegistry->getManager('user');
  142.         /** @var UserRepository $userRepository */
  143.         $userRepository $entityManager->getRepository(User::class);
  144.         /** @var User $user */
  145.         $user $userRepository->findOneBy(
  146.             ['hash' => $hash]
  147.         );
  148.         if (empty($user)) {
  149.             // error flash message
  150.             $this->addFlash('error'$translator->trans('Hash not exists'));
  151.             return $this->redirectToRoute('home');
  152.         }
  153.         // activate user
  154.         $user->setIsActive(true);
  155.         $user->setHash('');
  156.         // send email with password
  157.         $this->sendEmailWithPassword(
  158.             $generationService,
  159.             $encoder,
  160.             $translator,
  161.             $mailer,
  162.             $user
  163.         );
  164.         // save the User (include new password)
  165.         $entityManager->persist($user);
  166.         $entityManager->flush();
  167.         // success flash message
  168.         $this->addFlash('success'$translator->trans('Your email approved. Please check email to find password'));
  169.         return $this->redirectToRoute('home');
  170.     }
  171.     /**
  172.      * @Route("/reset-password", name="user_reset_password")
  173.      */
  174.     public function resetPasswordAction(
  175.         Request $request,
  176.         TranslatorInterface $translator,
  177.         GenerationService $generationService,
  178.         UserPasswordHasherInterface $encoder,
  179.         \Swift_Mailer $mailer
  180.     )
  181.     {
  182.         $data = new ResetPassword();
  183.         $form $this->createForm(ResetPasswordType::class, $data);
  184.         $form->handleRequest($request);
  185.         if ($form->isSubmitted() && $form->isValid()) {
  186.             /** @var UserRepository $userRepository */
  187.             $userRepository $this->managerRegistry->getRepository(User::class, 'user');
  188.             /** @var User $user */
  189.             $user $userRepository->findOneBy(['username' => $data->getUsername()]);
  190.             if (!$user instanceof User) {
  191.                 // error flash message
  192.                 $this->addFlash('error'$translator->trans('User not exists'));
  193.                 return $this->redirectToRoute('home');
  194.             }
  195.             // send email with password
  196.             $this->sendEmailWithPassword(
  197.                 $generationService,
  198.                 $encoder,
  199.                 $translator,
  200.                 $mailer,
  201.                 $user
  202.             );
  203.             // save the User (include new password)
  204.             $entityManager $this->managerRegistry->getManager('user');
  205.             $entityManager->persist($user);
  206.             $entityManager->flush();
  207.             // success flash message
  208.             $this->addFlash('success'$translator->trans('New password was created. Please check email'));
  209.             return $this->redirectToRoute('home');
  210.         }
  211.         return $this->render(
  212.             'user/resetPassword.html.twig',
  213.             [
  214.                 'form' => $form->createView()
  215.             ]
  216.         );
  217.     }
  218.     /**
  219.      * Change password action
  220.      *
  221.      * @Route("/change-password", name="user_change_password")
  222.      * @Security("is_granted('IS_AUTHENTICATED_FULLY')")
  223.      */
  224.     public function changePasswordAction(
  225.         Request $request,
  226.         UserPasswordHasherInterface  $encoder,
  227.         TranslatorInterface $translator
  228.     )
  229.     {
  230.         $changePasswordModel = new ChangePassword();
  231.         $form $this->createForm(
  232.             ChangePasswordType::class,
  233.             $changePasswordModel
  234.         );
  235.         $form->handleRequest($request);
  236.         if ($form->isSubmitted() && $form->isValid()) {
  237.             $user $this->getUser();
  238.             $password $encoder->hashPassword($user$changePasswordModel->getNewPassword());
  239.             $user->setPassword($password);
  240.             // save the User
  241.             $entityManager $this->managerRegistry->getManager('user');
  242.             $entityManager->persist($user);
  243.             $entityManager->flush();
  244.             // success flash message
  245.             $this->addFlash('success'$translator->trans('Your password was changed'));
  246.             return $this->redirectToRoute('home');
  247.         }
  248.         return $this->render(
  249.             'user/changePassword.html.twig',
  250.             [
  251.                 'form' => $form->createView()
  252.             ]
  253.         );
  254.     }
  255.     /**
  256.      * Send email to user with hash
  257.      *
  258.      * @param Request $request
  259.      * @param TranslatorInterface $translator
  260.      * @param User $user
  261.      */
  262.     protected function sendDOIEmail(Request $requestTranslatorInterface $translator\Swift_Mailer $mailerUser $user)
  263.     {
  264.         $link $request->getSchemeAndHttpHost() . $this->generateUrl(
  265.             'doi_check',
  266.             ['hash' => $user->getHash()]
  267.         );
  268.         $message = (new \Swift_Message($translator->trans('DOI Email Subject')))
  269.             ->setFrom(
  270.                 [
  271.                     'noreply@wdvs-planungsatlas.de' => 'WDVS-Planungsatlas'
  272.                 ]
  273.             )
  274.             ->setTo($user->getUsername())
  275.             ->setBody(
  276.                 $this->renderView(
  277.                     'Emails/doi.html.twig',
  278.                     [
  279.                         'link' => $link
  280.                     ]
  281.                 ),
  282.                 'text/html'
  283.             );
  284.         $mailer->send($message);
  285.     }
  286.     /**
  287.      * Send email with password
  288.      *
  289.      * @param GenerationService $generationService
  290.      * @param UserPasswordHasherInterface  $encoder
  291.      * @param TranslatorInterface $translator
  292.      * @param $user
  293.      */
  294.     protected function sendEmailWithPassword(
  295.         GenerationService $generationService,
  296.         UserPasswordHasherInterface $encoder,
  297.         TranslatorInterface $translator,
  298.         \Swift_Mailer $mailer,
  299.         $user
  300.     )
  301.     {
  302.         $generatedPassword $generationService->generatePassword(8);
  303.         $password $encoder->hashPassword($user$generatedPassword);
  304.         $user->setPassword($password);
  305.         $message = (new \Swift_Message($translator->trans('Password Email Subject')))
  306.             ->setFrom(['noreply@wdvs-planungsatlas.de' => 'WDVS-Planungsatlas'])
  307.             ->setTo($user->getUsername())
  308.             ->setBody(
  309.                 $this->renderView(
  310.                     'Emails/password.html.twig',
  311.                     ['pass' => $generatedPassword]
  312.                 ),
  313.                 'text/html'
  314.             );
  315.         $result $mailer->send($message);
  316.         if (!$result) {
  317.             exit('An error occurred while sending an email');
  318.         }
  319.     }
  320.     /**
  321.      * Send notify email about new user
  322.      *
  323.      * @param TranslatorInterface $translator
  324.      * @param \Swift_Mailer $mailer
  325.      * @param $user
  326.      */
  327.     protected function sendNewUserNotifyEmail(
  328.         TranslatorInterface $translator,
  329.         \Swift_Mailer $mailer,
  330.         $user,
  331.         $notifyEmail,
  332.         $brandName)
  333.     {
  334.         $message = (new \Swift_Message($translator->trans('email.notify_new')))
  335.             ->setFrom(['noreply@wdvs-planungsatlas.de' => 'WDVS-Planungsatlas'])
  336.             ->setTo($notifyEmail)
  337.             ->setBody(
  338.                 $this->renderView(
  339.                     'Emails/newUserNotify.html.twig',
  340.                     [
  341.                         'brand' => $brandName,
  342.                         'userEmail' => $user->getUsername()
  343.                     ]
  344.                 ),
  345.                 'text/html'
  346.             );
  347.         $mailer->send($message);
  348.     }
  349. }