This commit is contained in:
Romain 2024-11-23 15:05:14 +01:00
commit 8bc99d9492
14 changed files with 403 additions and 16 deletions

8
.idea/.gitignore vendored Normal file
View File

@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@ -1,21 +1,47 @@
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: 'plaintext' # à mettre en auto pour sécuriser les mdp
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider # https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
providers: providers:
# used to reload user from session & other features (e.g. switch_user) # used to reload user from session & other features (e.g. switch_user)
app_user_provider: app_intern_provider:
entity: entity:
class: App\Entity\User class: App\Entity\Intern
property: nickname property: nickname
app_employee_provider:
entity:
class: App\Entity\Employee
property: nickname
# used to reload user from session & other features (e.g. switch_user)
# used to reload user from session & other features (e.g. switch_user)
firewalls: firewalls:
dev: dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/ pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false security: false
main: intern:
lazy: true lazy: true
provider: app_user_provider provider: app_intern_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
employee:
lazy: true
provider: app_employee_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 # activate different ways to authenticate
# https://symfony.com/doc/current/security.html#the-firewall # https://symfony.com/doc/current/security.html#the-firewall

View File

@ -0,0 +1,31 @@
<?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 Version20241121153037 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
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('CREATE SCHEMA public');
}
}

View File

@ -0,0 +1,75 @@
<?php
namespace App\Controller;
use App\Entity\Employee;
use App\Entity\Intern;
use App\Entity\UserApp;
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;
#[Route('/register', name: 'app_register')]
class RegistrationController extends AbstractController
{
#[Route('/intern', name: '_intern')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, Security $security, EntityManagerInterface $entityManager): Response
{
$user = new Intern();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var string $plainPassword */
$plainPassword = $form->get('plainPassword')->getData();
$user->setRoles(['ROLE_INTERN']);
// encode the plain password
$user->setPassword($userPasswordHasher->hashPassword($user, $plainPassword));
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
return $security->login($user, 'form_login', 'intern');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form,
]);
}
#[Route('/employee', name: '_employee')]
public function registerEmployee(Request $request, UserPasswordHasherInterface $userPasswordHasher, Security $security, EntityManagerInterface $entityManager): Response
{
$user = new Employee();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/** @var string $plainPassword */
$plainPassword = $form->get('plainPassword')->getData();
$user->setRoles(['ROLE_EMPLOYEE']);
// encode the plain password
$user->setPassword($userPasswordHasher->hashPassword($user, $plainPassword));
$entityManager->persist($user);
$entityManager->flush();
// do anything else you need here, like send an email
return $security->login($user, 'form_login', 'employee');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form,
]);
}
}

View File

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

View File

