<?php
namespace App\Controller\Front;
use Exception;
use Throwable;
use App\Adapter\AuthAdapter;
use App\Controller\PageController;
use App\Dto\Input\RegisterDTO;
use App\Exception\InvalidFieldAuthenticationException;
use App\Form\Registration\RegisterType;
use App\Service\AppointmentService;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
/**
* @Route("/connexion")
*/
class SecurityController extends PageController
{
use RequestRefererTrait;
/**
* @Route("/{rdv}", name="client_auth", options={"expose"=true}, defaults={"rdv"=""})
*
* @throws Exception
*/
public function auth(AuthenticationUtils $authenticationUtils, Request $request, AuthAdapter $adapter, ?string $rdv = null): Response
{
$this->_initDatas($request, 'connexion');
if ($this->getUser() && $this->isGranted('ROLE_CLIENT')) {
return $this->redirectToRoute('front_index_page');
}
$this->setReferer($request);
$dataLogin = $this->login($authenticationUtils);
$dataRegister = $this->register($request, $adapter);
if ($dataRegister instanceof RedirectResponse) {
return $dataRegister;
}
$data = [
'login' => $dataLogin,
'register' => $dataRegister,
];
$data['rdv'] = $rdv;
if ($rdv) {
$data['show'] = true;
}
return $this->render('security/front/auth.html.twig', $this->getDatas($data));
}
protected function login(AuthenticationUtils $authenticationUtils): array
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
$isValidField = true;
if ($error instanceof InvalidFieldAuthenticationException) {
$isValidField = false;
}
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return ['last_username' => $lastUsername,
'error' => $error,
'valid_field' => $isValidField];
}
/**
* @return array|RedirectResponse
*/
protected function register(Request $request, AuthAdapter $adapter)
{
$dto = new RegisterDTO();
$form = $this->createForm(RegisterType::class, $dto);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$dto->password = $form->get('password')->getData();
$session = $request->getSession();
try {
$adapter->register($dto);
$session->set('register_email', $dto->email);
$session->set('register_password', $dto->password);
if ($request->get('rdv') === AppointmentService::APPOINTMENT_SLUG) {
$session->set('rdv', true);
}
return $this->redirectToRoute('registration_check_code');
} catch (Throwable $exception) {
$this->addFlash(
'error',
$exception->getMessage()
);
}
}
return [
'registerForm' => $form->createView(),
];
}
}