<?php
namespace App\Controller;
use App\Entity\ForumUser;
use App\Entity\Profile;
use App\Entity\Society;
use App\Entity\User;
use App\Form\FreelanceRegisterFormType;
use App\Form\FreelanceRegisterMobileFormType;
use App\Form\RegistrationFormType;
use App\Form\ResetPasswordRequestFormType;
use App\Form\SocietyRegisterFormType;
use App\Security\AppAuthenticator;
use App\Security\EmailVerifier;
use App\Service\Forum\ForumUserService;
use App\Service\Upload\AvatarUploader;
use App\Service\Upload\PDFUploader;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use SymfonyCasts\Bundle\VerifyEmail\Exception\VerifyEmailExceptionInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormError;
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\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
class AuthController extends AbstractController
{
/**
* @var EmailVerifier
*/
private EmailVerifier $emailVerifier;
public function __construct(EmailVerifier $emailVerifier)
{
$this->emailVerifier = $emailVerifier;
}
public function register(
Request $request,
UserPasswordHasherInterface $userPasswordHasher,
EntityManagerInterface $entityManager,
UserAuthenticatorInterface $authenticator,
AppAuthenticator $formAuthenticator
): ?Response
{
if ($this->getUser()) {
$user = $this->getUser();
$route = $user->isAdmin() ? 'admin_dashboard' : 'homepage';
return $this->redirectToRoute($route);
}
$user = new User();
$user->setCreatedAt(new DateTime());
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$form['email']->addError(new FormError('Veuillez saisir un email valide'));
$user->setPassword($userPasswordHasher->hashPassword($user,
$form->get('plainPassword')->getData()
));
$role = $user->isFreelance() ? "ROLE_FREELANCE" : "ROLE_SOCIETY";
$user->setRoles(["ROLE_USER", $role]);
$entityManager->persist($user);
$entityManager->flush();
$this->sendConfirmation($user);
$this->addFlash('email_validation_send', true);
return $authenticator->authenticateUser($user, $formAuthenticator, $request);
}
return $this->render('auth/register.html.twig', ['registrationForm' => $form->createView()]);
}
/**
* @Route("/register-jobseeker", name="register_freelance")
* @param Request $request
* @param UserPasswordHasherInterface $userPasswordHasher
* @param EntityManagerInterface $entityManager
* @param UserAuthenticatorInterface $authenticator
* @param AppAuthenticator $formAuthenticator
* @param PDFUploader $pdfUploader
* @return Response|null
*/
public function registerFreelance(
Request $request,
UserPasswordHasherInterface $userPasswordHasher,
EntityManagerInterface $entityManager,
UserAuthenticatorInterface $authenticator,
AppAuthenticator $formAuthenticator,
PDFUploader $pdfUploader,
ForumUserService $forumUserService
): ?Response
{
$user = new User();
$user->setCreatedAt(new DateTime());
$user->setRoles(['ROLE_FREELANCE']);
$user->setType('freelance');
$user->setPhone('');
$form = $this->createForm(FreelanceRegisterFormType::class, $user, [
'forumPseudo' => $forumUserService->getNextForumUserID()
]);
$form->handleRequest($request);
$isErrorEmail = false;
if ($form->isSubmitted() && $form->isValid()) {
$user->setPassword($userPasswordHasher->hashPassword($user,
$form->get('plainPassword')->getData()
));
$user->setIsVerified(true);
// SET PROFILE
$profile = $user->getUniqueProfile();
$profile->setTitle($form->get('title')->getData());
$profile->setName($form->get('name')->getData());
$profile->setCivility($form->get('civility')->getData());
$profile->setFirstname($form->get('firstname')->getData());
$pdfFile = $form->get('cv_file')->getData();
if (isset($pdfFile) && is_object($pdfFile)) {
$pdfSavedFile = $pdfUploader->upload($pdfFile);
if ($pdfSavedFile) {
$profile->setCvname($pdfSavedFile['name']);
$profile->setCvFile($pdfSavedFile['path']);
}
}
$entityManager->persist($user);
$entityManager->persist($profile);
$entityManager->flush();
// SET PSEUDO
$userForum = new ForumUser();
$userForum->setAlias($form->get('forumPseudo')->getData());
$userForum->setUser($user);
$entityManager->persist($userForum);
$entityManager->flush();
$profile->updateSlug();
$entityManager->persist($profile);
$entityManager->flush();
try {
/*$this->sendConfirmation($user);
$this->addFlash('email_validation_send', true);*/
return $authenticator->authenticateUser($user, $formAuthenticator, $request);
} catch (Exception $e) {
return $authenticator->authenticateUser($user, $formAuthenticator, $request);
}
}
return $this->render('auth/register_freelance_new.html.twig', [
'form' => $form->createView(),
'is_error_mail' => $isErrorEmail
]);
}
/**
* @Route("/register-employer", name="register_society")
*/
public function registerSociety(
Request $request,
UserPasswordHasherInterface $userPasswordHasher,
EntityManagerInterface $entityManager,
UserAuthenticatorInterface $authenticator,
AppAuthenticator $formAuthenticator
): ?Response
{
$user = new User();
$form = $this->createForm(SocietyRegisterFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$user->setCreatedAt(new DateTime());
$user->setRoles(['ROLE_SOCIETY']);
$user->setType('society');
$user->setPassword($userPasswordHasher->hashPassword($user,
$form->get('plainPassword')->getData()
));
$society = new Society();
$society->setName($form->get('name')->getData());
$society->setCa(0);
$society->setAdress('');
$society->setVille('');
$society->setDescription('');
$society->setPhone($form->get('phone')->getData());
$user->setPhone($form->get('phone')->getData());
$society->setUser($user);
$entityManager->persist($user);
$entityManager->persist($society);
$entityManager->flush();
$society->updateSlug();
$entityManager->persist($society);
$entityManager->flush();
/* @changeLog 2022-11-03 [FIX] (Anthony) Mise en place d'une redirection après inscription compte entreprise */
$this->addFlash('success', 'Your company account has been successfully created.');
return $this->redirectToRoute('login');
}
return $this->render('auth/register_society_new.html.twig', [
'form' => $form->createView(),
]);
}
/**
* @Route("/verify/resend", name="resend_verification")
*/
public function resendVerificationEmail(Request $request): Response
{
$this->sendConfirmation($this->getUser());
return $this->redirectToRoute('dashboard');
}
private function sendConfirmation(UserInterface $user)
{
$this->emailVerifier->sendEmailConfirmation('verify_email', $user,
(new TemplatedEmail())
->to($user->getEmail())->subject('Verify your mail')
->htmlTemplate('emails/confirmation_email.html.twig')
);
}
/**
* @Route("/verify/email", name="verify_email")
*/
public function verifyUserEmail(Request $request): 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', $exception->getReason());
return $this->redirectToRoute('register_freelance');
}
// return $this->redirectToRoute('dashboard');
return $this->redirectToRoute('complete_resume_profile');
}
/**
* @Route("/login", name="login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
if ($this->getUser()) {
$user = $this->getUser();
$route = $user->isAdmin() ? 'admin_dashboard' : 'homepage';
return $this->redirectToRoute($route);
}
$resetForm = $this->createForm(ResetPasswordRequestFormType::class);
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('auth/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'resetForm' => $resetForm->createView(),
]);
}
/**
* @Route("/logout", name="logout")
*/
public function logout(): Response
{
return $this->redirectToRoute('homepage');
}
/**
* @Route("/register-jobseeker/mobile", name="register_freelance_mobile")
* @param Request $request
* @param UserPasswordHasherInterface $userPasswordHasher
* @param EntityManagerInterface $entityManager
* @param UserAuthenticatorInterface $authenticator
* @param AppAuthenticator $formAuthenticator
* @param PDFUploader $pdfUploader
* @return Response|null
*/
public function registerFreelanceMobile(
Request $request,
UserPasswordHasherInterface $userPasswordHasher,
EntityManagerInterface $entityManager,
UserAuthenticatorInterface $authenticator,
AppAuthenticator $formAuthenticator
): ?Response
{
$user = new User();
$user->setCreatedAt(new DateTime());
$user->setRoles(['ROLE_FREELANCE']);
$user->setType('freelance');
$user->setPhone('');
$form = $this->createForm(FreelanceRegisterMobileFormType::class, $user);
$form->handleRequest($request);
$isErrorEmail = false;
if ($form->isSubmitted() && $form->isValid()) {
$user->setPassword($userPasswordHasher->hashPassword($user,
$form->get('plainPassword')->getData()
));
$user->setIsVerified(true);
// SET PROFILE
$profile = $user->getUniqueProfile();
$profile->setTitle($form->get('title')->getData());
$profile->setName($form->get('name')->getData());
$profile->setCivility($form->get('civility')->getData());
$profile->setFirstname($form->get('firstname')->getData());
$profile->setPhone($form->get('phone')->getData());
$entityManager->persist($user);
$entityManager->persist($profile);
$entityManager->flush();
$profile->updateSlug();
$entityManager->persist($profile);
$entityManager->flush();
try {
/*$this->sendConfirmation($user);
$this->addFlash('email_validation_send', true);*/
return $authenticator->authenticateUser($user, $formAuthenticator, $request);
} catch (Exception $e) {
return $authenticator->authenticateUser($user, $formAuthenticator, $request);
}
}
return $this->render('auth/register_freelance_mobile.html.twig', [
'form' => $form->createView(),
'is_error_mail' => $isErrorEmail
]);
}
}