@ -96,7 +96,7 @@ class Announcement
return $this->status; return $this->status;
} }
public function setStatus(?Status $status): static public function setStatus(?string $status): static
{ {
$this->status = $status; $this->status = $status;

View File

@ -9,7 +9,7 @@ use Doctrine\ORM\Mapping as ORM;
class Employee extends UserApp class Employee extends UserApp
{ {
#[ORM\ManyToOne(inversedBy: 'employees')] #[ORM\ManyToOne(inversedBy: 'employees')]
#[ORM\JoinColumn(nullable: false)] #[ORM\JoinColumn(nullable: true)]
private ?Company $company = null; private ?Company $company = null;
public function getCompany(): ?Company public function getCompany(): ?Company

View File

@ -12,10 +12,10 @@ use Doctrine\ORM\Mapping as ORM;
class Intern extends UserApp class Intern extends UserApp
{ {
#[ORM\Column(type: Types::TEXT)] #[ORM\Column(type: Types::TEXT,nullable: true)]
private ?string $coverLetter = null; private ?string $coverLetter = null;
#[ORM\Column(length: 255)] #[ORM\Column(length: 255,nullable: true)]
private ?string $resume = null; private ?string $resume = null;
/** /**

View File

@ -4,6 +4,7 @@ namespace App\Entity;
use App\Repository\UserRepository; use App\Repository\UserRepository;
use Doctrine\ORM\Mapping as ORM; 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\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserInterface;
@ -13,6 +14,7 @@ use Symfony\Component\Security\Core\User\UserInterface;
#[ORM\DiscriminatorColumn(name: 'DISCRIMINATOR', type: 'string')] #[ORM\DiscriminatorColumn(name: 'DISCRIMINATOR', type: 'string')]
#[ORM\DiscriminatorMap(['employee' => Employee::class, 'intern' => Intern::class])] #[ORM\DiscriminatorMap(['employee' => Employee::class, 'intern' => Intern::class])]
#[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_NICKNAME', fields: ['nickname'])] #[ORM\UniqueConstraint(name: 'UNIQ_IDENTIFIER_NICKNAME', fields: ['nickname'])]
#[UniqueEntity(fields: ['nickname'], message: 'Il y a déjà un compte avec ces identifiants !')]
class UserApp implements UserInterface, PasswordAuthenticatedUserInterface class UserApp implements UserInterface, PasswordAuthenticatedUserInterface
{ {
#[ORM\Id] #[ORM\Id]
@ -26,8 +28,8 @@ class UserApp implements UserInterface, PasswordAuthenticatedUserInterface
/** /**
* @var list<string> The user roles * @var list<string> The user roles
*/ */
#[ORM\Column(nullable: true)] #[ORM\Column]
private ?array $roles = null; private array $roles = [];
/** /**
* @var string The hashed password * @var string The hashed password
@ -35,21 +37,24 @@ class UserApp implements UserInterface, PasswordAuthenticatedUserInterface
#[ORM\Column] #[ORM\Column]
private ?string $password = null; private ?string $password = null;
#[ORM\Column(length: 255)] #[ORM\Column(length: 255, nullable: true)]
private ?string $firstName = null; private ?string $firstName = null;
#[ORM\Column(length: 255)] #[ORM\Column(length: 255, nullable: true)]
private ?string $lastName = null; private ?string $lastName = null;
#[ORM\Column(length: 255)] #[ORM\Column(length: 255,nullable: true)]
private ?string $tel = null; private ?string $tel = null;
#[ORM\Column(length: 255)] #[ORM\Column(length: 255,nullable: true)]
private ?string $address = null; private ?string $address = null;
#[ORM\Column(length: 255)] #[ORM\Column(length: 255,nullable: true)]
private ?string $mail = null; private ?string $mail = null;
#[ORM\Column(nullable: true)]
private bool $isVerified = false;
public function getId(): ?int public function getId(): ?int
{ {
return $this->id; return $this->id;
@ -184,6 +189,18 @@ class UserApp implements UserInterface, PasswordAuthenticatedUserInterface
return $this; return $this;
} }
public function isVerified(): bool
{
return $this->isVerified;
}
public function setVerified(bool $isVerified): static
{
$this->isVerified = $isVerified;
return $this;
}
} }

View File

@ -0,0 +1,81 @@
<?php
namespace App\Form;
use App\Entity\UserApp;
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\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
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('nickname', TextType::class, [
'label' => 'Utilisateur : ',
])
->add('firstname', TextType::class, [
'label' => 'Prénom : ',
'required' => true,
'constraints' => [
new NotBlank(),
]
])
->add('lastname', TextType::class, [
'label' => 'Nom : ',
'required' => true,
'constraints' => [
new NotBlank(),
]
])
->add('mail', EmailType::class, [
'label' => 'Email : ',
'required' => true,
'constraints' => [
new NotBlank(),
]
])
// ->add('agreeTerms', CheckboxType::class, [
// 'mapped' => false,
// 'constraints' => [
// new IsTrue([
// 'message' => 'Vous devez accepter les conditions d\'utilisation.',
// ]),
// ],
// ])
->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' => 'Merci d\'entrer votre mot de passe.',
]),
new Length([
'min' => 6,
'minMessage' => 'Votre mot de passe doit avoir au moins {{ limit }} caractères',
// max length allowed by Symfony for security reasons
'max' => 4096,
]),
],
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => UserApp::class,
]);
}
}

View File

@ -0,0 +1,52 @@
<?php
namespace App\Security;
use App\Entity\UserApp;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mailer\MailerInterface;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
use SymfonyCasts\Bundle\VerifyEmail\VerifyEmailHelperInterface;
class EmailVerifier
{
public function __construct(
private VerifyEmailHelperInterface $verifyEmailHelper,
private MailerInterface $mailer,
private EntityManagerInterface $entityManager
) {
}
public function sendEmailConfirmation(string $verifyEmailRouteName, UserApp $user, TemplatedEmail $email): void
{
$signatureComponents = $this->verifyEmailHelper->generateSignature(
$verifyEmailRouteName,
(string) $user->getId(),
(string) $user->getMail()
);
$context = $email->getContext();
$context['signedUrl'] = $signatureComponents->getSignedUrl();
$context['expiresAtMessageKey'] = $signatureComponents->getExpirationMessageKey();
$context['expiresAtMessageData'] = $signatureComponents->getExpirationMessageData();
$email->context($context);
$this->mailer->send($email);
}
/**
* @throws VerifyEmailExceptionInterface
*/
public function handleEmailConfirmation(Request $request, UserApp $user): void
{
$this->verifyEmailHelper->validateEmailConfirmationFromRequest($request, (string) $user->getId(), (string) $user->getMail());
$user->setVerified(true);
$this->entityManager->persist($user);
$this->entityManager->flush();
}
}

View File

@ -14,6 +14,8 @@
<h3> {{ ann.company.name }} </h3> <h3> {{ ann.company.name }} </h3>
<p> {{ ann.description }} </p> <p> {{ ann.description }} </p>
------------------------------ ------------------------------
<p> {{ ann.creationDate|format("") }} </p>
{% endfor %} {% endfor %}

View File

@ -0,0 +1,22 @@
{% extends 'base.html.twig' %}
{% block title %}Inscription{% endblock %}
{% block body %}
<h1>Inscription</h1>
{{ form_errors(registrationForm) }}
{{ form_start(registrationForm) }}
{{ form_row(registrationForm.nickname) }}
{{ form_row(registrationForm.firstname) }}
{{ form_row(registrationForm.lastname) }}
{{ form_row(registrationForm.mail) }}
{{ form_row(registrationForm.plainPassword, {
label: 'Password'
}) }}
{# {{ form_row(registrationForm.agreeTerms) }}#}
<button type="submit" class="btn">S'inscrire</button>
{{ form_end(registrationForm) }}
{% endblock %}

View File

@ -0,0 +1,41 @@
{% extends 'base.html.twig' %}
{% block title %}Connexion{% 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">Connexion à votre compte</h1>
<label for="username">Nom d'utilisateur</label>
<input type="text" value="{{ last_username }}" name="_username" id="username" class="form-control" autocomplete="username" required autofocus>
<label for="password">Mot de passe</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">
<input type="checkbox" name="_remember_me" id="_remember_me">
<label for="_remember_me">Remember me</label>
</div>
#}
<button class="btn btn-lg btn-primary" type="submit">
Connexion
</button>
</form>
{% endblock %}