src/Controller/Page/PageAuthController.php line 41

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Page;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\Routing\Annotation\Route;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpFoundation\JsonResponse;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  9. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  10. use Symfony\Component\Mailer\MailerInterface;
  11. use Symfony\Component\Mime\Address;
  12. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  13. use App\Entity\User;
  14. use App\Entity\Institution;
  15. use App\Entity\Notification;
  16. use App\Entity\Province;
  17. use App\Entity\Project;
  18. use App\Entity\Form;
  19. use App\Entity\Consent;
  20. use App\Entity\ConsentUser;
  21. use App\Form\Type\PageUserRegisterType;
  22. use App\Form\Type\PageUserPasswordType;
  23. use App\Form\Type\PageUserResetPasswordType;
  24. use App\Form\Type\InstitutionType;
  25. use App\Service\FreshMailService;
  26. use App\Service\InstitutionService;
  27. use Symfony\Component\HttpFoundation\Cookie;
  28. use Knp\Component\Pager\PaginatorInterface;
  29. class PageAuthController extends AbstractController
  30. {
  31.     private $paginator;
  32.     public function __construct(PaginatorInterface $paginator){
  33.         $this->paginator $paginator;
  34.     }
  35.     /**
  36.      * @Route("/", name="pageAuthLogin")
  37.      */
  38.     public function login(AuthenticationUtils $authenticationUtils): Response
  39.     {
  40.         if($this->getUser()) {
  41.             return $this->redirectToRoute('pageDashboardIndex');
  42.         }
  43.         $error $authenticationUtils->getLastAuthenticationError();
  44.         $lastUsername $authenticationUtils->getLastUsername();
  45.         return $this->render('page/auth/login.html.twig', [
  46.             'last_username' =>$lastUsername,
  47.             'error' => $error
  48.         ]);
  49.     }
  50.     /**
  51.      * @Route("/rejestracja", name="pageAuthRegister")
  52.      */
  53.     public function register(Request $requestMailerInterface $mailerFreshMailService $freshMailService): Response
  54.     {
  55.         $error '';
  56.         $em $this->getDoctrine()->getManager();
  57.         if($this->getUser()) {
  58.             return $this->redirectToRoute('pageDashboardIndex');
  59.         }
  60.         $consents $this->getDoctrine()->getRepository(Consent::class)->findBy([
  61.             'isDeleted' => false
  62.         ]);
  63.         $user = new User;
  64.         $user
  65.             ->setRole('ROLE_USER')
  66.             ->setStatus('INACTIVE')
  67.             ->setHash(hash('sha256'uniqid()))
  68.             ->setDateRegister(new \Datetime);
  69.         $form $this->createForm(PageUserRegisterType::class, $user, [
  70.             'consents' => $consents
  71.         ]);
  72.         $form->handleRequest($request);
  73.         if($form->isSubmitted() && $form->isValid() ) {
  74.             $type $form->get("type")->getData();
  75.             if ($type === 'project') {
  76.                 if ($institutionId = (int) $request->request->get('institution_id')) {
  77.                     $institution $this->getDoctrine()->getRepository(Institution::class)->find($institutionId);
  78.                 }
  79.                 if (!isset($institution) || !$institution){
  80.                     $error 'Musisz wybrać placówkę';
  81.                 } else {
  82.                     $notificationType null;
  83.                     if ($institution->getTarget()) {
  84.                         $notificationType 2// Rejestracja do placówki ze zmianą danych
  85.                     } else if ($institution->getStatus() == 'INACTIVE') {
  86.                         $notificationType 1// Rejestracja do nowej placówki
  87.                     } else if ($institution->getStatus() == 'ACTIVE') {
  88.                         $notificationType 3// Rejestracja do istniejącej placówki
  89.                     }
  90.                     if ($notificationType === 3) {
  91.                         // Gdy użytkownik rejestruje się do istniejącej placówki, nie potrzebna jest akceptacja administratora
  92.                         $user->setStatus('ACTIVE');
  93.                         $user->addInstitution($institution);
  94.                     } else {
  95.                         // Tworzone jest zgłoszenie do administratora
  96.                         $notification = new Notification;
  97.                         $notification
  98.                             ->setUser($user)
  99.                             ->setInstitution($institution)
  100.                             ->setDateCreated(new \Datetime)
  101.                             ->setType($notificationType)
  102.                             ->setStatus('NEW');
  103.                         $em->persist($notification);
  104.                     }
  105.                 }
  106.             } else {
  107.                 $user->setStatus('ACTIVE');
  108.             }
  109.             // Zapisanie zaznaczonych zgód
  110.             $checkedConsents $form->get("consents")->getData();
  111.             if ($checkedConsents && is_array($checkedConsents)) {
  112.                 foreach ($checkedConsents as $checkedConsent) {
  113.                     if ($consent $this->getDoctrine()->getRepository(Consent::class)->find((int) $checkedConsent)) {
  114.                         $consentUser = new ConsentUser;
  115.                         $consentUser
  116.                             ->setConsenst($consent)
  117.                             ->setUser($user)
  118.                             ->setDate(new \Datetime);
  119.                         $em->persist($consentUser);
  120.                         if (strpos($consent->getDescription(), 'newsletter') !== false) {
  121.                             $freshMailService->addSubscriber($user->getEmail());
  122.                         }
  123.                     }
  124.                 }
  125.             }
  126.             // ===
  127.             if ($error === '') {
  128.                 $em->persist($user);
  129.                 $em->flush();
  130.                 $link $request->getScheme() . '://' $request->getHttpHost() . '/ustaw-haslo/' $user->getHash();
  131.                 $title "Witamy w serwisie CAŁA POLSKA CZYTA DZIECIOM!";
  132.                 $email = (new TemplatedEmail())
  133.                     ->to(new Address($user->getEmail(), $user->getName() . ' ' $user->getSurname()))
  134.                     ->subject($title)
  135.                     ->htmlTemplate('email/register.html.twig')
  136.                     ->context([
  137.                         'title' => $title,
  138.                         'link' => $link
  139.                     ]);
  140.                 $mailer->send($email);
  141.                 $this->addFlash('success''Konto zostało utworzone. Na podany adres e-mail został wysłany link do utworzenia hasła.');
  142.                 return $this->redirectToRoute('pageAuthLogin');
  143.             }
  144.         }
  145.         // return $this->render('page/auth/register-old.html.twig', [
  146.         return $this->render('page/auth/register.html.twig', [
  147.             'form' => $form->createView(),
  148.             'error' => $error,
  149.             'user' => $user,
  150.             'provinces' => $this->getDoctrine()->getRepository(Province::class)->findAll()
  151.         ]);
  152.     }
  153.     /**
  154.      * @Route("/rejestracja/data/placowki", name="PageAuthRegisterInstitutionsJson")
  155.      */
  156.     public function listDataTable(Request $request): Response {
  157.         $page $_GET["page"];
  158.         $orderCol $request->request->get("order")[0]["column"];
  159.         $orderDir $request->request->get("order")[0]["dir"];
  160.         $elForPage $request->request->get("length");
  161.         $search $request->request->get("search")["value"];
  162.         $institutions $this->paginator->paginate(
  163.             $this->getDoctrine()->getRepository(Institution::class)->getInstitutionsForDataTable(
  164.                 $orderCol$orderDir$search,
  165.                 ($_GET["name"]) ? $_GET["name"] : null,
  166.                 ($_GET["place"]) ? $_GET["place"] : null,
  167.                 ($_GET["province"]) ? $_GET["province"] : null,
  168.                 ($_GET["district"]) ? $_GET["district"] : null,
  169.                 ($_GET["commune"]) ? $_GET["commune"] : null,
  170.                 ($_GET["category"]) ? $_GET["category"] : null
  171.             ), $page$elForPage
  172.         );
  173.         $data $this->InstitutionForDataTable($institutions);
  174.         return new JsonResponse(
  175.             array(
  176.                 'draw' => $request->request->get("draw"),
  177.                 'data' => $data,
  178.                 'recordsFiltered' =>  $institutions->getTotalItemCount(),
  179.                 'recordsTotal' => $institutions->getTotalItemCount()
  180.             )
  181.         , 200);
  182.     }
  183.     public function InstitutionForDataTable($institutions){
  184.         $data[0] = array("""""""""""");
  185.         $i 0;
  186.         if($institutions){
  187.             foreach($institutions->getItems() as $obj){
  188.                 $pathShow $this->generateUrl('adminInstitutionView', ['institutionId' => $obj->getId()]);
  189.                 $pathAdmin $this->generateUrl('adminInstitutionEdit', ['institutionId' => $obj->getId()]);
  190.                 $streetAndNumbers $obj->getStreet().' '.$obj->getBuilding();
  191.                 if($obj->getLocalNumber()){
  192.                     $streetAndNumbers.= " / ".$obj->getLocalNumber();
  193.                 }
  194.                 $buttons '
  195.                     <div class="text-nowrap">
  196.                         <a href="javascript:;" title="Edytuj dane placówki" onclick="institutions.add(' .$obj->getId(). ')"><i class="fa fa-edit"></i></a>
  197.                         <a href="javascript:;" title="Przypisz placówkę" onclick="institutions.change(' .$obj->getId(). ')"><i class="fa fa-plus-square-o"></i></a>
  198.                     </div>
  199.                 ';
  200.                 $data[$i] = array(
  201.                     $obj->getName(),
  202.                     ($obj->getProvince()) ? $obj->getProvince()->getName() : "",
  203.                     ($obj->getDistrict()) ? $obj->getDistrict()->getName() : "",
  204.                     ($obj->getCommune()) ? $obj->getCommune()->getName() : "",
  205.                     $buttons,
  206.                     $obj->getId()
  207.                 );
  208.                 $i++;
  209.             }
  210.         }
  211.         return $data;
  212.     }
  213.     /**
  214.      * @Route("/rejestracja/data/placowki/dodana", name="PageAuthRegisterInstitutionCustomJson")
  215.      */
  216.     public function getInstitutionCustom(): Response {
  217.         $id $_GET["custom"];
  218.         if($id != ""){
  219.             // $data = $this->getDoctrine()->getRepository(Institution::class)->find($id);
  220.             $obj $this->getDoctrine()->getRepository(Institution::class)->find($id);
  221.             $buttons '
  222.                 <div class="text-nowrap">
  223.                     <a href="javascript:;" onclick="institutions.add(' .$obj->getId(). ')"><i class="fa fa-edit"></i></a>
  224.                     <a href="javascript:;" onclick="institutions.change(' .$obj->getId(). ')"><i class="fa fa-plus-square-o"></i></a>
  225.                 </div>
  226.             ';
  227.             $data = array(
  228.                 $obj->getName(),
  229.                 ($obj->getProvince()) ? $obj->getProvince()->getName() : "",
  230.                 ($obj->getDistrict()) ? $obj->getDistrict()->getName() : "",
  231.                 ($obj->getCommune()) ? $obj->getCommune()->getName() : "",
  232.                 $buttons
  233.             );
  234.             return new JsonResponse( array( 'data' => $data ) , 200);
  235.         }
  236.         return new JsonResponse( array( 'data' => null ), 200);
  237.     }
  238.     /**
  239.      * @Route("/ustaw-haslo/{hash}", name="pageAuthPassword")
  240.      */
  241.     public function password(Request $requestUserPasswordEncoderInterface $encoderFreshMailService $freshMailServicestring $hash): Response
  242.     {
  243.         if ($this->getUser()) {
  244.             return $this->redirectToRoute('pageDashboardIndex');
  245.         }
  246.         $em $this->getDoctrine()->getManager();
  247.         $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  248.             'hash' => $hash
  249.         ]);
  250.         if (!$user) {
  251.             return $this->redirectToRoute('pageAuthLogin');
  252.         }
  253.         $consents $this->getDoctrine()->getRepository(Consent::class)->findBy([
  254.             'isDeleted' => false
  255.         ]);
  256.         $form $this->createForm(PageUserPasswordType::class, $user, [
  257.             'consents' => count($user->getConsentUsers()) === $consents : [] // Jeżeli użytkownik nie ma zaznaczonych zgód, to musi je zaznaczyć (konto założone przez administratora)
  258.         ]);
  259.         $form->handleRequest($request);
  260.         if($form->isSubmitted() && $form->isValid()) {
  261.             $isReset false;
  262.             if ($user->getPassword()) {
  263.                 $isReset true;
  264.             }
  265.             $password $encoder->encodePassword($user$user->getPlainPassword());
  266.             // Zapisanie zaznaczonych zgód (jeżeli konto było zakładane przez administratora)
  267.             if (count($user->getConsentUsers()) === 0) {
  268.                 $checkedConsents $form->get("consents")->getData();
  269.                 if ($checkedConsents && is_array($checkedConsents)) {
  270.                     foreach ($checkedConsents as $checkedConsent) {
  271.                         if ($consent $this->getDoctrine()->getRepository(Consent::class)->find((int) $checkedConsent)) {
  272.                             $consentUser = new ConsentUser;
  273.                             $consentUser
  274.                                 ->setConsenst($consent)
  275.                                 ->setUser($user)
  276.                                 ->setDate(new \Datetime);
  277.                             $em->persist($consentUser);
  278.                             if (strpos($consent->getDescription(), 'newsletter') !== false) {
  279.                                 $freshMailService->addSubscriber($user->getEmail());
  280.                             }
  281.                         }
  282.                     }
  283.                 }
  284.             }
  285.             // ===
  286.             $user
  287.                 ->setPassword($password)
  288.                 ->setHash(null);
  289.             $em->persist($user);
  290.             $em->flush();
  291.             if ($isReset) {
  292.                 $this->addFlash('success''Hasło zostało zmienione.');
  293.             } else {
  294.                 if ($user->getStatus() === 'ACTIVE') {
  295.                     $this->addFlash('success''Hasło zostało ustawione. Możesz się zalogować.');
  296.                 } else {
  297.                     $this->addFlash('success''Hasło zostało ustawione. Poczekaj na akceptację Twojego konta przez administratora.');
  298.                 }
  299.             }
  300.             return $this->redirectToRoute('pageAuthLogin');
  301.         }
  302.         return $this->render('page/auth/password.html.twig', [
  303.             'form' =>$form->createView(),
  304.             'user' => $user
  305.         ]);
  306.     }
  307.     /**
  308.      * @Route("/resetuj-haslo", name="pageAuthResetPassword")
  309.      */
  310.     public function resetPassword(Request $requestMailerInterface $mailer): Response
  311.     {
  312.         if ($this->getUser()) {
  313.             return $this->redirectToRoute('pageDashboardIndex');
  314.         }
  315.         $form $this->createForm(PageUserResetPasswordType::class);
  316.         $form->handleRequest($request);
  317.         if($form->isSubmitted() && $form->isValid()) {
  318.             $data $form->getData();
  319.             $user $this->getDoctrine()->getRepository(User::class)->findOneBy([
  320.                 'email' => $data['email'],
  321.                 'status' => 'ACTIVE'
  322.             ]);
  323.             if ($user) {
  324.                 $user->setHash(hash('sha256'uniqid()));
  325.                 $em $this->getDoctrine()->getManager();
  326.                 $em->persist($user);
  327.                 $em->flush();
  328.                 $link $request->getScheme() . '://' $request->getHttpHost() . '/ustaw-haslo/' $user->getHash();
  329.                 $message 'Kliknij w link <a href="' $link '">' $link '</a> i ustaw nowe hasło do portalu Cała Polska Czyta Dzieciom';
  330.                 $title "Zmień hasło do portalu Cała Polska Czyta Dzieciom";
  331.                 $email = (new TemplatedEmail())
  332.                     ->to(new Address($user->getEmail(), $user->getName() . ' ' $user->getSurname()))
  333.                     ->subject($title)
  334.                     ->htmlTemplate('email/message.html.twig')
  335.                     ->context([
  336.                         'title' => $title,
  337.                         'message' => $message
  338.                     ]);
  339.                 $mailer->send($email);
  340.             }
  341.             $this->addFlash('success''Na podany adres e-mail został wysłany link do utworzenia nowego hasła.');
  342.             return $this->redirectToRoute('pageAuthLogin');
  343.         }
  344.         return $this->render('page/auth/resetPassword.html.twig', [
  345.             'form' => $form->createView()
  346.         ]);
  347.     }
  348.     /**
  349.      * @Route("/wyloguj", name="pageAuthLogout")
  350.      */
  351.     public function logout()
  352.     {
  353.     }
  354.     /**
  355.      * @Route("/lista-placowek", name="pageAuthInstitutions")
  356.      */
  357.     public function list(Request $request): JsonResponse
  358.     {
  359.         $name $request->query->get('name'null);
  360.         $place $request->query->get('place'null);
  361.         $province = (int) $request->query->get('province'0);
  362.         $district = (int) $request->query->get('district'0);
  363.         $commune = (int) $request->query->get('commune'0);
  364.         $custom = (int) $request->query->get('custom'0);
  365.         if ($custom) {
  366.             $institutionsData $this->getDoctrine()->getRepository(Institution::class)->findBy([
  367.                 'id' => $custom
  368.             ]);
  369.         } else {
  370.             $institutionsData $this->getDoctrine()->getRepository(Institution::class)->findByFilters($name$place$province$district$commune);
  371.         }
  372.         $institutions = [];
  373.         foreach ($institutionsData as $institution) {
  374.             $institutions[] = [
  375.                 'id' => $institution->getId(),
  376.                 'name' => $institution->getName(),
  377.                 'province' => $institution->getProvince() ? $institution->getProvince()->getName() : '',
  378.                 'district' => $institution->getDistrict() ? $institution->getDistrict()->getName() : '',
  379.                 'commune' => $institution->getCommune() ? $institution->getCommune()->getName() : ''
  380.             ];
  381.         }
  382.         return new JsonResponse($institutions);
  383.     }
  384.     /**
  385.      * @Route("/dodaj-placowke", name="pageAuthAddInstitution")
  386.      */
  387.     public function addInstitution(Request $requestInstitutionService $institutionService): Response
  388.     {
  389.         $baseInstitution = new Institution;
  390.         if ($id = (int) $request->query->get('id')) {
  391.             $baseInstitution $this->getDoctrine()->getRepository(Institution::class)->find($id);
  392.         }
  393.         $newInstitution = new Institution;
  394.         $newInstitution
  395.             ->setName($baseInstitution->getName())
  396.             ->setRegon($baseInstitution->getRegon())
  397.             ->setStreet($baseInstitution->getStreet())
  398.             ->setBuilding($baseInstitution->getBuilding())
  399.             ->setLocalNumber($baseInstitution->getLocalNumber())
  400.             ->setPostcode($baseInstitution->getPostcode())
  401.             ->setPlace($baseInstitution->getPlace())
  402.             ->setProvince($baseInstitution->getProvince())
  403.             ->setDistrict($baseInstitution->getDistrict())
  404.             ->setCommune($baseInstitution->getCommune())
  405.             ->setCountry($baseInstitution->getCountry())
  406.             ->setCategory($baseInstitution->getCategory())
  407.             ->setType($baseInstitution->getType())
  408.             ->setPhone($baseInstitution->getPhone())
  409.             ->setEmail($baseInstitution->getEmail())
  410.             ->setStatus('INACTIVE');
  411.         if ($baseInstitution->getId()) {
  412.             if ($baseInstitution->getTarget()) {
  413.                 $newInstitution->setTarget($baseInstitution->getTarget());
  414.             } else {
  415.                 $newInstitution->setTarget($baseInstitution);
  416.             }
  417.         }
  418.         $form $this->createForm(InstitutionType::class, $newInstitution);
  419.         $form->handleRequest($request);
  420.         if(
  421.             $form->isSubmitted() &&
  422.             $form->isValid() &&
  423.             !$errors $institutionService->validate($newInstitution)
  424.         ) {
  425.             $em $this->getDoctrine()->getManager();
  426.             $em->persist($newInstitution);
  427.             $em->flush();
  428.         }
  429.         return $this->render('page/auth/addInstitution.html.twig', [
  430.             'form' => $form->createView(),
  431.             'baseInstitution' => $baseInstitution,
  432.             'newInstitution' => $newInstitution,
  433.             'errors' => isset($errors) ? $errors : []
  434.         ]);
  435.     }
  436.     /**
  437.      * @Route("/projekt/{projectUrl}", name="pageAuthProject", requirements={"projectUrl": "[a-zA-Z0-9\-]{1,}"})
  438.      */
  439.     public function project(string $projectUrl):Response
  440.     {
  441.         $form $this ->getDoctrine()->getRepository(Form::class)->findOneBy([
  442.             'url' => $projectUrl
  443.         ]);
  444.         if(!$form){
  445.             throw $this->createNotFoundException();
  446.         }
  447.         if(!$form->getIsAssigned()){
  448.             throw $this->createNotFoundException('Nieprawidłowy formularz');
  449.         }
  450.         if($form->getType() == "evaluation"){
  451.             throw $this->createNotFoundException('Wybrano formularz ewaluacyjny');
  452.         }
  453.         $project null;
  454.         foreach($form->getProjects() as $obj){
  455.             $project $obj;
  456.         }
  457.         $response $this ->redirectToRoute('pageProjectAddStep2', [
  458.             'projectId' => $project->getId()
  459.         ]);
  460.         if(!$this->getUser()){
  461.             $cookie Cookie::create('redirectToProject')
  462.                 ->withValue($project->getId())
  463.                 ->withExpires(new \DateTime('+3 days'))
  464.                 ->withSecure(true)
  465.                 ->withHttpOnly(true);
  466.             $response->headers->setCookie($cookie);
  467.         }
  468.         return $response;
  469.     }
  470. }