From 3410abd70a9d3c57c19bea5f573e0b40a1759357 Mon Sep 17 00:00:00 2001 From: Ro Date: Fri, 30 Dec 2022 14:41:49 -0800 Subject: [PATCH] Location Editing Part. 1 Now that full-text searching is set up in the DB, the next step is data population. The adding and editing templates were added as long as routes and base functionality to add single locations. Adding works and editing is almost there but both still need to cleaned up. The basic plumbing will be completed and then the tweaking to account for roles and login status for the sake of security. Part 2 will include clean up and and bulk uploads through the use of CSV files. --- .gitignore | 3 +- migrations/Version20221226225509.php | 36 +++++ migrations/Version20221226230207.php | 32 ++++ public/assets/css/front/forms.css | 39 +++++ public/assets/css/front/frame.css | 23 ++- public/assets/css/front/index-den.css | 10 ++ public/assets/css/front/typography.css | 4 +- src/Controller/Routes/Back/Locations.php | 167 ++++++++++++++++++++ src/Controller/Routes/Back/Members.php | 2 +- src/Entity/Location.php | 186 +++++++++++++++++++++++ src/Repository/LocationRepository.php | 66 ++++++++ src/Service/Auth.php | 19 ++- src/Service/FileUploader.php | 46 ++++++ src/Service/HandleLocations.php | 142 +++++++++++++++++ templates/back/locations.twig | 34 +++++ templates/back/start.twig | 11 +- templates/base/frame.twig | 22 +++ templates/forms/add-location.twig | 27 ++++ templates/forms/edit-location.twig | 31 ++++ 19 files changed, 879 insertions(+), 21 deletions(-) create mode 100644 migrations/Version20221226225509.php create mode 100644 migrations/Version20221226230207.php create mode 100644 public/assets/css/front/forms.css create mode 100644 src/Controller/Routes/Back/Locations.php create mode 100644 src/Entity/Location.php create mode 100644 src/Repository/LocationRepository.php create mode 100644 src/Service/FileUploader.php create mode 100644 src/Service/HandleLocations.php create mode 100644 templates/back/locations.twig create mode 100644 templates/forms/add-location.twig create mode 100644 templates/forms/edit-location.twig diff --git a/.gitignore b/.gitignore index aa781fd..dc8ca91 100644 --- a/.gitignore +++ b/.gitignore @@ -7,8 +7,7 @@ .env /config/secrets/prod/prod.decrypt.private.php /public/bundles/ -/public/images/avatars/ -/public/images/blog/ +/public/assets/images/examples/ /var/ /vendor/ /assets/node_modules diff --git a/migrations/Version20221226225509.php b/migrations/Version20221226225509.php new file mode 100644 index 0000000..f1a0c44 --- /dev/null +++ b/migrations/Version20221226225509.php @@ -0,0 +1,36 @@ +addSql('CREATE SEQUENCE location_id_seq INCREMENT BY 1 MINVALUE 1 START 1'); + $this->addSql('CREATE TABLE location (id INT NOT NULL, uuid VARCHAR(255) NOT NULL, name VARCHAR(255) NOT NULL, url VARCHAR(255) NOT NULL, description TEXT NOT NULL, images JSON DEFAULT NULL, active BOOLEAN NOT NULL, rating VARCHAR(255) NOT NULL, added_by INT NOT NULL, created_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, updated_at TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id))'); + $this->addSql('COMMENT ON COLUMN location.created_at IS \'(DC2Type:datetime_immutable)\''); + $this->addSql('COMMENT ON COLUMN location.updated_at IS \'(DC2Type:datetime_immutable)\''); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('CREATE SCHEMA public'); + $this->addSql('DROP SEQUENCE location_id_seq CASCADE'); + $this->addSql('DROP TABLE location'); + } +} diff --git a/migrations/Version20221226230207.php b/migrations/Version20221226230207.php new file mode 100644 index 0000000..18c6c49 --- /dev/null +++ b/migrations/Version20221226230207.php @@ -0,0 +1,32 @@ +addSql('ALTER TABLE location ADD tags VARCHAR(255) NOT NULL'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('CREATE SCHEMA public'); + $this->addSql('ALTER TABLE location DROP tags'); + } +} diff --git a/public/assets/css/front/forms.css b/public/assets/css/front/forms.css new file mode 100644 index 0000000..39fe46c --- /dev/null +++ b/public/assets/css/front/forms.css @@ -0,0 +1,39 @@ +input[type="email"], +input[type="password"], +input[type="text"] { + border: 0; + padding: 5px; + border-radius: 5px; + font: 18px var(--base-type); + display: inline-block; + background: var(--white); + color: var(--primary); +} + +textarea { + border: 0; + border-radius: 3px; + color: var(--primary); + background: var(--white); +} + +button, +input[type="submit"] { + background: var(--highlight); + color: var(--white); + font: 20px var(--base-type); + border-radius: 5px; + position: relative; + cursor: pointer; + border: 0; + transition: all 0.3s linear; +} + +select { + font: 20px var(--base-type); + border-radius: 5px; + border: 1px solid var(--primary); + appearance: none; + color: var(--primary); + background: var(--secondary); +} diff --git a/public/assets/css/front/frame.css b/public/assets/css/front/frame.css index ff62cea..e7bd387 100644 --- a/public/assets/css/front/frame.css +++ b/public/assets/css/front/frame.css @@ -16,22 +16,39 @@ html body { overflow-x: hidden; } +header { + width: 100%; + color: var(--primary); + background: var(--secondary); +} + +header > nav { + display: grid; + grid-template-columns: 200px 1fr; + padding: 10px; +} + +header > nav > div[role="nav-right"] { + text-align: right; +} + /* GLOBALS */ a { color: var(--primary); text-decoration: none; - border-bottom: 1px solid var(--secondary); + border-bottom: 1px solid var(--white); transition: all 0.2s linear; } a:hover { - border-bottom: 1px solid var(--highlight); + border-bottom: 1px solid var(--primary); } sup { background: var(--black); color: var(--white); - padding: 3px; + padding: 2px; border-radius: 3px; + vertical-align: text-bottom; } diff --git a/public/assets/css/front/index-den.css b/public/assets/css/front/index-den.css index 8dbf3bc..8005d6b 100644 --- a/public/assets/css/front/index-den.css +++ b/public/assets/css/front/index-den.css @@ -10,3 +10,13 @@ section[role="den-login"] div[role="system-notice"] { background: var(--highlight); color: var(--primary); } + +section[role="den-index"], +section[role="loc-index"] { + padding: 20px; +} + +section a { + color: var(--white); + border-bottom: 1px solid var(--secondary); +} diff --git a/public/assets/css/front/typography.css b/public/assets/css/front/typography.css index 2a02551..218367c 100644 --- a/public/assets/css/front/typography.css +++ b/public/assets/css/front/typography.css @@ -26,7 +26,7 @@ h3 { } h1 { - font-size: 2em; + font-size: 2.5em; font-weight: 700; } @@ -36,7 +36,7 @@ h2 { } h3 { - font-size: 1.5em; + font-size: 1.2em; font-weight: 500; } diff --git a/src/Controller/Routes/Back/Locations.php b/src/Controller/Routes/Back/Locations.php new file mode 100644 index 0000000..ddb160a --- /dev/null +++ b/src/Controller/Routes/Back/Locations.php @@ -0,0 +1,167 @@ +LOGGED IN"); + } + + /** + * @Route("/den/locations/page/{pageNum}", name="den-locations") + */ + public function locationIndex( + Request $request, + RequestStack $requestStack, + Auth $auth, + HandleLocations $locations, + string $pageNum + ): Response { + $result = $auth->status(); + if ($result["status"]) { + $session = $requestStack->getSession(); + $member = $session->get("member"); + $list = $locations->getLocationsPage($pageNum); + return $this->render("back/locations.twig", [ + "title" => "Bad Space | Locations", + "handle" => $member->getHandle(), + "list" => $list, + "mode" => "index" + ]); + } else { + return $this->render("back/index.twig", [ + "title" => "Close the door behind you", + ]); + } + } + + /** + * @Route("/den/locations/add", name="location-add") + */ + public function addLocation( + Request $request, + Auth $auth, + HandleLocations $locations, + ManagerRegistry $doctrine, + FileUploader $uploader + ): Response { + $result = $auth->status(); + if ($result["status"]) { + if ($request->getMethod() == "GET") { + return $this->render("back/locations.twig", [ + "title" => "Bad Space | Locations | Add", + "mode" => "add" + ]); + } else { + //add new member + $token = $request->get("token"); + $notice = ""; + $entityManager = $doctrine->getManager(); + + //token check + if (!$this->isCsrfTokenValid("upload", $token)) { + $logger->info("CSRF failure"); + + return new Response( + "Operation not allowed", + Response::HTTP_BAD_REQUEST, + [ + "content-type" => "text/plain", + ] + ); + } + + $examples = []; + $files = $request->files->get("loc_examples"); + if (!empty($files)) { + for ($i = 0; $i < count($files); $i++) { + $path = $files[$i]->getClientOriginalName(); + array_push($examples, ["image_index" => $i, "path" => urlencode($path)]); + $uploader->uploadExamples("../public/assets/images/examples", $files[$i]); + } + } + + if ( + $request->request->get("loc_name") == "" || + $request->request->get("loc_url") == "" || + $request->request->get("loc_desc") == "" || + $request->request->get("loc_tags") == "" + ) { + $notice = "All fields are required, champ."; + return $this->render("back/locations.twig", [ + "title" => "Bad Space | Locations | Add", + "notice" => $notice, + "mode" => "add" + ]); + } + + //check clear, call add method + $response = $locations->addLocation($request, $result["id"]); + if ($response["status"]) { + $notice = "New location added! Take a break."; + return $this->render("back/locations.twig", [ + "title" => "Bad Space | Locations | Add", + "notice" => $notice, + "mode" => "add" + ]); + } else { + return $this->render("back/locations.twig", [ + "title" => "Bad Space | Locations | Add", + "notice" => $response["message"], + "mode" => "add" + ]); + } + } + } else { + //back to index to login + header("Location:/den"); + return new Response("LOGGED IN"); + } + } + + /** + * @Route("/den/locations/edit/{uuid}", name="location-edit") + */ + public function editLocation( + Request $request, + Auth $auth, + HandleLocations $locations, + ManagerRegistry $doctrine, + FileUploader $uploader, + string $uuid = "1" + ): Response { + $result = $auth->status(); + if ($result["status"]) { + $location = $locations->getLocationbyUUID($uuid); + return $this->render("back/locations.twig", [ + "title" => "Bad Space | Locations | Edit", + "mode" => "edit", + "location" => $location[0] + ]); + } else { + header("Location:/den"); + return new Response("LOGGED IN"); + } + } +} diff --git a/src/Controller/Routes/Back/Members.php b/src/Controller/Routes/Back/Members.php index 3e254c5..875b9ee 100644 --- a/src/Controller/Routes/Back/Members.php +++ b/src/Controller/Routes/Back/Members.php @@ -137,7 +137,7 @@ class Members extends AbstractController } } else { //back to index to login - header("Location:/knockknock"); + header("Location:/den"); return new Response("LOGGED IN"); } } diff --git a/src/Entity/Location.php b/src/Entity/Location.php new file mode 100644 index 0000000..7091d9d --- /dev/null +++ b/src/Entity/Location.php @@ -0,0 +1,186 @@ +id; + } + + public function getUuid(): ?string + { + return $this->uuid; + } + + public function setUuid(string $uuid): self + { + $this->uuid = $uuid; + + return $this; + } + + public function getName(): ?string + { + return $this->name; + } + + public function setName(string $name): self + { + $this->name = $name; + + return $this; + } + + public function getUrl(): ?string + { + return $this->url; + } + + public function setUrl(string $url): self + { + $this->url = $url; + + return $this; + } + + public function getDescription(): ?string + { + return $this->description; + } + + public function setDescription(string $description): self + { + $this->description = $description; + + return $this; + } + + public function getImages(): array + { + return $this->images; + } + + public function setImages(?array $images): self + { + $this->images = $images; + + return $this; + } + + public function isActive(): ?bool + { + return $this->active; + } + + public function setActive(bool $active): self + { + $this->active = $active; + + return $this; + } + + public function getRating(): ?string + { + return $this->rating; + } + + public function setRating(string $rating): self + { + $this->rating = $rating; + + return $this; + } + + public function getAddedBy(): ?int + { + return $this->addedBy; + } + + public function setAddedBy(int $addedBy): self + { + $this->addedBy = $addedBy; + + return $this; + } + + public function getCreatedAt(): ?\DateTimeImmutable + { + return $this->createdAt; + } + + public function setCreatedAt(\DateTimeImmutable $createdAt): self + { + $this->createdAt = $createdAt; + + return $this; + } + + public function getUpdatedAt(): ?\DateTimeImmutable + { + return $this->updatedAt; + } + + public function setUpdatedAt(\DateTimeImmutable $updatedAt): self + { + $this->updatedAt = $updatedAt; + + return $this; + } + + public function getTags(): ?string + { + return $this->tags; + } + + public function setTags(string $tags): self + { + $this->tags = $tags; + + return $this; + } +} diff --git a/src/Repository/LocationRepository.php b/src/Repository/LocationRepository.php new file mode 100644 index 0000000..e64cb85 --- /dev/null +++ b/src/Repository/LocationRepository.php @@ -0,0 +1,66 @@ + + * + * @method Location|null find($id, $lockMode = null, $lockVersion = null) + * @method Location|null findOneBy(array $criteria, array $orderBy = null) + * @method Location[] findAll() + * @method Location[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) + */ +class LocationRepository extends ServiceEntityRepository +{ + public function __construct(ManagerRegistry $registry) + { + parent::__construct($registry, Location::class); + } + + public function save(Location $entity, bool $flush = false): void + { + $this->getEntityManager()->persist($entity); + + if ($flush) { + $this->getEntityManager()->flush(); + } + } + + public function remove(Location $entity, bool $flush = false): void + { + $this->getEntityManager()->remove($entity); + + if ($flush) { + $this->getEntityManager()->flush(); + } + } + +// /** +// * @return Location[] Returns an array of Location objects +// */ +// public function findByExampleField($value): array +// { +// return $this->createQueryBuilder('l') +// ->andWhere('l.exampleField = :val') +// ->setParameter('val', $value) +// ->orderBy('l.id', 'ASC') +// ->setMaxResults(10) +// ->getQuery() +// ->getResult() +// ; +// } + +// public function findOneBySomeField($value): ?Location +// { +// return $this->createQueryBuilder('l') +// ->andWhere('l.exampleField = :val') +// ->setParameter('val', $value) +// ->getQuery() +// ->getOneOrNullResult() +// ; +// } +} diff --git a/src/Service/Auth.php b/src/Service/Auth.php index 586cb51..be3b029 100644 --- a/src/Service/Auth.php +++ b/src/Service/Auth.php @@ -81,13 +81,20 @@ class Auth public function status() { $response = []; + //checks to see if member session exists if ($this->session->get("member")) { - //$member = $this->session->get("member"); - $response = [ - "status" => true, - "role" => $this->session->get("member")->getRole(), - "token" => $this->session->get("token"), - ]; + //checks if token is still valid + $verify = Token::validateExpiration($this->session->get("token"), $this->secret); + if ($verify) { + $response = [ + "status" => true, + "role" => $this->session->get("member")->getRole(), + "id" => $this->session->get("member")->getId(), + "token" => $this->session->get("token"), + ]; + } else { + $response = ["status" => false, "role" => null]; + } } else { $response = ["status" => false, "role" => null]; } diff --git a/src/Service/FileUploader.php b/src/Service/FileUploader.php new file mode 100644 index 0000000..c0376ab --- /dev/null +++ b/src/Service/FileUploader.php @@ -0,0 +1,46 @@ +logger = $logger; + } + + public function upload($uploadDir, $file, $filename) + { + try { + $file->move($uploadDir, $filename); + } catch (FileException $e) { + $this->logger->error("failed to upload image: " . $e->getMessage()); + throw new FileException("Failed to upload file"); + } + } + + public function uploadExamples($examplesDir, $file) + { + try { + $file->move($examplesDir, urldecode($file->getClientOriginalName())); + } catch (FileException $e) { + $this->logger->error("failed to upload image: " . $e->getMessage()); + throw new FileException("Failed to upload image file"); + } + } + + public function uploadAvatar($avatarsDir, $file) + { + try { + $file->move($avatarsDir, $file->getClientOriginalName()); + } catch (FileException $e) { + $this->logger->error("failed to upload image: " . $e->getMessage()); + throw new FileException("Failed to upload image file"); + } + } +} diff --git a/src/Service/HandleLocations.php b/src/Service/HandleLocations.php new file mode 100644 index 0000000..ccd1faa --- /dev/null +++ b/src/Service/HandleLocations.php @@ -0,0 +1,142 @@ +entityManager = $entityManager; + $this->session = $requestStack->getSession(); + } + + public function getActiveLocations() + { + $listings = $this->entityManager->getRepository(Location::class); + $locations = $listings->findBy(["active" => true]); + + return $locations; + } + + public function getLocationByUUID(string $uuid) + { + return $this->entityManager->getRepository(Location::class)->findBy(["uuid" => $uuid]); + } + + public function getLocationsPage(int $page) + { + $locations = $this->entityManager->getRepository(Location::class); + $list = $locations->findBy( + [], + ["id" => "ASC"] + ); + + $count = ceil(count($list) / $this->limit); + $totalCount = count($list); + + $shelf = []; + $range = $page * $this->limit - $this->limit; + for ($i = 0; $i <= $this->limit; $i++) { + try { + array_push($shelf, $list[$i + $range]); + } catch (Exception $error) { + } + } + + return [ + "locations" => $shelf, + "total" => $count, + "totalLocations" => $totalCount, + ]; + } + + /** + * Add new location to db + * + * @param Request $request object containing posted data + * @return JSON + */ + public function addLocation($request, $memberId) + { + $errorMessage = null; + $location = new Location(); + + //submitted values + $name = $request->request->get("loc_name"); + $location->setName($name); + $url = $request->request->get("loc_url"); + $location->setUrl($url); + $desc = $request->request->get("loc_desc"); + $location->setDescription($desc); + $tags = $request->request->get("loc_tags"); + $location->setTags($tags); + $rating = $request->request->get("rating"); + $location->setRating($rating); + //get images + $files = $request->files->get("loc_examples"); + if (!empty($files)) { + $examples = []; + for ($i = 0; $i < count($files); $i++) { + $path = $files[$i]->getClientOriginalName(); + array_push($examples, ["image_index" => $i, "path" => urlencode($path)]); + } + $location->setImages($examples); + } + + //set defaults + $location->setUuid(Uuid::v4()); + $location->setActive(false); + $location->setCreatedAt(new \DateTimeImmutable()); + $location->setUpdatedAt(new \DateTimeImmutable()); + $location->setAddedBy($memberId); + + $this->entityManager->persist($location); + + try { + $this->entityManager->flush(); + } catch (PDOException $error) { + $errorMessage = $error->getMessage(); + } catch (DBALException $error) { + $errorMessage = $error->getMessage(); + } catch (ORMException $error) { + $errorMessage = $error->getMessage(); + } catch (Exception $error) { + $errorMessage = $error->getMessage(); + } catch (SyntaxErrorException $e) { + $errorMessage = $error->getMessage(); + } + // return result status + if ($errorMessage == null) { + return $response = [ + "status" => true, + "message" => "New member added. Woohoo!", + ]; + } else { + return $response = ["status" => false, "message" => $errorMessage]; + } + } +} diff --git a/templates/back/locations.twig b/templates/back/locations.twig new file mode 100644 index 0000000..dbbeb5c --- /dev/null +++ b/templates/back/locations.twig @@ -0,0 +1,34 @@ +{% extends "base/frame.twig" %} +{% block stylesheets %} + + {% endblock %} + + {% block main %} +
+

