Form login, WIP
This commit is contained in:
parent
17fd3ef23a
commit
136dc8367e
2
.env
2
.env
@ -37,5 +37,5 @@ MESSENGER_TRANSPORT_DSN=doctrine://default?auto_setup=0
|
||||
###< symfony/messenger ###
|
||||
|
||||
###> symfony/mailer ###
|
||||
# MAILER_DSN=null://null
|
||||
MAILER_DSN=null://null
|
||||
###< symfony/mailer ###
|
||||
|
@ -42,6 +42,7 @@
|
||||
"symfony/validator": "7.1.*",
|
||||
"symfony/web-link": "7.1.*",
|
||||
"symfony/yaml": "7.1.*",
|
||||
"symfonycasts/verify-email-bundle": "^1.17",
|
||||
"twig/extra-bundle": "^2.12|^3.0",
|
||||
"twig/twig": "^2.12|^3.0"
|
||||
},
|
||||
|
48
composer.lock
generated
48
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": "6a957fcd0a6de48ba22ea99ed82f113f",
|
||||
"content-hash": "fa6b415ac11ece0fbfc562be9a5d1df3",
|
||||
"packages": [
|
||||
{
|
||||
"name": "composer/semver",
|
||||
@ -7342,6 +7342,52 @@
|
||||
],
|
||||
"time": "2024-08-12T09:59:40+00:00"
|
||||
},
|
||||
{
|
||||
"name": "symfonycasts/verify-email-bundle",
|
||||
"version": "v1.17.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/SymfonyCasts/verify-email-bundle.git",
|
||||
"reference": "f72af149070b39ef82a7095074378d0a98b4d2ef"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/SymfonyCasts/verify-email-bundle/zipball/f72af149070b39ef82a7095074378d0a98b4d2ef",
|
||||
"reference": "f72af149070b39ef82a7095074378d0a98b4d2ef",
|
||||
"shasum": ""
|
||||
},
|
||||
"require": {
|
||||
"ext-json": "*",
|
||||
"php": ">=8.1",
|
||||
"symfony/config": "^5.4 | ^6.0 | ^7.0",
|
||||
"symfony/dependency-injection": "^5.4 | ^6.0 | ^7.0",
|
||||
"symfony/deprecation-contracts": "^2.2 | ^3.0",
|
||||
"symfony/http-kernel": "^5.4 | ^6.0 | ^7.0",
|
||||
"symfony/routing": "^5.4 | ^6.0 | ^7.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"doctrine/orm": "^2.7",
|
||||
"doctrine/persistence": "^2.0",
|
||||
"symfony/framework-bundle": "^5.4 | ^6.0 | ^7.0",
|
||||
"symfony/phpunit-bridge": "^5.4 | ^6.0 | ^7.0"
|
||||
},
|
||||
"type": "symfony-bundle",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"SymfonyCasts\\Bundle\\VerifyEmail\\": "src/"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"description": "Simple, stylish Email Verification for Symfony",
|
||||
"support": {
|
||||
"issues": "https://github.com/SymfonyCasts/verify-email-bundle/issues",
|
||||
"source": "https://github.com/SymfonyCasts/verify-email-bundle/tree/v1.17.0"
|
||||
},
|
||||
"time": "2024-03-17T02:29:53+00:00"
|
||||
},
|
||||
{
|
||||
"name": "twig/extra-bundle",
|
||||
"version": "v3.13.0",
|
||||
|
@ -13,4 +13,5 @@ return [
|
||||
Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],
|
||||
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
|
||||
Symfony\Bundle\MakerBundle\MakerBundle::class => ['dev' => true],
|
||||
SymfonyCasts\Bundle\VerifyEmail\SymfonyCastsVerifyEmailBundle::class => ['all' => true],
|
||||
];
|
||||
|
@ -1,7 +1,7 @@
|
||||
security:
|
||||
# https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
|
||||
password_hashers:
|
||||
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
|
||||
Symfony\Component\Security\Core\Employee: 'auto'
|
||||
# https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
|
||||
providers:
|
||||
# used to reload user from session & other features (e.g. switch_user)
|
||||
@ -9,6 +9,7 @@ security:
|
||||
entity:
|
||||
class: App\Entity\Employee
|
||||
property: email
|
||||
# used to reload user from session & other features (e.g. switch_user)
|
||||
firewalls:
|
||||
dev:
|
||||
pattern: ^/(_(profiler|wdt)|css|images|js)/
|
||||
@ -16,6 +17,19 @@ security:
|
||||
main:
|
||||
lazy: true
|
||||
provider: app_user_provider
|
||||
custom_authenticator: App\Security\LoginFormAuthenticator
|
||||
logout:
|
||||
path: app_logout
|
||||
# where to redirect after logout
|
||||
# target: app_any_route
|
||||
|
||||
remember_me:
|
||||
secret: '%kernel.secret%'
|
||||
lifetime: 604800
|
||||
path: /
|
||||
# by default, the feature is enabled by checking a checkbox in the
|
||||
# login form, uncomment the following line to always enable it.
|
||||
#always_remember_me: true
|
||||
|
||||
# activate different ways to authenticate
|
||||
# https://symfony.com/doc/current/security.html#the-firewall
|
||||
@ -36,7 +50,7 @@ when@test:
|
||||
# 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\Employee\PasswordAuthenticatedUserInterface:
|
||||
algorithm: auto
|
||||
cost: 4 # Lowest possible value for bcrypt
|
||||
time_cost: 3 # Lowest possible value for argon
|
||||
|
49
migrations/Version20241017154551.php
Normal file
49
migrations/Version20241017154551.php
Normal file
@ -0,0 +1,49 @@
|
||||
<?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 Version20241017154551 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 SEQUENCE category_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE employee_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE incident_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE incident_type_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE mission_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE ride_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE skill_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE "user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE TABLE "user" (id INT NOT NULL, email VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_IDENTIFIER_EMAIL ON "user" (email)');
|
||||
}
|
||||
|
||||
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 category_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE employee_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE incident_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE incident_type_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE mission_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE ride_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE skill_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE "user_id_seq" CASCADE');
|
||||
$this->addSql('DROP TABLE "user"');
|
||||
}
|
||||
}
|
49
migrations/Version20241017154952.php
Normal file
49
migrations/Version20241017154952.php
Normal file
@ -0,0 +1,49 @@
|
||||
<?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 Version20241017154952 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 SEQUENCE category_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE employee_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE incident_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE incident_type_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE mission_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE ride_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE skill_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE "user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE TABLE "user" (id INT NOT NULL, email VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, is_verified BOOLEAN NOT NULL, PRIMARY KEY(id))');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_IDENTIFIER_EMAIL ON "user" (email)');
|
||||
}
|
||||
|
||||
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 category_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE employee_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE incident_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE incident_type_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE mission_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE ride_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE skill_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE "user_id_seq" CASCADE');
|
||||
$this->addSql('DROP TABLE "user"');
|
||||
}
|
||||
}
|
49
migrations/Version20241114142616.php
Normal file
49
migrations/Version20241114142616.php
Normal file
@ -0,0 +1,49 @@
|
||||
<?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 Version20241114142616 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 SEQUENCE category_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE employee_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE incident_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE incident_type_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE mission_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE ride_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE skill_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE SEQUENCE "user_id_seq" INCREMENT BY 1 MINVALUE 1 START 1');
|
||||
$this->addSql('CREATE TABLE "user" (id INT NOT NULL, email VARCHAR(180) NOT NULL, roles JSON NOT NULL, password VARCHAR(255) NOT NULL, is_verified BOOLEAN NOT NULL, PRIMARY KEY(id))');
|
||||
$this->addSql('CREATE UNIQUE INDEX UNIQ_IDENTIFIER_EMAIL ON "user" (email)');
|
||||
}
|
||||
|
||||
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 category_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE employee_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE incident_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE incident_type_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE mission_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE ride_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE skill_id_seq CASCADE');
|
||||
$this->addSql('DROP SEQUENCE "user_id_seq" CASCADE');
|
||||
$this->addSql('DROP TABLE "user"');
|
||||
}
|
||||
}
|
@ -5,13 +5,14 @@ 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;
|
||||
|
||||
#[Route('/dashboard', name: 'DashboardController')]
|
||||
class DashboardController extends AbstractController
|
||||
{
|
||||
#[Route('', name: '_index')]
|
||||
#[Route(path: '/dashboard', name: 'app_dashboard')]
|
||||
public function index(): Response
|
||||
{
|
||||
return $this->render('dashboard/index.html.twig');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
86
src/Controller/RegistrationController.php
Normal file
86
src/Controller/RegistrationController.php
Normal file
@ -0,0 +1,86 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Entity\Employee;
|
||||
use App\Form\RegistrationFormType;
|
||||
use App\Security\EmailVerifier;
|
||||
use App\Security\LoginFormAuthenticator;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Bundle\SecurityBundle\Security;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Mime\Address;
|
||||
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Contracts\Translation\TranslatorInterface;
|
||||
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
|
||||
|
||||
class RegistrationController extends AbstractController
|
||||
{
|
||||
public function __construct(private EmailVerifier $emailVerifier)
|
||||
{
|
||||
}
|
||||
|
||||
#[Route('/register', name: 'app_register')]
|
||||
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, Security $security, EntityManagerInterface $entityManager): Response
|
||||
{
|
||||
$employee = new Employee();
|
||||
$form = $this->createForm(RegistrationFormType::class, $employee);
|
||||
$form->handleRequest($request);
|
||||
|
||||
if ($form->isSubmitted() && $form->isValid()) {
|
||||
|
||||
|
||||
|
||||
// encode the plain password
|
||||
$employee->setPassword(
|
||||
password_hash($form->get('plainPassword')->getData(), PASSWORD_BCRYPT)
|
||||
);
|
||||
|
||||
$entityManager->persist($employee);
|
||||
$entityManager->flush();
|
||||
|
||||
// generate a signed url and email it to the employee
|
||||
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $employee,
|
||||
(new TemplatedEmail())
|
||||
->from(new Address('no-reply@HegreLand.com', 'Hegre Land'))
|
||||
->to((string) $employee->getEmail())
|
||||
->subject('Please Confirm your Email')
|
||||
->htmlTemplate('registration/confirmation_email.html.twig')
|
||||
);
|
||||
|
||||
// do anything else you need here, like send an email
|
||||
|
||||
return $security->login($employee, LoginFormAuthenticator::class, 'main');
|
||||
}
|
||||
|
||||
return $this->render('registration/register.html.twig', [
|
||||
'registrationForm' => $form,
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/verify/email', name: 'app_verify_email')]
|
||||
public function verifyUserEmail(Request $request, TranslatorInterface $translator): Response
|
||||
{
|
||||
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
|
||||
|
||||
// validate email confirmation link, sets User::isVerified=true and persists
|
||||
try {
|
||||
/** @var Employee $employee */
|
||||
$employee = $this->getUser();
|
||||
$this->emailVerifier->handleEmailConfirmation($request, $employee);
|
||||
} catch (VerifyEmailExceptionInterface $exception) {
|
||||
$this->addFlash('verify_email_error', $translator->trans($exception->getReason(), [], 'VerifyEmailBundle'));
|
||||
|
||||
return $this->redirectToRoute('DashboardController');
|
||||
}
|
||||
|
||||
// @TODO Change the redirect on success and handle or remove the flash message in your templates
|
||||
$this->addFlash('success', 'Your email address has been verified.');
|
||||
|
||||
return $this->redirectToRoute('app_register');
|
||||
}
|
||||
}
|
33
src/Controller/SecurityController.php
Normal file
33
src/Controller/SecurityController.php
Normal file
@ -0,0 +1,33 @@
|
||||
<?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
|
||||
{
|
||||
// if ($this->getUser()) {
|
||||
// return $this->redirectToRoute('target_path');
|
||||
// }
|
||||
|
||||
// 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.');
|
||||
}
|
||||
}
|
28
src/Form/LoginType.php
Normal file
28
src/Form/LoginType.php
Normal file
@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Form;
|
||||
use App\Entity\Employee;
|
||||
use Symfony\Component\Form\AbstractType;
|
||||
use Symfony\Component\Form\FormBuilderInterface;
|
||||
use Symfony\Component\OptionsResolver\OptionsResolver;
|
||||
use Symfony\Component\Form\Extension\Core\Type\TextType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\EmailType;
|
||||
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
|
||||
|
||||
class LoginType extends AbstractType
|
||||
{
|
||||
public function buildForm(FormBuilderInterface $builder, array $options): void
|
||||
{
|
||||
$builder
|
||||
->add('email', EmailType::class)
|
||||
->add('password', PasswordType::class)
|
||||
;
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
'data_class' => Employee::class,
|
||||
]);
|
||||
}
|
||||
}
|
64
src/Form/RegistrationFormType.php
Normal file
64
src/Form/RegistrationFormType.php
Normal file
@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Form;
|
||||
|
||||
use App\Entity\Employee;
|
||||
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\SubmitType;
|
||||
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('email', EmailType::class, ['label' => 'Email Address'])
|
||||
->add('firstName', TextType::class, ['label' => 'First Name'])
|
||||
->add('lastName', TextType::class, ['label' => 'Last Name'])
|
||||
->add('roles', ChoiceType::class, [
|
||||
'label' => 'Roles (comma-separated)',
|
||||
'required' => false,
|
||||
'choices' => [
|
||||
'User' => 'ROLE_USER',
|
||||
'Admin' => 'ROLE_ADMIN',
|
||||
],
|
||||
'multiple' => true, // Allow multiple selections
|
||||
'expanded' => true, // Render as checkboxes
|
||||
])
|
||||
->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,
|
||||
]),
|
||||
],
|
||||
])
|
||||
->add('save', SubmitType::class, ['label' => 'Add Employee'])
|
||||
;
|
||||
}
|
||||
|
||||
public function configureOptions(OptionsResolver $resolver): void
|
||||
{
|
||||
$resolver->setDefaults([
|
||||
'data_class' => Employee::class,
|
||||
]);
|
||||
}
|
||||
}
|
60
src/Repository/UserRepository.php
Normal file
60
src/Repository/UserRepository.php
Normal file
@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Repository;
|
||||
|
||||
use App\Entity\User;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
|
||||
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
|
||||
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
|
||||
|
||||
/**
|
||||
* @extends ServiceEntityRepository<User>
|
||||
*/
|
||||
class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface
|
||||
{
|
||||
public function __construct(ManagerRegistry $registry)
|
||||
{
|
||||
parent::__construct($registry, User::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Used to upgrade (rehash) the user's password automatically over time.
|
||||
*/
|
||||
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
|
||||
{
|
||||
if (!$user instanceof User) {
|
||||
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', $user::class));
|
||||
}
|
||||
|
||||
$user->setPassword($newHashedPassword);
|
||||
$this->getEntityManager()->persist($user);
|
||||
$this->getEntityManager()->flush();
|
||||
}
|
||||
|
||||
// /**
|
||||
// * @return User[] Returns an array of User objects
|
||||
// */
|
||||
// public function findByExampleField($value): array
|
||||
// {
|
||||
// return $this->createQueryBuilder('u')
|
||||
// ->andWhere('u.exampleField = :val')
|
||||
// ->setParameter('val', $value)
|
||||
// ->orderBy('u.id', 'ASC')
|
||||
// ->setMaxResults(10)
|
||||
// ->getQuery()
|
||||
// ->getResult()
|
||||
// ;
|
||||
// }
|
||||
|
||||
// public function findOneBySomeField($value): ?User
|
||||
// {
|
||||
// return $this->createQueryBuilder('u')
|
||||
// ->andWhere('u.exampleField = :val')
|
||||
// ->setParameter('val', $value)
|
||||
// ->getQuery()
|
||||
// ->getOneOrNullResult()
|
||||
// ;
|
||||
// }
|
||||
}
|
52
src/Security/EmailVerifier.php
Normal file
52
src/Security/EmailVerifier.php
Normal file
@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Security;
|
||||
|
||||
use App\Entity\Employee;
|
||||
use App\Entity\User;
|
||||
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, Employee $employee, TemplatedEmail $email): void
|
||||
{
|
||||
$signatureComponents = $this->verifyEmailHelper->generateSignature(
|
||||
$verifyEmailRouteName,
|
||||
(string) $employee->getId(),
|
||||
(string) $employee->getEmail()
|
||||
);
|
||||
|
||||
$context = $email->getContext();
|
||||
$context['signedUrl'] = $signatureComponents->getSignedUrl();
|
||||
$context['expiresAtMessageKey'] = $signatureComponents->getExpirationMessageKey();
|
||||
$context['expiresAtMessageData'] = $signatureComponents->getExpirationMessageData();
|
||||
|
||||
$email->context($context);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws VerifyEmailExceptionInterface
|
||||
*/
|
||||
public function handleEmailConfirmation(Request $request, Employee $employee): void
|
||||
{
|
||||
$this->verifyEmailHelper->validateEmailConfirmationFromRequest($request, (string) $employee->getId(), (string) $employee->getEmail());
|
||||
|
||||
$employee->setVerified(true);
|
||||
|
||||
$this->entityManager->persist($employee);
|
||||
$this->entityManager->flush();
|
||||
}
|
||||
}
|
60
src/Security/LoginFormAuthenticator.php
Normal file
60
src/Security/LoginFormAuthenticator.php
Normal file
@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Security;
|
||||
|
||||
use Symfony\Component\HttpFoundation\RedirectResponse;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
|
||||
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
|
||||
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\RememberMeBadge;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
|
||||
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
|
||||
use Symfony\Component\Security\Http\SecurityRequestAttributes;
|
||||
use Symfony\Component\Security\Http\Util\TargetPathTrait;
|
||||
|
||||
class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
|
||||
{
|
||||
use TargetPathTrait;
|
||||
|
||||
public const LOGIN_ROUTE = 'app_login';
|
||||
|
||||
public function __construct(private UrlGeneratorInterface $urlGenerator)
|
||||
{
|
||||
}
|
||||
|
||||
public function authenticate(Request $request): Passport
|
||||
{
|
||||
$email = $request->getPayload()->getString('email');
|
||||
|
||||
$request->getSession()->set(SecurityRequestAttributes::LAST_USERNAME, $email);
|
||||
|
||||
return new Passport(
|
||||
new UserBadge($email),
|
||||
new PasswordCredentials($request->getPayload()->getString('password')),
|
||||
[
|
||||
new CsrfTokenBadge('authenticate', $request->getPayload()->getString('_csrf_token')),
|
||||
new RememberMeBadge(),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
|
||||
{
|
||||
if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
|
||||
return new RedirectResponse($targetPath);
|
||||
}
|
||||
|
||||
// For example:
|
||||
return new RedirectResponse($this->urlGenerator->generate('app_dashboard'));
|
||||
//return new RedirectResponse($this->urlGenerator->generate('DashboardController'));
|
||||
}
|
||||
|
||||
protected function getLoginUrl(Request $request): string
|
||||
{
|
||||
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
|
||||
}
|
||||
}
|
@ -288,6 +288,9 @@
|
||||
"config/packages/messenger.yaml"
|
||||
]
|
||||
},
|
||||
"symfonycasts/verify-email-bundle": {
|
||||
"version": "v1.17.0"
|
||||
},
|
||||
"twig/extra-bundle": {
|
||||
"version": "v3.13.0"
|
||||
}
|
||||
|
11
templates/registration/confirmation_email.html.twig
Normal file
11
templates/registration/confirmation_email.html.twig
Normal file
@ -0,0 +1,11 @@
|
||||
<h1>Hi! Please confirm your email!</h1>
|
||||
|
||||
<p>
|
||||
Please confirm your email address by clicking the following link: <br><br>
|
||||
<a href="{{ signedUrl|raw }}">Confirm my Email</a>.
|
||||
This link will expire in {{ expiresAtMessageKey|trans(expiresAtMessageData, 'VerifyEmailBundle') }}.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Cheers!
|
||||
</p>
|
32
templates/registration/register.html.twig
Normal file
32
templates/registration/register.html.twig
Normal file
@ -0,0 +1,32 @@
|
||||
{% extends 'base.html.twig' %}
|
||||
|
||||
{% block title %}HegreLand{% endblock %}
|
||||
|
||||
{% block body %}
|
||||
{% for flash_error in app.flashes('verify_email_error') %}
|
||||
<div class="alert alert-danger" role="alert">{{ flash_error }}</div>
|
||||
{% endfor %}
|
||||
|
||||
<h1>M'inscrire</h1>
|
||||
|
||||
{{ form_errors(registrationForm) }}
|
||||
|
||||
{{ form_start(registrationForm) }}
|
||||
<div>
|
||||
{{ form_row(registrationForm.email) }}
|
||||
{{ form_row(registrationForm.firstName) }}
|
||||
{{ form_row(registrationForm.lastName) }}
|
||||
{{ form_row(registrationForm.roles) }}
|
||||
</div>
|
||||
<div>
|
||||
{{ form_row(registrationForm.plainPassword, {
|
||||
label: 'Password'
|
||||
}) }}
|
||||
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn">M'inscrire</button>
|
||||
<p>Déjà inscrit(e) ?<a href="{{ path('app_login') }}"> Me connecter</a> </p>
|
||||
|
||||
{{ form_end(registrationForm) }}
|
||||
{% endblock %}
|
26
templates/security/login.html.twig
Normal file
26
templates/security/login.html.twig
Normal file
@ -0,0 +1,26 @@
|
||||
{% extends 'base.html.twig' %}
|
||||
|
||||
{% block title %}HegreLand{% 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">
|
||||
Vous êtes déjà connecté(e) en tant que {{ app.user.userIdentifier }}, <a href="{{ path('app_logout') }}">Me déconnecter</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
|
||||
<h1 class="h3 mb-3 font-weight-normal">Me connecter</h1>
|
||||
{{ form_row(loginForm.email) }}
|
||||
<button class="btn btn-lg btn-primary" type="submit">
|
||||
Se connecter
|
||||
</button>
|
||||
<p><a href="#"> Mot de passe oublié</a> </p>
|
||||
<p>Pas encore inscrit(e) ?<a href="{{ path('app_register') }}"> M'inscrire</a> </p>
|
||||
</form>
|
||||
{% endblock %}
|
Loading…
Reference in New Issue
Block a user