diff --git a/composer.json b/composer.json index dbb68cb..759ce3c 100644 --- a/composer.json +++ b/composer.json @@ -4,7 +4,7 @@ "minimum-stability": "stable", "prefer-stable": true, "require": { - "php": ">=8.2", + "php": ">=8.0", "ext-ctype": "*", "ext-iconv": "*", "doctrine/dbal": "^3", @@ -100,7 +100,7 @@ "symfony/browser-kit": "7.0.7", "symfony/css-selector": "7.0.7", "symfony/debug-bundle": "7.0.7", - "symfony/maker-bundle": "^1.0", + "symfony/maker-bundle": "^1.59", "symfony/phpunit-bridge": "^7.0", "symfony/stopwatch": "7.0.7", "symfony/web-profiler-bundle": "7.0.7" diff --git a/composer.lock b/composer.lock index 9c94d3e..d220368 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "b12441d7e7daa91f6af1b31decf59970", + "content-hash": "23d2c64b5bd955feec6a3a3d7dd6a841", "packages": [ { "name": "composer/semver", @@ -9725,7 +9725,7 @@ "prefer-stable": true, "prefer-lowest": false, "platform": { - "php": ">=8.2", + "php": ">=8.0", "ext-ctype": "*", "ext-iconv": "*" }, diff --git a/config/packages/security.yaml b/config/packages/security.yaml index 367af25..fbc97f9 100644 --- a/config/packages/security.yaml +++ b/config/packages/security.yaml @@ -1,17 +1,30 @@ security: # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords password_hashers: - Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto' - # https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider + Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: + algorithm: bcrypt + cost: 13 + providers: - users_in_memory: { memory: null } + app_user_provider: + entity: + class: App\Entity\Profil + property: name firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false main: lazy: true - provider: users_in_memory + provider: app_user_provider + form_login: + login_path: app_login + check_path: app_login + enable_csrf: true + logout: + path: app_logout + # where to redirect after logout + # target: app_any_route # activate different ways to authenticate # https://symfony.com/doc/current/security.html#the-firewall @@ -28,12 +41,6 @@ security: when@test: security: password_hashers: - # By default, password hashers are resource intensive and take time. This is - # important to generate secure password hashes. In tests however, secure hashes - # are not important, waste resources and increase test times. The following - # reduces the work factor to the lowest possible values. Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: - algorithm: auto + algorithm: bcrypt cost: 4 # Lowest possible value for bcrypt - time_cost: 3 # Lowest possible value for argon - memory_cost: 10 # Lowest possible value for argon diff --git a/config/routes/security.yaml b/config/routes/security.yaml index f853be1..60a7afb 100644 --- a/config/routes/security.yaml +++ b/config/routes/security.yaml @@ -1,3 +1,3 @@ _security_logout: resource: security.route_loader.logout - type: service + type: service \ No newline at end of file diff --git a/migrations/Version20240611131531.php b/migrations/Version20240611131531.php new file mode 100644 index 0000000..838e4bf --- /dev/null +++ b/migrations/Version20240611131531.php @@ -0,0 +1,41 @@ +addSql('CREATE TEMPORARY TABLE __temp__post AS SELECT id, profil_id, title, text, is_dream, up_vote, down_vote FROM post'); + $this->addSql('DROP TABLE post'); + $this->addSql('CREATE TABLE post (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profil_id INTEGER NOT NULL, title VARCHAR(255) DEFAULT NULL, text VARCHAR(512) DEFAULT NULL, is_dream BOOLEAN NOT NULL, up_vote INTEGER DEFAULT 0 NOT NULL, down_vote INTEGER DEFAULT 0 NOT NULL, CONSTRAINT FK_5A8A6C8D275ED078 FOREIGN KEY (profil_id) REFERENCES profil (id) ON UPDATE NO ACTION ON DELETE NO ACTION NOT DEFERRABLE INITIALLY IMMEDIATE)'); + $this->addSql('INSERT INTO post (id, profil_id, title, text, is_dream, up_vote, down_vote) SELECT id, profil_id, title, text, is_dream, up_vote, down_vote FROM __temp__post'); + $this->addSql('DROP TABLE __temp__post'); + $this->addSql('CREATE INDEX IDX_5A8A6C8D275ED078 ON post (profil_id)'); + } + + public function down(Schema $schema): void + { + // this down() migration is auto-generated, please modify it to your needs + $this->addSql('CREATE TEMPORARY TABLE __temp__post AS SELECT id, profil_id, title, text, is_dream, up_vote, down_vote FROM post'); + $this->addSql('DROP TABLE post'); + $this->addSql('CREATE TABLE post (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, profil_id INTEGER NOT NULL, title VARCHAR(255) DEFAULT NULL, text VARCHAR(512) DEFAULT NULL, is_dream BOOLEAN NOT NULL, up_vote INTEGER NOT NULL, down_vote INTEGER NOT NULL, CONSTRAINT FK_5A8A6C8D275ED078 FOREIGN KEY (profil_id) REFERENCES profil (id) NOT DEFERRABLE INITIALLY IMMEDIATE)'); + $this->addSql('INSERT INTO post (id, profil_id, title, text, is_dream, up_vote, down_vote) SELECT id, profil_id, title, text, is_dream, up_vote, down_vote FROM __temp__post'); + $this->addSql('DROP TABLE __temp__post'); + $this->addSql('CREATE INDEX IDX_5A8A6C8D275ED078 ON post (profil_id)'); + } +} diff --git a/src/Controller/.gitignore b/src/Controller/.gitignore deleted file mode 100644 index e69de29..0000000 diff --git a/src/Controller/PostController.php b/src/Controller/PostController.php index 241c67c..62d8d7a 100644 --- a/src/Controller/PostController.php +++ b/src/Controller/PostController.php @@ -7,27 +7,40 @@ use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Routing\Attribute\Route; use Doctrine\ORM\EntityManagerInterface; use App\Entity\Post; +use App\Entity\Profil; use App\Form\Type\PostType; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; -use Symfony\Component\Serializer\Serializer; -class PostController extends AbstractController { +class PostController extends AbstractController +{ private EntityManagerInterface $em; - private Serializer $serializer; - public function __construct(EntityManagerInterface $em, Serializer $serializer) + public function __construct(EntityManagerInterface $em) { $this->em = $em; - $this->serializer = $serializer; } - - #[Route('/post/{id}', name: 'display post', methods: ['POST'])] + + # DEBUG: Ne doit pas être laissé en production. + #[Route('/post/all', name: 'all post', methods: ['GET'])] + public function getAllPost(): Response + { + $posts = $this->em->getRepository(Post::class)->findAll(); + + return $this->render('post/all.html.twig', [ + "posts" => $posts + ]); + } + + #[Route('/post/{id}', + name: 'display post', + methods: ['GET'], + requirements: ['id' => '\d+'])] public function getPost(int $id): Response { $post = $this->em->getRepository(Post::class)->find($id); - if(!$post) { + if (!$post) { # Error 404 page } @@ -35,8 +48,8 @@ class PostController extends AbstractController { return new Response(); } - #[Route('/post/new/', name: 'add_post', methods: ['GET','POST'])] - public function addPost(Request $request) :Response + #[Route('/post/new/', name: 'add_post', methods: ['GET', 'POST'])] + public function addPost(Request $request): Response { $post = new Post(); @@ -47,20 +60,31 @@ class PostController extends AbstractController { if ($form->isSubmitted() && $form->isValid()) { $form = $form->getData(); + $user = $this->getUser(); + + $profil = new Profil(); + $profil->setId(11); + $profil->setName("coucou"); + + + $post->setProfil($user); + $this->em->persist($post); $this->em->flush(); + + return new Response($user->getUserIdentifier()); } return $this->render('post/new.html.twig', [ 'form' => $form, ]); - + # Handle error on data - + } #[Route('/post/{id}', name: 'remove_post', methods: ['DELETE'])] - public function removePost(int $id) :Response + public function removePost(int $id): Response { $postRef = $this->em->getReference('Post', $id); $this->em->remove($postRef); diff --git a/src/Controller/ProfilController.php b/src/Controller/ProfilController.php new file mode 100644 index 0000000..34d6be1 --- /dev/null +++ b/src/Controller/ProfilController.php @@ -0,0 +1,18 @@ +render('profil/index.html.twig', [ + 'controller_name' => 'ProfilController', + ]); + } +} diff --git a/src/Controller/RegistrationController.php b/src/Controller/RegistrationController.php new file mode 100644 index 0000000..2b47b0d --- /dev/null +++ b/src/Controller/RegistrationController.php @@ -0,0 +1,44 @@ +createForm(RegistrationFormType::class, $user); + $form->handleRequest($request); + + if ($form->isSubmitted() && $form->isValid()) { + $user->setName($form->get('name')->getData()); + + $hashedPassword = $userPasswordHasher->hashPassword( + $user, + $form->get('plainPassword')->getData() + ); + $user->setPassword($hashedPassword); + + $entityManager->persist($user); + $entityManager->flush(); + + + return $security->login($user, 'form_login', 'main'); + } + + return $this->render('registration/register.html.twig', [ + 'registrationForm' => $form, + ]); + } +} diff --git a/src/Controller/SecurityController.php b/src/Controller/SecurityController.php new file mode 100644 index 0000000..76bf5c4 --- /dev/null +++ b/src/Controller/SecurityController.php @@ -0,0 +1,32 @@ +getLastAuthenticationError(); + + // last username entered by the user + $lastUsername = $authenticationUtils->getLastUsername(); + + return $this->render('security/login.html.twig', [ + 'last_username' => $lastUsername, + 'error' => $error, + ]); + } + + #[Route(path: '/logout', name: 'app_logout')] + public function logout(): void + { + throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.'); + } +} diff --git a/src/Entity/Post.php b/src/Entity/Post.php index b709ed0..7d7a2db 100644 --- a/src/Entity/Post.php +++ b/src/Entity/Post.php @@ -24,11 +24,11 @@ class Post #[ORM\Column] private ?bool $isDream = null; - #[ORM\Column] - private ?int $upVote = null; + #[ORM\Column(options: ["default" => 0])] + private int $upVote = 0; - #[ORM\Column] - private ?int $downVote = null; + #[ORM\Column(options: ["default" => 0])] + private int $downVote = 0; #[ORM\ManyToOne(inversedBy: 'posts')] #[ORM\JoinColumn(nullable: false)] diff --git a/src/Entity/Profil.php b/src/Entity/Profil.php index 1aabf6d..a14065f 100644 --- a/src/Entity/Profil.php +++ b/src/Entity/Profil.php @@ -6,15 +6,21 @@ use App\Repository\ProfilRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; use Doctrine\ORM\Mapping as ORM; +use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; +use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; +use Symfony\Component\Security\Core\User\UserInterface; #[ORM\Entity(repositoryClass: ProfilRepository::class)] -class Profil +#[UniqueEntity(fields: ['name'], message: 'There is already an account with this name')] +class Profil implements UserInterface, PasswordAuthenticatedUserInterface { #[ORM\Id] #[ORM\GeneratedValue] #[ORM\Column] private ?int $id = null; + private array $roles = []; + #[ORM\Column(length: 255, nullable: true)] private ?string $name = null; @@ -54,6 +60,11 @@ class Profil return $this->id; } + public function setId(int $id): ?int + { + return $this->id = $id; + } + public function getName(): ?string { return $this->name; @@ -173,4 +184,30 @@ class Profil return $this; } + + public function getRoles(): array + { + $roles = $this->roles; + // guarantee every user at least has ROLE_USER + $roles[] = 'ROLE_USER'; + + return array_unique($roles); + } + + public function setRoles(array $roles): self + { + $this->roles = $roles; + + return $this; + } + + public function eraseCredentials(): void + { + // TODO: Implement eraseCredentials() method. + } + + public function getUserIdentifier(): string + { + return $this->name; + } } diff --git a/src/Form/RegistrationFormType.php b/src/Form/RegistrationFormType.php new file mode 100644 index 0000000..b121f26 --- /dev/null +++ b/src/Form/RegistrationFormType.php @@ -0,0 +1,55 @@ +add('name') + ->add('agreeTerms', CheckboxType::class, [ + 'mapped' => false, + 'constraints' => [ + new IsTrue([ + 'message' => 'You should agree to our terms.', + ]), + ], + ]) + ->add('plainPassword', PasswordType::class, [ + // instead of being set onto the object directly, + // this is read and encoded in the controller + 'mapped' => false, + 'attr' => ['autocomplete' => 'new-password'], + 'constraints' => [ + new NotBlank([ + 'message' => 'Please enter a password', + ]), + new Length([ + 'min' => 6, + 'minMessage' => 'Your password should be at least {{ limit }} characters', + // max length allowed by Symfony for security reasons + 'max' => 4096, + ]), + ], + ]) + ; + } + + public function configureOptions(OptionsResolver $resolver): void + { + $resolver->setDefaults([ + 'data_class' => Profil::class, + ]); + } +} diff --git a/src/Repository/TagsRepository.php b/src/Repository/TagsRepository.php index 01f3452..5116b48 100644 --- a/src/Repository/TagsRepository.php +++ b/src/Repository/TagsRepository.php @@ -9,7 +9,7 @@ use Doctrine\Persistence\ManagerRegistry; /** * @extends ServiceEntityRepository */ -class TagsRepository extends ServiceEntityRepository +class agsRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { diff --git a/templates/post/all.html.twig b/templates/post/all.html.twig new file mode 100644 index 0000000..13180f2 --- /dev/null +++ b/templates/post/all.html.twig @@ -0,0 +1,9 @@ +

All website posts

+ +{% for post in posts %} +
+ Id: {{ post.id }} + Title: {{ post.title }} + Content: {{ post.text }} +
+{% endfor %} diff --git a/templates/profil/index.html.twig b/templates/profil/index.html.twig new file mode 100644 index 0000000..e2c425e --- /dev/null +++ b/templates/profil/index.html.twig @@ -0,0 +1,20 @@ +{% extends 'base.html.twig' %} + +{% block title %}Hello ProfilController!{% endblock %} + +{% block body %} + + +
+

Hello {{ controller_name }}! ✅

+ + This friendly message is coming from: + +
+{% endblock %} diff --git a/templates/registration/register.html.twig b/templates/registration/register.html.twig new file mode 100644 index 0000000..c4218e0 --- /dev/null +++ b/templates/registration/register.html.twig @@ -0,0 +1,19 @@ +{% extends 'base.html.twig' %} + +{% block title %}Register{% endblock %} + +{% block body %} +

Register

+ + {{ form_errors(registrationForm) }} + + {{ form_start(registrationForm) }} + {{ form_row(registrationForm.name) }} + {{ form_row(registrationForm.plainPassword, { + label: 'Password' + }) }} + {{ form_row(registrationForm.agreeTerms) }} + + + {{ form_end(registrationForm) }} +{% endblock %} diff --git a/templates/security/login.html.twig b/templates/security/login.html.twig new file mode 100644 index 0000000..ca79723 --- /dev/null +++ b/templates/security/login.html.twig @@ -0,0 +1,42 @@ +{% extends 'base.html.twig' %} + +{% block title %}Log in!{% endblock %} + +{% block body %} +
+ {% if error %} +
{{ error.messageKey|trans(error.messageData, 'security') }}
+ {% endif %} + + {% if app.user %} +
+ You are logged in as {{ app.user.userIdentifier }}, Logout +
+ {% endif %} + +

Please sign in

+ + + + + + + + {# + Uncomment this section and add a remember_me option below your firewall to activate remember me functionality. + See https://symfony.com/doc/current/security/remember_me.html + +
+ +
+ #} + + +
+{% endblock %} diff --git a/var/data.db b/var/data.db index 6237051..380e83c 100644 Binary files a/var/data.db and b/var/data.db differ