<?php
namespace App\Controller;
use App\Entity\Ringer;
use App\Entity\User;
use App\Form\RegistrationFormType;
use App\Service\LoggerService;
use App\Security\EmailVerifier;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
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\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
class RegistrationController extends AbstractController
{
public function __construct(
private EmailVerifier $emailVerifier,
private LoggerService $logger
) {
}
/**
* @Route(
* {
* "es": "/{_locale}/register",
* "ca": "/{_locale}/register",
* "eu": "/{_locale}/register",
* },
* name="app_register",
* requirements={"_locale": "%app.supported_locales%"}
* )
*/
public function register(
Request $request,
UserPasswordHasherInterface $userPasswordHasher,
EntityManagerInterface $entityManager,
TranslatorInterface $translator
): Response {
if ($this->getUser()) {
return $this->redirectToRoute('app_actAs');
}
$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()
)
);
$user->setHashAux("");
try {
$entityManager->persist($user);
$entityManager->flush();
$this->logger->info('usuario registrado:', ['Name' => $user->getName()]);
} catch (Exception $e) {
dd($e);
}
$ringer = $entityManager->getRepository(Ringer::class)->findOneBy(['identityDocument' => $user->getDni()]);
if (isset($ringer)) {
$ringer->setUser($user);
$entityManager->persist($ringer);
$entityManager->flush();
}
$office = $entityManager->getRepository(User::class)->findOffice($user->getInstitution()->getId());
$sender_email = $this->getParameter('sender_email');
$subject = $translator->trans('email.ringer_platform_record');
if (isset($office[0])) {
$office = $office[0];
// generate a signed url and email it to the user
$this->emailVerifier->sendEmailConfirmation(
'app_verify_email',
$user,
(new TemplatedEmail())
->from(new Address(
$sender_email,
$translator->trans('login.platform')
))
->to($office->getEmail())
->subject($subject)
->htmlTemplate('registration/confirmation_email.html.twig')
->context([
'user' => $user,
])
);
}
// send the email
$this->emailVerifier->sendEmailConfirmation(
'app_verify_email',
$user,
(new TemplatedEmail())
->from(new Address(
$sender_email,
$translator->trans('login.platform')
))
->to($user->getEmail())
->subject($subject)
->htmlTemplate('registration/notify.html.twig')
->context([
'user' => $user,
])
);
return $this->redirectToRoute('app_waiting_verify');
}
return $this->render('registration/register.html.twig', [
'registrationForm' => $form->createView(),
]);
}
/**
* @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 {
$this->emailVerifier->handleEmailConfirmation($request, $this->getUser());
} 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.');
// ! TODO , verificar si el dd se ejecuta en algún sitio,
// ! creo que la variable $user no existe
// ! creo que este código no se ejecuta nunca
// dd("User verification", $request, $this->getUser());
// $this->logger->info('Usuario verificado', ['Id' => $user->getId()]);
$this->logger->info('Usuario verificado - method: verifyUserEmail', ['Id' => 'desconocido']);
return $this->redirectToRoute('app_register');
}
}