<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Form\ResetFormType;
use App\Form\ResetPasswordFormType;
use App\Repository\UserRepository;
use App\Security\EmailVerifier;
use App\Security\AppFormAuthenticator;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mime\Address;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
use SymfonyCasts\Bundle\VerifyEmail\VerifyEmailHelperInterface;
class RegistrationController extends AbstractController
{
private $emailVerifier;
public function __construct(EmailVerifier $emailVerifier)
{
$this->emailVerifier = $emailVerifier;
}
/**
* @Route("/register", name="app_register")
*/
public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder, GuardAuthenticatorHandler $guardHandler, AppFormAuthenticator $authenticator): Response
{
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
)
);
// set username equal to email for now
$user->setUsername($user->getEmail());
$user->setEmailCanonical(mb_strtolower($user->getEmail()));
$user->setUsernameCanonical(mb_strtolower($user->getEmail()));
$entityManager = $this->getDoctrine()->getManager();
$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('noreply@getrealtrialtool.eu', 'GetReal Trial Tool'))
->to($user->getEmail())
->subject('Please Confirm your Email')
->htmlTemplate('registration/confirmation_email.html.twig')
);
// do anything else you need here, like send an email
// old code: log the user in
// return $guardHandler->authenticateUserAndHandleSuccess(
// $user,
// $request,
// $authenticator,
// 'main' // firewall name in security.yaml
// );
return $this->render('registration/check_mail.html.twig', [
]);
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
/**
* @Route("/resetting/request", name="app_password_reset_request")
*/
public function resetRequest(Request $request, UserRepository $userRepository, GuardAuthenticatorHandler $guardHandler, AppFormAuthenticator $authenticator): Response
{
$user = new User();
$form = $this->createForm(ResetFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// check if user exists
$resettingUser = $userRepository->findOneBy(['emailCanonical' => mb_strtolower($user->getEmail())]);
$this->emailVerifier->sendEmailConfirmation('app_password_reset', $resettingUser,
(new TemplatedEmail())
->from(new Address('noreply@getrealtrialtool.eu', 'GetReal Trial Tool'))
->to($user->getEmail())
->subject('Password reset request')
->htmlTemplate('registration/reset_password_email.html.twig')
);
return $this->render('registration/reset_password_request_done.html.twig', [
'registrationForm' => $form->createView(),
]);
}
return $this->render('registration/reset_password_request.html.twig', [
'registrationForm' => $form->createView(),
]);
}
/**
* @Route("/resetting/password", name="app_password_reset")
*/
public function resetPassword(Request $request, UserPasswordEncoderInterface $passwordEncoder,
GuardAuthenticatorHandler $guardHandler, AppFormAuthenticator $authenticator,
VerifyEmailHelperInterface $verifyEmailHelper,
UserRepository $userRepository, EntityManagerInterface $entityManager
): Response
{
$id = $request->get('id'); // retrieve the user id from the url
// Verify the user id exists and is not null
if (null === $id) {
$this->addFlash('verify_email_error', 'id missing');
return $this->redirectToRoute('app_password_reset_request');
}
$user = $userRepository->find($id);
// Ensure the user exists in persistence
if (null === $user) {
$this->addFlash('verify_email_error', 'user not found');
return $this->redirectToRoute('app_password_reset_request');
}
// validate email confirmation link, sets User::isVerified=true and persists
try {
$verifyEmailHelper->validateEmailConfirmation($request->getUri(), $user->getId(), $user->getEmail());
// update password
$userFormModel = new User();
$form = $this->createForm(ResetPasswordFormType::class, $userFormModel);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user->setPassword(
$passwordEncoder->encodePassword(
$user,
$form->get('plainPassword')->getData()
)
);
$entityManager->flush();
$this->addFlash('success', 'Your password has been updated.');
return $this->redirectToRoute('app_login');
}
return $this->render('registration/reset_password.html.twig', [
'registrationForm' => $form->createView(),
]);
} catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $exception->getReason());
return $this->redirectToRoute('app_register');
}
}
/**
* @Route("/verify/email", name="app_verify_email")
*/
public function verifyUserEmail(Request $request, UserRepository $userRepository): Response
{
// This is if you want to validated on a logged in session
// $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$id = $request->get('id'); // retrieve the user id from the url
// Verify the user id exists and is not null
if (null === $id) {
$this->addFlash('verify_email_error', 'id missing');
return $this->redirectToRoute('app_register');
}
$user = $userRepository->find($id);
// Ensure the user exists in persistence
if (null === $user) {
$this->addFlash('verify_email_error', 'user not found');
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', $exception->getReason());
return $this->redirectToRoute('app_register');
}
$this->addFlash('success', 'Your email address has been verified.');
return $this->redirectToRoute('app_login');
}
}