finished user prfile and passwords

This commit is contained in:
2022-11-01 14:57:36 +01:00
parent a488e489da
commit 560e96cf18
61 changed files with 1581 additions and 852 deletions

@ -0,0 +1,16 @@
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Entity\User;
abstract class BaseController extends AbstractController
{
protected function getUser(): User
{
return parent::getUser();
}
}

@ -10,27 +10,30 @@ use Exception;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\SerializerInterface;
/**
*
*/
class FrontendController extends AbstractController
{
const TEMPLATE_DIR = 'themes/default/';
#[Route(path: '/', name: 'app_main')]
public function quote(QuotesRepository $quotesRepository): Response
{
$user = $this->getUser();
$quote = $quotesRepository->findOneRandom();
return $this->render(view: '@default/base.html.twig', parameters: [
'user' => $user,
'quote' => json_encode(value: $quote->getQuote())
]);
}
/**
* @throws Exception
*/
#[Route(path: '/', name: 'app_main')]
public function quote(SerializerInterface $serializer, QuotesRepository $quotesRepository): Response
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): never
{
$quote = $quotesRepository->findOneRandom();
return $this->render(view: self::TEMPLATE_DIR . 'base.html.twig', parameters: [
'template_dir' => self::TEMPLATE_DIR,
'user' => $serializer->serialize(data: $this->getUser(), format: 'jsonld'),
'quote' => json_encode(value: $quote->getQuote())
]);
throw new Exception(message: 'Logout should never be reached.');
}
}

