You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

168 lines
5.7 KiB
PHP

<?php
namespace App\Controller;
use App\Entity\User;
use App\Form\SignUpFormType;
use App\Repository\UserRepository;
use App\Security\EmailVerifier;
use Doctrine\ORM\EntityManagerInterface;
use LogicException;
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\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Contracts\Translation\TranslatorInterface;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
class UserController extends AbstractController {
/**
* @var EmailVerifier The email verifier service
*/
private readonly EmailVerifier $emailVerifier;
/**
* Initialisation
*
* @param EmailVerifier $emailVerifier The email verifier service
*/
public function __construct (EmailVerifier $emailVerifier) {
$this->emailVerifier = $emailVerifier;
}
/**
* Register a new user
*
* @param Request $request The query
* @param UserPasswordHasherInterface $userPasswordHasher The password hashing service
* @param EntityManagerInterface $entityManager The entity manager
*
* @return Response The response
*
* @throws TransportExceptionInterface
*/
#[Route('/signUp', name: 'user_signUp')]
public function signUp (Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager): Response {
$user = new User();
$form = $this->createForm(SignUpFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// encode the plain password
$user->setPassword(
$userPasswordHasher->hashPassword(
$user,
$form->get('newPassword')->getData()
)
);
$entityManager->persist($user);
$entityManager->flush();
// Generate the mail with the link to verify the account
$this->emailVerifier->sendEmailConfirmation(
'user_mailVerify',
$user,
(new TemplatedEmail())
->from(
new Address(
$this->getParameter('mailer.email'),
$this->getParameter('mailer.name')
)
)
->to($user->getEmail())
->subject('Please Confirm your Email')
->htmlTemplate('user/confirmation_email.html.twig')
);
$this->addFlash('info', 'Please validate your account through the confirmation mail');
return $this->redirectToRoute('core_main');
}
return $this->render('user/signUp.html.twig', [
'registrationForm' => $form,
]);
}
/**
* User email verification
*
* @param Request $request The request
* @param TranslatorInterface $translator The translation service
* @param UserRepository $userRepository The user repository
*
* @return Response
*/
#[Route('/emailVerify', name: 'user_mailVerify')]
public function verifyUserEmail (Request $request, TranslatorInterface $translator, UserRepository $userRepository): Response {
$id = $request->query->get('id');
if ($id === null) {
return $this->redirectToRoute('user_signUp');
}
$user = $userRepository->find($id);
if ($user === null) {
return $this->redirectToRoute('user_signUp');
}
try {
$this->emailVerifier->handleEmailConfirmation($request, $user);
}
catch (VerifyEmailExceptionInterface $exception) {
$this->addFlash('verify_email_error', $translator->trans($exception->getReason(), [], 'VerifyEmailBundle'));
return $this->redirectToRoute('user_signUp');
}
$this->addFlash('success', 'Your email address has been verified, now please wait for an administrator confirmation');
return $this->redirectToRoute('core_main');
}
/**
* Sign in a user
*
* @param AuthenticationUtils $authenticationUtils Security errors from query
*
* @return Response The response
*/
#[Route(path: '/signIn', name: 'user_signIn')]
public function login (AuthenticationUtils $authenticationUtils): Response {
/** @var User|null $user */
$user = $this->getUser();
if ($user !== null) {
$this->addFlash(
'warning',
'You are already logged in, please <a href="' . $this->generateUrl('user_signOut') . '">sign out</a> first.'
);
}
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'user/signIn.html.twig',
[
'last_username' => $lastUsername,
'error' => $error,
]
);
}
/**
* Sign out
*
* <b>NOTE :</b> dummy controller, intercepted by firewall
*
* @return void
*/
#[Route(path: '/signOut', name: 'user_signOut')]
public function logout (): void {
throw new LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}