fix login error + postcontroller tests

pull/16/head
remrem 11 months ago
commit 0c142515c1

@ -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"

4
composer.lock generated

@ -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": "*"
},

@ -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

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20240611131531 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() 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 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)');
}
}

@ -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,8 +60,19 @@ 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', [
@ -60,7 +84,7 @@ class PostController extends AbstractController {
}
#[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);

@ -0,0 +1,18 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
class ProfilController extends AbstractController
{
#[Route('/profil', name: 'app_profil')]
public function index(): Response
{
return $this->render('profil/index.html.twig', [
'controller_name' => 'ProfilController',
]);
}
}

@ -0,0 +1,44 @@
<?php
namespace App\Controller;
use App\Entity\Profil;
use App\Form\RegistrationFormType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
class RegistrationController extends AbstractController
{
#[Route('/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, Security $security, EntityManagerInterface $entityManager): Response
{
$user = new Profil();
$form = $this->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,
]);
}
}

@ -0,0 +1,32 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')]
public function login(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
$error = $authenticationUtils->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.');
}
}

@ -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)]

@ -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;
}
}

@ -0,0 +1,55 @@
<?php
namespace App\Form;
use App\Entity\Profil;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class RegistrationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->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,
]);
}
}

@ -9,7 +9,7 @@ use Doctrine\Persistence\ManagerRegistry;
/**
* @extends ServiceEntityRepository<Tags>
*/
class TagsRepository extends ServiceEntityRepository
class agsRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{

@ -0,0 +1,9 @@
<h1>All website posts</h1>
{% for post in posts %}
<div>
<span>Id: {{ post.id }}</span>
<span>Title: {{ post.title }}</span>
<span>Content: {{ post.text }}</span>
</div>
{% endfor %}

@ -0,0 +1,20 @@
{% extends 'base.html.twig' %}
{% block title %}Hello ProfilController!{% endblock %}
{% block body %}
<style>
.example-wrapper { margin: 1em auto; max-width: 800px; width: 95%; font: 18px/1.5 sans-serif; }
.example-wrapper code { background: #F5F5F5; padding: 2px 6px; }
</style>
<div class="example-wrapper">
<h1>Hello {{ controller_name }}! ✅</h1>
This friendly message is coming from:
<ul>
<li>Your controller at <code>/home/aurian/3eme_annee/assassymfony/fukafukashita/src/Controller/ProfilController.php</code></li>
<li>Your template at <code>/home/aurian/3eme_annee/assassymfony/fukafukashita/templates/profil/index.html.twig</code></li>
</ul>
</div>
{% endblock %}

@ -0,0 +1,19 @@
{% extends 'base.html.twig' %}
{% block title %}Register{% endblock %}
{% block body %}
<h1>Register</h1>
{{ form_errors(registrationForm) }}
{{ form_start(registrationForm) }}
{{ form_row(registrationForm.name) }}
{{ form_row(registrationForm.plainPassword, {
label: 'Password'
}) }}
{{ form_row(registrationForm.agreeTerms) }}
<button type="submit" class="btn">Register</button>
{{ form_end(registrationForm) }}
{% endblock %}

@ -0,0 +1,42 @@
{% extends 'base.html.twig' %}
{% block title %}Log in!{% endblock %}
{% block body %}
<form method="post">
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
{% if app.user %}
<div class="mb-3">
You are logged in as {{ app.user.userIdentifier }}, <a href="{{ path('app_logout') }}">Logout</a>
</div>
{% endif %}
<h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
<label for="username">Name</label>
<input type="text" value="{{ last_username }}" name="_username" id="username" class="form-control" autocomplete="username" required autofocus>
<label for="password">Password</label>
<input type="password" name="_password" id="password" class="form-control" autocomplete="current-password" required>
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
{#
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
<div class="checkbox mb-3">
<label>
<input type="checkbox" name="_remember_me"> Remember me
</label>
</div>
#}
<button class="btn btn-lg btn-primary" type="submit">
Sign in
</button>
</form>
{% endblock %}

Binary file not shown.
Loading…
Cancel
Save