@ -10,8 +10,6 @@ use Symfony\Component\Routing\Annotation\Route;
class PagesController extends AbstractController
{
const TEMPLATE_DIR = 'themes/default/';
#[Route(path: '/pages/{name}', name: 'pages_display')]
public function display(PagesRepository $pagesRepository, string $name): Response
{
@ -25,7 +23,7 @@ class PagesController extends AbstractController
$page->setContent(content: 'The requested page was not found.');
}
return $this->render(view: 'pages/display.html.twig', parameters: [
return $this->render(view: '@default/pages/display.html.twig', parameters: [
'page' => $page,
]);
}
@ -33,18 +31,12 @@ class PagesController extends AbstractController
#[Route(path: '/imprint', name: 'app_imprint')]
public function imprint(): Response
{
return $this->render(view: self::TEMPLATE_DIR . 'pages/imprint.html.twig', parameters: [
'template_dir' => self::TEMPLATE_DIR,
'controller_name' => 'PagesController',
]);
return $this->render(view: '@default/pages/imprint.html.twig');
}
#[Route(path: '/privacy', name: 'app_privacy')]
public function privacy(): Response
{
return $this->render(view: self::TEMPLATE_DIR . 'pages/privacy.html.twig', parameters: [
'template_dir' => self::TEMPLATE_DIR,
'controller_name' => 'PagesController',
]);
return $this->render(view: '@default/pages/privacy.html.twig');
}
}

@ -13,7 +13,7 @@ class ProjectsController extends AbstractController
public function index(ProjectsRepository $projectsRepository, string $name = ''): Response
{
if ($name == '') {
return $this->render(view: 'projects/index.html.twig', parameters: [
return $this->render(view: '@default/projects/index.html.twig', parameters: [
'projects' => $projectsRepository->findAll(),
]);
} else {
@ -22,7 +22,7 @@ class ProjectsController extends AbstractController
// $parsedReadMe = $markdownParser->transformMarkdown(text: $readMe);
return $this->render(view: 'projects/show.html.twig', parameters: [
return $this->render(view: '@default/projects/show.html.twig', parameters: [
'project' => $project,
'readme' => $readMe,
]);

@ -0,0 +1,179 @@
<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\ChangePasswordFormType;
use App\Form\ResetPasswordRequestFormType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\ResetPassword\Controller\ResetPasswordControllerTrait;
use SymfonyCasts\Bundle\ResetPassword\Exception\ResetPasswordExceptionInterface;
use SymfonyCasts\Bundle\ResetPassword\ResetPasswordHelperInterface;
class ResetPasswordController extends AbstractController
{
use ResetPasswordControllerTrait;
public function __construct(
private readonly ResetPasswordHelperInterface $resetPasswordHelper,
private readonly EntityManagerInterface $entityManager
)
{
// empty body
}
/**
* Display & process form to request a password reset.
*/
#[Route(path: '/security/forgot/password', name: 'security_forgot_password')]
public function request(Request $request, MailerInterface $mailer): Response
{
$form = $this->createForm(type: ResetPasswordRequestFormType::class);
$form->handleRequest(request: $request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->processSendingPasswordResetEmail(
formData: $form->get(name: 'account')->getData(),
mailer: $mailer
);
}
return $this->render(view: '@default/security/forgot_password.html.twig', parameters: [
'requestForm' => $form->createView(),
]);
}
/**
* Confirmation page after a user has requested a password reset.
*/
#[Route(path: '/security/recovery/mail/sent', name: 'security_recovery_mail_sent')]
public function checkEmail(): Response
{
// Generate a fake token if the user does not exist or someone hit this page directly.
// This prevents exposing whether a user was found with the given email address or username or not
if (null === ($resetToken = $this->getTokenObjectFromSession())) {
$resetToken = $this->resetPasswordHelper->generateFakeResetToken();
}
return $this->render(view: '@default/security/recovery_mail_sent.html.twig', parameters: [
'resetToken' => $resetToken,
]);
}
/**
* Validates and process the reset URL that the user clicked in their email.
*/
#[Route(path: '/security/recovery/reset/{token}', name: 'security_recovery_reset')]
public function reset(Request $request, UserPasswordHasherInterface $passwordHasher, TranslatorInterface $translator, string $token = null): Response
{
if ($token) {
// We store the token in session and remove it from the URL, to avoid the URL being
// loaded in a browser and potentially leaking the token to 3rd party JavaScript.
$this->storeTokenInSession(token: $token);
return $this->redirectToRoute(route: 'security_recovery_reset');
}
$token = $this->getTokenFromSession();
if (null === $token) {
throw $this->createNotFoundException(message: 'No reset password token found in the URL or in the session.');
}
try {
$user = $this->resetPasswordHelper->validateTokenAndFetchUser(fullToken: $token);
} catch (ResetPasswordExceptionInterface $e) {
$this->addFlash(type: 'reset_password_error', message: sprintf(
'%s - %s',
$translator->trans(id: ResetPasswordExceptionInterface::MESSAGE_PROBLEM_VALIDATE, parameters: [], domain: 'ResetPasswordBundle'),
$translator->trans(id: $e->getReason(), parameters: [], domain: 'ResetPasswordBundle')
));
return $this->redirectToRoute(route: 'app_forgot_password_request');
}
// The token is valid; allow the user to change their password.
$form = $this->createForm(type: ChangePasswordFormType::class);
$form->handleRequest(request: $request);
if ($form->isSubmitted() && $form->isValid()) {
// A password reset token should be used only once, remove it.
$this->resetPasswordHelper->removeResetRequest(fullToken: $token);
// Encode(hash) the plain password, and set it.
$encodedPassword = $passwordHasher->hashPassword(
user: $user,
plainPassword: $form->get(name: 'plainPassword')->getData()
);
$user->setPassword($encodedPassword);
$this->entityManager->flush();
// The session is cleaned up after the password has been changed.
$this->cleanSessionAfterReset();
$this->addFlash(type: 'success', message: 'Your password has been changed.');
return $this->redirectToRoute(route: 'app_main');
}
return $this->render(view: '@default/security/reset_password.html.twig', parameters: [
'resetForm' => $form->createView(),
]);
}
private function processSendingPasswordResetEmail(string $formData, MailerInterface $mailer): RedirectResponse
{
$user = $this->entityManager->getRepository(entityName: User::class)->findOneBy(criteria: [
'email' => $formData,
]);
if (!$user) {
$user = $this->entityManager->getRepository(entityName: User::class)->findOneBy(criteria: [
'username' => $formData,
]);
}
// Do not reveal whether a user account was found or not.
// if (!$user) {
// return $this->redirectToRoute(route: 'app_check_email');
// }
try {
$resetToken = $this->resetPasswordHelper->generateResetToken(user: $user);
} catch (ResetPasswordExceptionInterface $e) {
$this->addFlash(type: 'reset_password_error', message: sprintf(
'%s - %s',
ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
$e->getReason()
));
return $this->redirectToRoute(route: 'security_forgot_password');
}
$email = (new TemplatedEmail())
->from(new Address(address: 'tracer@24unix.net', name: '24unix.net'))
->to($user->getEmail())
->subject(subject: 'Your password reset request')
->htmlTemplate(template: '@default/security/mail/recovery.html.twig')
->context(context: [
'resetToken' => $resetToken,
]);
$mailer->send(message: $email);
// Store the token object in session for retrieval in check-email route.
$this->setTokenObjectInSession(token: $resetToken);
return $this->redirectToRoute(route: 'security_recovery_mail_sent');
}
}

@ -2,46 +2,117 @@
namespace App\Controller;
use ApiPlatform\Core\Api\IriConverterInterface;
use App\Entity\User;
use App\Form\LoginFormType;
use App\Form\RegistrationFormType;
use App\Repository\UserRepository;
use App\Security\EmailVerifier;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Config\Definition\Exception\Exception;
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\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
/**
*
*/
class SecurityController extends AbstractController
{
#[Route(path: '/login', name: 'app_login')] // *** method post
public function login(AuthenticationUtils $authenticationUtils, IriConverterInterface $iriConverter): Response
{
/** @var User $user */
$user = $this->getUser() ?? null;
return new Response(content: null, status: 204, headers: [
'Location' => $iriConverter->getIriFromItem(item: $user)
]);
public function __construct(private readonly EmailVerifier $emailVerifier)
{
// empty body
}
/*
return $this->render(view: 'security/login.html.twig', parameters: [
'error' => $authenticationUtils->getLastAuthenticationError(),
'last_username' => $authenticationUtils->getLastUsername(),
#[Route(path: '/login', name: 'app_login')]
public function index(AuthenticationUtils $authenticationUtils): Response
{
// get the login error if there is one
if ($error = $authenticationUtils->getLastAuthenticationError()) {
$this->addFlash(type: 'error', message: $error->getMessageKey());
}
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(view: '@default/security/login.html.twig', parameters: [
'last_username' => $lastUsername,
'error' => '',
]);
*
}
/**
* @return mixed
*/
#[Route(path: '/logout', name: 'app_logout')]
public function logout(): never
#[Route(path: '/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
throw new Exception(message: 'Logout should never be reached.');
$form = $this->createForm(type: RegistrationFormType::class);
$form->handleRequest(request: $request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
// hash the plain password
$user->setPassword(
password: $userPasswordHasher->hashPassword(
user: $user,
plainPassword: $form->get(name: 'password')->getData()
)
);
if ($form->get(name: 'agreeTerms')->getData()) {
$user->agreeTerms();
} // no else, we already confirmed in the form itself
$entityManager->persist(entity: $user);
$entityManager->flush();
// generate a signed url and email it to the user
$this->emailVerifier->sendEmailConfirmation(verifyEmailRouteName: 'app_verify_email', user: $user,
email: (new TemplatedEmail())
->from(new Address(address: 'info@24unix.net', name: '24unix.net'))
->to($user->getEmail())
->subject(subject: 'Please Confirm your Email')
->htmlTemplate(template: '@default/security/mail/registration.html.twig')
->context(context: [
'username' => $user->getUsername()
])
);
return $this->render(view: '@default/security/registration_finished.html.twig');
}
return $this->render(view: '@default/security/register.html.twig', parameters: [
'registrationForm' => $form->createView(),
]);
}
#[Route(path: '/verify/email', name: 'app_verify_email')]
public function verifyUserEmail(Request $request, TranslatorInterface $translator, UserRepository $userRepository): Response
{
$id = $request->get(key: 'id');
if ($id === null) {
return $this->redirectToRoute(route: 'app_register');
}
$user = $userRepository->find($id);
if ($user === null) {
return $this->redirectToRoute(route: 'app_register');
}
// validate email confirmation link, sets User::isVerified=true and persists
try {
$this->emailVerifier->handleEmailConfirmation(request: $request, user: $user);
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash(type: 'verify_email_error', message: $translator->trans(id: $exception->getReason(), parameters: [], domain: 'VerifyEmailBundle'));
return $this->redirectToRoute(route: 'app_main');
}
$this->addFlash(type: 'success', message: 'Your email address has been verified.');
return $this->redirectToRoute(route: 'app_main');
}
}

@ -3,9 +3,13 @@
namespace App\Controller;
use App\Entity\User;
use App\Form\EditProfileFormType;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
@ -13,31 +17,56 @@ use Symfony\Component\Security\Core\Exception\UserNotFoundException;
/**
* Class UserController.
*/
class UserController extends AbstractController
class UserController extends BaseController
{
#[Route(path: '/profile/edit/{username}', name: 'app_profile_edit')]
public function editProfile(UserRepository $userRepository, string $username = ''): Response
public function editProfile(Request $request, UserRepository $userRepository, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, string $username = ''): Response
{
/* var User $user */
if ($username === '') {
if ($this->isGranted(attribute: 'ROLE_USER')) {
$user = $this->getUser();
} else {
throw new AccessDeniedException(message: 'You need to be logged in.');
}
} else {
if ($username !== '') {
if ($this->isGranted(attribute: 'ROLE_ADMIN')) {
$user = $userRepository->findOneBy([
'username' => $username,
]);
} else {
throw new AccessDeniedException(message: 'Only admins are allowed to edit Profiles.');
}
} else {
$user = $this->getUser();
}
$form = $this->createForm(type: EditProfileFormType::class, data: $user);
$form->handleRequest(request: $request);
if ($form->isSubmitted() && $form->isValid()) {
$user = $form->getData();
// if there's a new password, use it
if ($form->get(name: 'newPassword')->getData())
$user->setPassword(
password: $userPasswordHasher->hashPassword(
user: $user,
plainPassword: $form->get(name: 'newPassword')->getData()
)
);
$entityManager->persist(entity: $user);
$entityManager->flush();
return $this->redirectToRoute(route: 'app_main');
};
$user = $form->getData();
// hash the plain password
return $this->renderForm(view: '@default/user/edit_profile.html.twig', parameters: [
'user' => $user,
'userForm' => $form
]);
if (isset($user)) {
return $this->render(view: 'user/edit_profile.html.twig', parameters: [
'user' => $user,
]);
} else {
throw new UserNotFoundException();
}

@ -0,0 +1,39 @@
<?php
namespace App\Entity;
use App\Repository\ResetPasswordRequestRepository;
use Doctrine\ORM\Mapping as ORM;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestTrait;
#[ORM\Entity(repositoryClass: ResetPasswordRequestRepository::class)]
class ResetPasswordRequest implements ResetPasswordRequestInterface
{
use ResetPasswordRequestTrait;
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\ManyToOne]
#[ORM\JoinColumn(nullable: false)]
private ?User $user = null;
public function __construct(User $user, \DateTimeInterface $expiresAt, string $selector, string $hashedToken)
{
$this->user = $user;
$this->initialize(expiresAt: $expiresAt, selector: $selector, hashedToken: $hashedToken);
}
public function getId(): ?int
{
return $this->id;
}
public function getUser(): object
{
return $this->user;
}
}

@ -2,48 +2,40 @@
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiFilter;
use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\SearchFilter;
use App\Repository\UserRepository;
use DateTimeImmutable;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Stringable;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
/**
* => ["security" => "is_granted('ROLE_ADMIN') or object.owner == user"]
attributes : ['security' => 'is_granted("ROLE_USER")']
*/
#[ORM\Entity(repositoryClass: UserRepository::class), ORM\HasLifecycleCallbacks]
#[ApiResource(
collectionOperations: ['get', 'post'],
itemOperations : ['get'],
)]
#[ApiFilter(filterClass: SearchFilter::class, properties: ['username' => 'exact'])]
#[UniqueEntity(fields: ['username', 'email'], message: 'There is already an account with this username or email.')]
class User implements UserInterface, PasswordAuthenticatedUserInterface, \Stringable
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private int $id;
#[ORM\Column(type: 'string', length: 180, unique: true)]
#[ORM\Column(type: 'string', length: 180, unique: true, nullable: false)]
private string $username;
#[ORM\Column(type: 'json')]
private array $roles = [];
#[ORM\Column(type: 'string')]
#[ORM\Column(type: 'string', nullable: false)]
private string $password;
private string $plainPassword;
#[ORM\Column(type: 'string', length: 255)]
#[ORM\Column(type: 'string', length: 255, nullable: false)]
#[Assert\Email(
message: 'The eMail {{ value }} is not a valid eMail.'
)]
private string $email;
#[ORM\Column(type: 'string', length: 255, nullable: true)]
@ -67,15 +59,18 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface, \String
#[ORM\Column(type: 'datetime_immutable', nullable: true)]
private $modifiedAt;
#[ORM\Column(type: 'boolean')]
private $isVerified = false;
#[ORM\Column]
private ?DateTimeImmutable $agreedTermsAt = null;
public function __construct()
{
$this->projects = new ArrayCollection();
$this->pages = new ArrayCollection();
}
/**
* @return string|null
*/
public function __toString(): string
{
return $this->username;
@ -86,11 +81,6 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface, \String
return $this->id;
}
public function getPlainPassword(): string
{
return $this->plainPassword;
}
public function getUsername(): ?string
{
return $this->username;
@ -293,9 +283,9 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface, \String
* @return string
*/
public function getAvatarUri()
{
return 'avatar';
}
{
return 'avatar';
}
#[ORM\PrePersist]
public function onPrePersist(): void
@ -308,4 +298,28 @@ class User implements UserInterface, PasswordAuthenticatedUserInterface, \String
{
$this->modifiedAt = new DateTimeImmutable(datetime: 'now');
}
public function isVerified(): bool
{
return $this->isVerified;
}
public function setIsVerified(bool $isVerified): self
{
$this->isVerified = $isVerified;
return $this;
}
public function getAgreedTermsAt(): ?DateTimeImmutable
{
return $this->agreedTermsAt;
}
public function agreeTerms(): self
{
$this->agreedTermsAt = new DateTimeImmutable();
return $this;
}
}

@ -0,0 +1,54 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
class ChangePasswordFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add(child: 'plainPassword', type: RepeatedType::class, options: [
'type' => PasswordType::class,
'options' => [
'attr' => [
'autocomplete' => 'new-password',
],
],
'first_options' => [
'constraints' => [
new NotBlank(options: [
'message' => 'Please enter a password',
]),
new Length(exactly: [
'min' => 6,
'minMessage' => 'Your password should be at least {{ limit }} characters',
// max length allowed by Symfony for security reasons
'max' => 4096,
]),
],
'label' => 'New password',
],
'second_options' => [
'label' => 'Repeat Password',
],
'invalid_message' => 'The password fields must match.',
// Instead of being set onto the object directly,
// this is read and encoded in the controller
'mapped' => false,
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(defaults: []);
}
}

@ -0,0 +1,45 @@
<?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
class EditProfileFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add(child: 'username')
->add(child: 'firstName')
->add(child: 'lastName')
->add(child: 'email', type: EmailType::class)
->add(child: 'newPassword', type: RepeatedType::class, options: [
'type' => PasswordType::class,
'mapped' => false,
'invalid_message' => 'The password fields must match.',
'options' => ['attr' => ['class' => 'password-field', 'autocomplete' => 'off']],
'required' => false,
'first_options' => ['label' => 'Password'],
'second_options' => ['label' => 'Repeat Password (only needed if you want to update the password'],
'constraints' => [new Length(exactly: ['min' => 6])]
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(defaults: [
'data_class' => User::class,
'csrf_protection' => true,
'csrf_field_name' => '_csrf_token',
'csrf_token_id' => 'authenticate'
]);
}
}

@ -0,0 +1,49 @@
<?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\IsTrue;
use Symfony\Component\Validator\Constraints\Length;
class RegistrationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add(child: 'username')
->add(child: 'email', type: EmailType::class)
->add(child: 'password', type: RepeatedType::class, options: [
'type' => PasswordType::class,
'invalid_message' => 'The password fields must match.',
'options' => ['attr' => ['class' => 'password-field']],
'required' => true,
'first_options' => ['label' => 'Password'],
'second_options' => ['label' => 'Repeat Password'],
'constraints' => [new Length(exactly: ['min' => 6])]
])
->add(child: 'agreeTerms', type: CheckboxType::class, options: [
'mapped' => false,
'constraints' => [
new IsTrue(options: [
'message' => 'You should agree to our terms.',
]),
],
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(defaults: [
'data_class' => User::class,
]);
}
}

@ -0,0 +1,31 @@
<?php
namespace App\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\NotBlank;
class ResetPasswordRequestFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add(child: 'account', type: null, options: [
'mapped' => false,
'constraints' => [
new NotBlank(options: [
'message' => 'Please enter your email or username',
]),
],
])
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults(defaults: []);
}
}

@ -0,0 +1,51 @@
<?php
namespace App\Repository;
use App\Entity\ResetPasswordRequest;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use SymfonyCasts\Bundle\ResetPassword\Model\ResetPasswordRequestInterface;
use SymfonyCasts\Bundle\ResetPassword\Persistence\Repository\ResetPasswordRequestRepositoryTrait;
use SymfonyCasts\Bundle\ResetPassword\Persistence\ResetPasswordRequestRepositoryInterface;
/**
* @extends ServiceEntityRepository<ResetPasswordRequest>
*
* @method ResetPasswordRequest|null find($id, $lockMode = null, $lockVersion = null)
* @method ResetPasswordRequest|null findOneBy(array $criteria, array $orderBy = null)
* @method ResetPasswordRequest[] findAll()
* @method ResetPasswordRequest[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ResetPasswordRequestRepository extends ServiceEntityRepository implements ResetPasswordRequestRepositoryInterface
{
use ResetPasswordRequestRepositoryTrait;
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, ResetPasswordRequest::class);
}
public function save(ResetPasswordRequest $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(ResetPasswordRequest $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function createResetPasswordRequest(object $user, \DateTimeInterface $expiresAt, string $selector, string $hashedToken): ResetPasswordRequestInterface
{
return new ResetPasswordRequest($user, $expiresAt, $selector, $hashedToken);
}
}

@ -0,0 +1,54 @@
<?php
namespace App\Security;
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 Symfony\Component\Security\Core\User\UserInterface;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
use SymfonyCasts\Bundle\VerifyEmail\VerifyEmailHelperInterface;
class EmailVerifier
{
public function __construct(
private readonly VerifyEmailHelperInterface $verifyEmailHelper,
private readonly MailerInterface $mailer,
private readonly EntityManagerInterface $entityManager
) {
}
public function sendEmailConfirmation(string $verifyEmailRouteName, User /* UserInterface */ $user, TemplatedEmail $email): void
{
$signatureComponents = $this->verifyEmailHelper->generateSignature(
routeName: $verifyEmailRouteName,
userId: $user->getId(),
userEmail: $user->getEmail(),
extraParams: ['id' => $user->getId()]
);
$context = $email->getContext();
$context['signedUrl'] = $signatureComponents->getSignedUrl();
$context['expiresAtMessageKey'] = $signatureComponents->getExpirationMessageKey();
$context['expiresAtMessageData'] = $signatureComponents->getExpirationMessageData();
$email->context(context: $context);
$this->mailer->send(message: $email);
}
/**
* @throws VerifyEmailExceptionInterface
*/
public function handleEmailConfirmation(Request $request, User /*UserInterface*/ $user): void
{
$this->verifyEmailHelper->validateEmailConfirmation(signedUrl: $request->getUri(), userId: $user->getId(), userEmail: $user->getEmail());
$user->setIsVerified(isVerified: true);
$this->entityManager->persist(entity: $user);
$this->entityManager->flush();
}
}

@ -3,12 +3,17 @@
namespace App\Security;
use App\Entity\User;
use App\Form\LoginFormType;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
@ -16,7 +21,9 @@ 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\CustomCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
/**
@ -38,15 +45,13 @@ class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
$csrfToken = $request->request->get(key: '_csrf_token');
$request->getSession()->set(name: Security::LAST_USERNAME, value: $username);
dd("here");
return new Passport(
userBadge: new UserBadge(userIdentifier: $username, userLoader: function ($userIdentifier) {
$user = $this->userRepository->findOneBy(['username' => $userIdentifier]);
userBadge: new UserBadge(userIdentifier: $username, userLoader: function ($username) {
$user = $this->userRepository->findOneBy(['username' => $username]);
if (!$user) {
$user = $this->userRepository->findOneBy(['email' => $userIdentifier]);
$user = $this->userRepository->findOneBy(['email' => $username]);
}
if (!$user) {
@ -56,10 +61,7 @@ class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
return $user;
}),
// remove me later for PasswordCredentials()
credentials: new CustomCredentials(customCredentialsChecker: fn($credentials, User $user) => $credentials === 'test', credentials : $password),
// new PasswordCredentials($password),
credentials: new PasswordCredentials(password: $password),
badges: [
new CsrfTokenBadge(csrfTokenId: 'authenticate', csrfToken: $csrfToken),
new RememberMeBadge(),
@ -82,4 +84,5 @@ class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
{
return $this->router->generate(name: 'app_login');
}
}