src/Controller/ClientController.php line 250

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Client;
  4. use App\Entity\ClientNotification;
  5. use App\Entity\ClientSettings;
  6. use App\Entity\Invitation;
  7. use App\Entity\NotificationType;
  8. use App\Form\Type\ClientType;
  9. use App\Repository\ClientMessageRepository;
  10. use App\Repository\ClientNotificationRepository;
  11. use App\Repository\ClientRepository;
  12. //use App\Service\MailService;
  13. use App\Repository\CountryRepository;
  14. use App\Repository\InvitationRepository;
  15. use App\Service\MailService;
  16. use DateTime;
  17. use \Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\HttpFoundation\JsonResponse;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  22. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  23. use Symfony\Component\Routing\Annotation\Route;
  24. use Vich\UploaderBundle\VichUploaderBundle;
  25. class ClientController extends AbstractController
  26. {
  27.     private ClientRepository $clientRepository;
  28.     private ClientActivationTokenController $clientActivationTokenController;
  29.     private MailService $mailService;
  30.     private InvitationRepository $invitationRepository;
  31.     private UserPasswordHasherInterface $encoder;
  32.     private CountryRepository $countryRepository;
  33.     private ClientNotificationRepository $clientNotificationRepository;
  34.     public function __construct(
  35.         ClientRepository $clientRepository,
  36.         MailService $mailService,
  37.         UserPasswordHasherInterface $encoder,
  38.         InvitationRepository $invitationRepository,
  39.         ClientActivationTokenController $clientActivationTokenController,
  40.         CountryRepository $countryRepository,
  41.         ClientNotificationRepository $clientNotificationRepository
  42.     )
  43.     {
  44.         $this->clientRepository $clientRepository;
  45.         $this->mailService $mailService;
  46.         $this->encoder $encoder;
  47.         $this->invitationRepository=$invitationRepository;
  48.         $this->clientActivationTokenController=$clientActivationTokenController;
  49.         $this->countryRepository=$countryRepository;
  50.         $this->clientNotificationRepository=$clientNotificationRepository;
  51.     }
  52.     #[Route("/register-new-client"name"register_new_client"methods: ["POST"])]
  53.     public function registerClient(Request $request): JsonResponse
  54.     {
  55.         $data $request->request->all();
  56.         $username $data['username'];
  57.         $email $data['email'];
  58.         $password $data['password'];
  59.         if (empty($email) || empty($password)) {
  60.             throw new NotFoundHttpException('Expecting mandatory parameters!');
  61.         }
  62.         $clientExists false;
  63.         $checkClient $this->clientRepository->findOneByEmail($email);
  64.         if(!empty($checkClient)){
  65.             $clientExists true;
  66.         }
  67.         if(!$clientExists){
  68.             $newUser = new Client();
  69.             $encoded $this->encoder->hashPassword($newUser,$password);
  70.             $newUser
  71.                 ->setEmail($email)
  72.                 ->setUsername($username)
  73.                 ->setPassword($encoded)
  74.                 ->setName("Unknown")
  75.                 ->setSurname("Unknown")
  76.                 ->setActivatedAt(new \DateTime("0/0/0000 00:00:00"))
  77.                 ->setRoles((['ROLE_CLIENT']))
  78.                 ->setIsDeleted(false)
  79.                 ->setEnabled(true)
  80.                 ->setDateCreated(new \DateTime('now'));
  81.             $newClient $this->clientRepository->save($newUser,true);
  82.             $notification = new ClientNotification();
  83.             $notification
  84.                 ->setCreatedAt(new \DateTime('now'))
  85.                 ->setTitle('Welcome notification')
  86.                 ->setNotificationText('Welcome to Rap Battle Online '.$newClient->getName())
  87.                 ->setType(NotificationType::INTERACTION_TYPE_MESSAGE)
  88.                 ->setClient($newClient)
  89.                 ->setNotificationRead(false);
  90.             $this->clientNotificationRepository->save($notification,true);
  91.             $settings $this->getDefaultClientSettings($newClient);
  92.             $newClient->setClientSettings($settings);
  93.             $this->clientRepository->save($newUser,true);
  94.             $token $this->clientActivationTokenController->createActivationTokenForClientAction($newClient->getId());
  95.             $this->mailService->sendWelcomeMessage($email,$newUser->getUsername(),$token->getToken());
  96.             $this->mailService->notifyAgents($newUser->getUsername());
  97.             $data = [
  98.                 'id' => $newClient->getId(),
  99.                 'email' => $newClient->getEmail()
  100.             ];
  101.             return new JsonResponse($dataResponse::HTTP_CREATED);
  102.         }else{
  103.             return new JsonResponse(["message" => "Email je je vyuzivan"], Response::HTTP_BAD_REQUEST);
  104.         }
  105.     }
  106.     #[Route("/reset-password-process/"name"reset_password"methods: ["POST"])]
  107.     public function resetPassword(Request $request): JsonResponse
  108.     {
  109.         $data $request->request->all();
  110.         $email $data['email'];
  111.         $client $this->clientRepository->findOneBy(['email'=>$email]);
  112.         if($client != null){
  113.             $clientName $client->getName().' '.$client->getSurname();
  114.             $newGeneratedPasswordHash $this->generateRandomString(12);
  115.             $validToDate = new \DateTime('tomorrow');
  116.             $client->setResetPasswordHash($newGeneratedPasswordHash);
  117.             $client->setResetPasswordHashValidTo($validToDate);
  118.             $this->clientRepository->save($client,true);
  119.             $this->mailService->sendResetPassword($email,$newGeneratedPasswordHash);
  120.             return new JsonResponse(["message" => "Email vyresetovan!""clientName"=>$clientName"resetPasswordLink"=>$newGeneratedPasswordHash], Response::HTTP_OK);
  121.         }else{
  122.             return new JsonResponse(["message" => "Uzivatel nenalezen"], Response::HTTP_NOT_FOUND);
  123.         }
  124.     }
  125.     #[Route("/reseting-password/{hash}"name"reseting_password_page"methods: ["GET"])]
  126.     public function resetingPasswordPage($hash): Response
  127.     {
  128.         $client $this->clientRepository->findOneBy(['resetPasswordHash'=>$hash]);
  129.         if($client!=null)
  130.         {
  131.             $validTo $client->getResetPasswordHashValidTo();
  132.             $today = new DateTime('now');
  133.             if($today>$validTo){
  134.                 return $this->render('pages/auth/reseting-password.html.twig', ["clientHash"=>$hash]);
  135.             }else{
  136.                 return $this->render('pages/auth/reseting-password-not-valid.html.twig', []);
  137.             }
  138.         }
  139.         else
  140.         {
  141.             return $this->render('pages/auth/reseting-password-not-valid.html.twig', []);
  142.         }
  143.     }
  144.     #[Route("/reseting-password"name"reseting_password_validate"methods: ["POST"])]
  145.     public function resetingPasswordValidate(Request $request): JsonResponse
  146.     {
  147.         //$data = json_decode($request->getContent(), true);
  148.         $data $request->request->all();
  149.         dump($data);
  150.         $clientHash $data["clientHash"];
  151.         $newPassword $data["password_new"];
  152.         $client $this->clientRepository->findOneBy(['resetPasswordHash'=>$clientHash]);
  153.         $encoded $this->encoder->hashPassword($client$newPassword);
  154.         $client->setPassword($encoded);
  155.         $client->setResetPasswordHash(null);
  156.         $client->setResetPasswordHashValidTo(new \DateTime('1/1/2024'));
  157.         $this->clientRepository->save($client,true);
  158.         return new JsonResponse(["message" => "Heslo zmeneno!"], Response::HTTP_OK);
  159.     }
  160.     #[Route("/client/edit"name"edit_client_info"methods: ["POST"])]
  161.     public function editClientBasic(Request $request): Response
  162.     {
  163.         $data $request->request->all();
  164.         $clientId $data['client_id'];
  165.         $firstname $data['client']['name'];
  166.         $surname $data['client']['surname'];
  167.         $username $data['client']['username'];
  168.         $city $data['client']['city'];
  169.         $countryId $data['client']['country'];
  170.         $country null;
  171.         if(intval($countryId)!==0){
  172.             $country $this->countryRepository->findOneBy(['id'=>$countryId]);
  173.         }
  174.         $client $this->clientRepository->findOneBy(['id'=>$clientId]);
  175.         $form=$this->createForm(ClientType::class,$client);
  176.         $form->handleRequest($request);
  177.         $updatedClient=null;
  178.         if($form->isSubmitted() && $form->isValid()){
  179.             dump($form->getExtraData());
  180.             $client
  181.                 ->setName($firstname)
  182.                 ->setSurname($surname)
  183.                 ->setUsername($username)
  184.                 ->setCity($city)
  185.                 ->setCountry($country)
  186.                 ->setDateUpdated(new DateTime('now'));
  187.             $updatedClient $this->clientRepository->save($client,true);
  188.         }
  189. //        $data = [
  190. //            'id' => $updatedClient->getId(),
  191. //            'email' => $updatedClient->getEmail()
  192. //        ];
  193. //        if($updatedClient->getUsername() === $username && $updatedClient->getSurname() === $surname && $updatedClient->getName() === $firstname){
  194.             return $this->redirectToRoute('profile');
  195. //        }else{
  196. //            return new JsonResponse("Err", Response::HTTP_BAD_REQUEST);
  197. //        }
  198.     }
  199.     #[Route("/reset-password"name"reset_password_page")]
  200.     public function resetPasswordPageAction(): Response
  201.     {
  202.         return $this->render('pages/auth/reset-password.html.twig');
  203.     }
  204.     #[Route("/sent-reset-password/{email}"name"reset_password_sent",methods: ['GET'])]
  205.     public function resetPasswordSent($email): Response
  206.     {
  207.         return $this->render('pages/reseting-password-email-sent.html.twig',[
  208.             'email'=>$email
  209.         ]);
  210.     }
  211.     #[Route("/invite-client"name"invite_client"methods: ["POST"])]
  212.     public function inviteNewClient(Request $request): JsonResponse
  213.     {
  214.         $data $request->request->all();
  215.         $email $data['email'];
  216.         $client $this->clientRepository->findBy(['email'=>$email]);
  217.         if($client!=null){
  218.             return new JsonResponse($dataResponse::HTTP_FOUND);
  219.         }
  220.         // Create valid invite
  221.         $invitationHash $this->generateRandomString();
  222.         $invite = new Invitation();
  223.         $invite
  224.             ->setInvitedEmail($email)
  225.             ->setInvitationHash($invitationHash)
  226.             ->setInviteAccepted(false)
  227.             ->setInviteSendDate(new \DateTime('now'));
  228.         $this->invitationRepository->save($invite,true);
  229.         //TODO Notify new client
  230.         return new JsonResponse($dataResponse::HTTP_CREATED);
  231.     }
  232.     #[Route("/check-username-exist"name"check_username_exist"methods: ["POST"])]
  233.     public function checkUsernameExistAction(Request $request): JsonResponse
  234.     {
  235.         $data $request->request->all();
  236.         $username $data['username'];
  237.         $client $this->clientRepository->findOneBy(['username'=>$username]);
  238.         $exist=false;
  239.         if($client!=null){
  240.             $exist=true;
  241.         }
  242.         $data=[
  243.            "exist"=>$exist
  244.         ];
  245.         return new JsonResponse($data,200);
  246.     }
  247.     #[Route("/check-email-exist"name"check_email_exist"methods: ["POST"])]
  248.     public function checkEmailExistAction(Request $request): JsonResponse
  249.     {
  250.         $data $request->request->all();
  251.         $email $data['email'];
  252.         $client $this->clientRepository->findOneBy(['email'=>$email]);
  253.         $exist=false;
  254.         if($client!=null){
  255.             $exist=true;
  256.         }
  257.         $data=[
  258.             "exist"=>$exist
  259.         ];
  260.         return new JsonResponse($data,200);
  261.     }
  262.     #[Route(path'/client-avatar-upload'name'clientUploadAvatar'methods: ['POST'])]
  263.     public function frontendClientUploadAvatarAction(Request $request): JsonResponse
  264.     {
  265.         $user $this->getUser();
  266.         $client $this->clientRepository->findOneByEmail($user->getUserIdentifier());
  267.         $avatarNew $request->files->get('imageFile');
  268.         $form $this->createForm(ClientType::class, $client);
  269.         $form->handleRequest($request);
  270.         if ($form->isSubmitted() && $form->isValid()) {
  271.             $client
  272.                 ->setDateUpdated(new \DateTime('now'));
  273.         }
  274.         if($this->clientRepository->save($client,true)){
  275.             return new JsonResponse("Uploaded"Response::HTTP_OK);
  276.         }else{
  277.             return new JsonResponse("Error"Response::HTTP_BAD_REQUEST);
  278.         }
  279.     }
  280.     // HELPERS
  281.     public function generateRandomString($length 10) {
  282.         $characters '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  283.         $charactersLength strlen($characters);
  284.         $randomString '';
  285.         for ($i 0$i $length$i++) {
  286.             $randomString .= $characters[rand(0$charactersLength 1)];
  287.         }
  288.         return $randomString;
  289.     }
  290.     function getDefaultClientSettings($newClient):ClientSettings
  291.     {
  292.         $res = new ClientSettings();
  293.         $res->setDisplayContact(true)->setClient($newClient);
  294.         return $res;
  295.     }
  296. //    public function upload(Request $request):Response
  297. //    {
  298. //        $client = new Client();
  299. //        $form = $this->createForm(ImageType::class, $image);
  300. //        $token = $request->request->get('token');
  301. //        $form->handleRequest($request);
  302. //
  303. //        if ($form->isSubmitted() && $this->isCsrfTokenValid('image-upload', $token)) {
  304. //            dump($image);
  305. //            dump($form->getData());
  306. //            $this->em->persist($image);
  307. //            $this->em->flush();
  308. //            return $this->redirectToRoute('admin_image_index');
  309. //        }
  310. //
  311. //        return $this->render('admin/image/upload.html.twig', array(
  312. //            'form' => $form->createView()
  313. //        ));
  314. //    }
  315. }