I created a form and a user using make user and make registration-form. Here is my controller.
<?php
namespace AppController;
use AppEntityUser;
use AppFormRegistrationFormType;
use AppRepositoryUserRepository;
use AppSecurityEmailVerifier;
use DoctrineORMEntityManagerInterface;
use SymfonyBridgeTwigMimeTemplatedEmail;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentMimeAddress;
use SymfonyComponentPasswordHasherHasherUserPasswordHasherInterface;
use SymfonyComponentRoutingAttributeRoute;
use SymfonyContractsTranslationTranslatorInterface;
use SymfonyCastsBundleVerifyEmailExceptionVerifyEmailExceptionInterface;
class RegistrationController extends AbstractController
{
public function __construct(private EmailVerifier $emailVerifier)
{
}
#[Route('/register', name: 'app_register')]
public function register(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager->persist($user);
$entityManager->flush();
// generate a signed url and email it to the user
$this->emailVerifier->sendEmailConfirmation('app_verify_email', $user,
(new TemplatedEmail())
->from(new Address('web@****.ru', 'Test Test'))
->to($user->getEmail())
->subject('Подтверждение по Email')
->htmlTemplate('registration/confirmation_email.html.twig')
);
// do anything else you need here, like send an email
return $this->redirectToRoute('app_register');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form,
]);
}
#[Route('/verify/email', name: 'app_verify_email')]
public function verifyUserEmail(Request $request, TranslatorInterface $translator, UserRepository $userRepository): Response
{
$id = $request->query->get('id');
if (null === $id) {
return $this->redirectToRoute('app_register');
}
$user = $userRepository->find($id);
if (null === $user) {
return $this->redirectToRoute('app_register');
}
// validate email confirmation link, sets User::isVerified=true and persists
try {
$this->emailVerifier->handleEmailConfirmation($request, $user);
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $translator->trans($exception->getReason(), [], 'VerifyEmailBundle'));
return $this->redirectToRoute('app_register');
}
// @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');
}
}
My EmailVerifier
<?php
namespace AppSecurity;
use AppEntityUser;
use DoctrineORMEntityManagerInterface;
use SymfonyBridgeTwigMimeTemplatedEmail;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentMailerMailerInterface;
use SymfonyCastsBundleVerifyEmailExceptionVerifyEmailExceptionInterface;
use SymfonyCastsBundleVerifyEmailVerifyEmailHelperInterface;
class EmailVerifier
{
public function __construct(
private VerifyEmailHelperInterface $verifyEmailHelper,
private MailerInterface $mailer,
private EntityManagerInterface $entityManager
) {
}
public function sendEmailConfirmation(string $verifyEmailRouteName, User $user, TemplatedEmail $email): void
{
$signatureComponents = $this->verifyEmailHelper->generateSignature(
$verifyEmailRouteName,
(string) $user->getId(),
$user->getEmail(),
['id' => $user->getId()]
);
$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, User $user): void
{
$this->verifyEmailHelper->validateEmailConfirmationFromRequest($request, (string) $user->getId(), $user->getEmail());
$user->setVerified(true);
$this->entityManager->persist($user);
$this->entityManager->flush();
}
}
The email is sent, but when following the link
The link to verify your email is invalid. Please request a new link.
Symfony version 7. Development locally in Docker. Tried to output the parameters.
[2024-07-31T06:48:40.768182+00:00] app.ERROR: Email verification failed: The link to verify your email is invalid. Please request a new link. {“request_params”:{“expires”:”1722412100″,”id”:”5″,”signature”:”kyzxor2V5WImlWuE3lRyE2qiCDFFVI4hU4iQixjfK5o=”,”token”:”p1xjadDSxJyAff0OnkAg3lOSmWj7pmppNy4jgG5TcBc=”,”uri”:”/verify/email”},”expected_signature”:”http://localhost/verify/email?expires=1722412120&id=5&signature=csTPzpES61dQ2ZTyLJcVH1U%2Ft5VMLx%2F4i9b2x%2Fyf%2Bk8%3D&token=p1xjadDSxJyAff0OnkAg3lOSmWj7pmppNy4jgG5TcBc%3D”} []
The expires and signature values are different. What could be the issue? How can this be debugged?
output the parameters, I created verify_email.yaml with the following content symfonycasts_verify_email:
lifetime: 3600
Юра Горячев is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.