security #11

Merged
aurian.jault merged 10 commits from security into master 10 months ago

@ -1,29 +1,29 @@
security: security:
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
password_hashers: password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto' Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider algorithm: bcrypt
cost: 13
providers: providers:
app_user_provider: app_user_provider:
entity: entity:
class: App\Entity\Profil class: App\Entity\Profil
property: name property: name
users_in_memory: { memory: null }
firewalls: firewalls:
dev: dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/ pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false security: false
main: main:
lazy: true lazy: true
provider: users_in_memory provider: app_user_provider
form_login: form_login:
login_path: app_login login_path: app_login
check_path: app_login check_path: app_login
enable_csrf: true enable_csrf: true
logout: logout:
path: app_logout path: app_logout
# where to redirect after logout target: /login
# target: app_any_route
# activate different ways to authenticate # activate different ways to authenticate
# https://symfony.com/doc/current/security.html#the-firewall # https://symfony.com/doc/current/security.html#the-firewall
@ -34,18 +34,13 @@ security:
# Easy way to control access for large sections of your site # Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used # Note: Only the *first* access control that matches will be used
access_control: access_control:
# - { path: ^/admin, roles: ROLE_ADMIN } #- { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
# - { path: ^/profile, roles: ROLE_USER } #- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
#- { path: ^/logout, role: ROLE_USER}
when@test: when@test:
security: security:
password_hashers: 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: Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface:
algorithm: auto algorithm: bcrypt
cost: 4 # Lowest possible value for bcrypt cost: 4 # Lowest possible value for bcrypt
time_cost: 3 # Lowest possible value for argon
memory_cost: 10 # Lowest possible value for argon

@ -11,6 +11,9 @@ services:
autowire: true # Automatically injects dependencies in your services. autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc. autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
Symfony\Component\Serializer\Serializer:
autowire: true
# makes classes in src/ available to be used as services # makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name # this creates a service per class whose id is the fully-qualified class name
App\: App\:

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

@ -0,0 +1,35 @@
<?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 Version20240612112105 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('ALTER TABLE profil ADD COLUMN roles CLOB DEFAULT NULL');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TEMPORARY TABLE __temp__profil AS SELECT id, name, description, password FROM profil');
$this->addSql('DROP TABLE profil');
$this->addSql('CREATE TABLE profil (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) DEFAULT NULL, description VARCHAR(255) DEFAULT NULL, password VARCHAR(255) DEFAULT NULL)');
$this->addSql('INSERT INTO profil (id, name, description, password) SELECT id, name, description, password FROM __temp__profil');
$this->addSql('DROP TABLE __temp__profil');
}
}

@ -0,0 +1,35 @@
<?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 Version20240612121601 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('ALTER TABLE profil ADD COLUMN roles CLOB DEFAULT NULL');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE TEMPORARY TABLE __temp__profil AS SELECT id, name, description, password FROM profil');
$this->addSql('DROP TABLE profil');
$this->addSql('CREATE TABLE profil (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name VARCHAR(255) DEFAULT NULL, description VARCHAR(255) DEFAULT NULL, password VARCHAR(255) DEFAULT NULL)');
$this->addSql('INSERT INTO profil (id, name, description, password) SELECT id, name, description, password FROM __temp__profil');
$this->addSql('DROP TABLE __temp__profil');
}
}

@ -0,0 +1,56 @@
:root {
font-family: "Helvetica", 'Courier New', Courier, monospace;
}
#post-wrapper {
width: 70%;
background-color: #f2f2f7;
margin: 0 auto;
border: 3px solid black;
border-radius: 1rem;
padding: 20px;
margin-top: 25vh;
}
#post-info {
display: flex;
flex-direction: row;
align-items: center;
gap: 10px;
}
h1 {
font-size: 3em;
}
p {
white-space: pre-wrap;
font-size: 1.2em;
}
#comments {
h2 {
font-size: 30px;
}
}
hr {
color: black;
}
html {
--s: 257px;
/* control the size */
--c1: #38476b;
--c2: #bda3b6;
--_c: var(--c1) calc(100% - var(--s)/2) 99%, #0000;
--_g: var(--s), #0000 calc(99% - var(--s)/2), var(--_c);
background:
radial-gradient(var(--s) at 100% var(--_g)),
radial-gradient(calc(var(--s)/4) at 50% calc(100%/3), var(--_c)) var(--s) 0,
radial-gradient(var(--s) at 0% var(--_g)) 0 calc(3*var(--s)) var(--c2);
background-size:
calc(2*var(--s)) calc(9*var(--s)/4),
calc(2*var(--s)) calc(3*var(--s)/4);
}