+ Location Listing +

+ {% if notice is defined %} +
+ {{ notice }} +
+ {% endif %} + + {% if mode == "add" %} +

Add New Location

+ {{ include("forms/add-location.twig") }} + {% elseif mode == "edit" %} +

Editing + {{ location.name }}

+ {{ include("forms/edit-location.twig") }} + {% else %} +

Take care. These are bad places.

+ {% for location in list.locations %} + + ID:{{ location.id }} + {{ location.name }}
+ {% endfor %} + {% endif %} + +
+ {% endblock %} diff --git a/templates/back/start.twig b/templates/back/start.twig index f3ee9eb..ca7c623 100644 --- a/templates/back/start.twig +++ b/templates/back/start.twig @@ -1,17 +1,14 @@ {% extends "base/frame.twig" %} {% block stylesheets %} - + {% endblock %} {% block main %} -
+

Welcome to the Den. -

- Hey - {{ handle }} - . Nice to see you again. - Bye bye + + Remember to pace yourself because you're working with some of the worse places on the web. Drink water, takes lot of breaks and remember you are the reason the interent is becoming safer.
{% endblock %} diff --git a/templates/base/frame.twig b/templates/base/frame.twig index e57ec96..14fa53b 100644 --- a/templates/base/frame.twig +++ b/templates/base/frame.twig @@ -10,6 +10,28 @@ {% block stylesheets %}{% endblock %} +
+ + +
{% block main %}{% endblock %}
diff --git a/templates/forms/add-location.twig b/templates/forms/add-location.twig new file mode 100644 index 0000000..4e8a188 --- /dev/null +++ b/templates/forms/add-location.twig @@ -0,0 +1,27 @@ +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+ +
diff --git a/templates/forms/edit-location.twig b/templates/forms/edit-location.twig new file mode 100644 index 0000000..9b74a86 --- /dev/null +++ b/templates/forms/edit-location.twig @@ -0,0 +1,31 @@ +
+
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+ +