@ -0,0 +1,86 @@
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Post;
use App\Form\Type\PostType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
class PostController extends AbstractController
{
private EntityManagerInterface $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
# 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) {
}
return $this->render('post/post.html.twig', [
'post' => $post
]);
}
#[Route('/post/new/', name: 'add_post', methods: ['GET', 'POST'])]
public function addPost(Request $request): Response
{
$post = new Post();
$form = $this->createForm(PostType::class, $post);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$form = $form->getData();
$user = $this->getUser();
$post->setProfil($user);
$this->em->persist($post);
$this->em->flush();
return new Response($user->getUserIdentifier());
}
return $this->render('post/new.html.twig', [
'form' => $form,
]);
}
#[Route('/post/{id}', name: 'remove_post', methods: ['DELETE'])]
public function removePost(int $id): Response
{
$post = $this->em->getRepository(Post::class)->find($id);
$this->em->remove($post);
$this->em->flush();
return new Response();
}
}

@ -22,19 +22,17 @@ class RegistrationController extends AbstractController
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) { if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password $user->setName($form->get('name')->getData());
$user->setPassword(
$userPasswordHasher->hashPassword( $hashedPassword = $userPasswordHasher->hashPassword(
$user, $user,
$form->get('plainPassword')->getData() $form->get('plainPassword')->getData()
)
); );
$user->setRoles(['ROLE_USER']);
$user->setPassword($hashedPassword);
$entityManager->persist($user); $entityManager->persist($user);
$entityManager->flush(); $entityManager->flush();
// do anything else you need here, like send an email
return $security->login($user, 'form_login', 'main'); return $security->login($user, 'form_login', 'main');
} }

@ -24,11 +24,11 @@ class Post
#[ORM\Column] #[ORM\Column]
private ?bool $isDream = null; private ?bool $isDream = null;
#[ORM\Column] #[ORM\Column(options: ["default" => 0])]
private ?int $upVote = null; private int $upVote = 0;
#[ORM\Column] #[ORM\Column(options: ["default" => 0])]
private ?int $downVote = null; private int $downVote = 0;
#[ORM\ManyToOne(inversedBy: 'posts')] #[ORM\ManyToOne(inversedBy: 'posts')]
#[ORM\JoinColumn(nullable: false)] #[ORM\JoinColumn(nullable: false)]

@ -19,6 +19,7 @@ class Profil implements UserInterface, PasswordAuthenticatedUserInterface
#[ORM\Column] #[ORM\Column]
private ?int $id = null; private ?int $id = null;
#[ORM\Column(type: 'json', nullable: true)]
private array $roles = []; private array $roles = [];
#[ORM\Column(length: 255, nullable: true)] #[ORM\Column(length: 255, nullable: true)]
@ -60,6 +61,11 @@ class Profil implements UserInterface, PasswordAuthenticatedUserInterface
return $this->id; return $this->id;
} }
public function setId(int $id): ?int
{
return $this->id = $id;
}
public function getName(): ?string public function getName(): ?string
{ {
return $this->name; return $this->name;
@ -184,7 +190,7 @@ class Profil implements UserInterface, PasswordAuthenticatedUserInterface
{ {
$roles = $this->roles; $roles = $this->roles;
// guarantee every user at least has ROLE_USER // guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER'; // $roles[] = 'ROLE_USER';
return array_unique($roles); return array_unique($roles);
} }
@ -192,17 +198,16 @@ class Profil implements UserInterface, PasswordAuthenticatedUserInterface
public function setRoles(array $roles): self public function setRoles(array $roles): self
{ {
$this->roles = $roles; $this->roles = $roles;
return $this; return $this;
} }
public function eraseCredentials(): void public function getUserIdentifier(): string
{ {
// TODO: Implement eraseCredentials() method. return $this->name;
} }
public function getUserIdentifier(): string public function eraseCredentials(): void
{ {
return $this->name; // TODO: Implement eraseCredentials() method.
} }
} }

@ -2,14 +2,12 @@
namespace App\Entity; namespace App\Entity;
use ApiPlatform\Metadata\ApiResource;
use App\Repository\TagsRepository; use App\Repository\TagsRepository;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection; use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: TagsRepository::class)] #[ORM\Entity(repositoryClass: TagsRepository::class)]
#[ApiResource]
class Tags class Tags
{ {
#[ORM\Id] #[ORM\Id]

@ -0,0 +1,27 @@
<?php
namespace App\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
class PostType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add('title', TextType::class)
->add('text', TextareaType::class)
->add('dream', CheckboxType::class)
// ->add('tags', ChoiceType::class, [
// "multiple" => true
// ])
->add('submit', SubmitType::class)
;
}
}

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

@ -0,0 +1,25 @@
<link rel="stylesheet" href="{{ asset('css/components/post.css') }}">
<title>{{ post.title }}</title>
{% block body %}
<div id="post-wrapper">
<div id="post">
<div id="post-info">
<img src="https://api.dicebear.com/8.x/big-smile/svg?seed={{ post.profil.name }}" width="50px">
<span>{{ post.profil.name }}</span>
{# <span>- {{ post.dateCreated }}</span> #}
<span>- Il y a 3 jours</span>
</div>
<h1 id="post-title">{{ post.title }}</h1>
<p>{{ post.text }}</p>
</div>
<hr>
<div id="comments">
<h2>Comments</h2>
</div>
</div>
{% endblock %}

Binary file not shown.
Loading…
Cancel
Save