<?php
declare(strict_types=1);
namespace Kobizo\Bundle\CoreBundle\Controller;
use Doctrine\ORM\EntityManagerInterface;
use Kobizo\Bundle\CoreBundle\Helper\SiteParamsHelper;
use Kobizo\Component\Attributes\DefaultRolesAttribute;
use Kobizo\Component\Configuration\Backend\AdminUrlConfig;
use Kobizo\Component\Configuration\MailTemplate\RegistrationEmailConfirmMailTemplateConfig;
use Kobizo\Component\Entity\User;
use Kobizo\Bundle\CoreBundle\Exception\NoRoleExistException;
use Kobizo\Bundle\CoreBundle\Form\RegistrationFormType;
use Kobizo\Component\Helper\TokenGeneratorInterface;
use Kobizo\Bundle\CoreBundle\Repository\RoleRepository;
use Kobizo\Bundle\CoreBundle\Repository\UserRepository;
use Kobizo\Bundle\CoreBundle\Security\LoginFormAuthenticator;
use Kobizo\Component\Provider\MailTemplateProvider;
use Kobizo\Component\Resources\AccessControl\DashboardResource;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Http\Authentication\UserAuthenticatorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Kobizo\Component\Configuration\Google\GoogleCaptchaConfig;
use Kobizo\Component\Configuration\Google\GoogleCaptchaPublicKeyConfig;
use Kobizo\Bundle\CoreBundle\Exception\LoginCaptchaValidationException;
use Kobizo\Component\Helper\GoogleReCaptchaV3Helper;
/**
* @Route("/registration")
*/
class FeRegistrationController extends KobizoFeAbstractController
{
/**
* @Route("/register", name="app_register")
*/
public function register(
Request $request,
UserPasswordHasherInterface $passwordHasher,
MailerInterface $mailer,
RoleRepository $roleRepository,
TokenGeneratorInterface $tokenGenerator,
SiteParamsHelper $siteParamsHelper,
EntityManagerInterface $entityManager,
TranslatorInterface $translator,
MailTemplateProvider $mailTemplateProvider,
RegistrationEmailConfirmMailTemplateConfig $registrationEmailConfirmTemplateConfig,
GoogleCaptchaConfig $googleCaptchaConfig,
GoogleCaptchaPublicKeyConfig $googleCaptchaPublicKeyConfig,
GoogleReCaptchaV3Helper $googleReCaptchaV3Helper
): Response {
//if user logged in then redirect to dashboard page
if ($this->isGranted(AuthenticatedVoter::IS_AUTHENTICATED_FULLY)) {
return $this->render('@KobizoCore/frontend/user-already-logged-in.twig');
}
$user = new User();
$form = $this->createForm(RegistrationFormType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// Execute google captcha validation if enabled
if ($googleCaptchaConfig->isGoogleCaptchaEnabled()) {
if (!$googleReCaptchaV3Helper->isValid($form->get('recaptcha_token')->getData())) {
throw new LoginCaptchaValidationException($translator->trans('Invalid or low score Login Captcha Checking.'));
}
}
// encode the plain password
$user->setPassword(
$passwordHasher->hashPassword(
$user,
$form->get('plainPassword')->getData()
)
);
$customerRole = $roleRepository->findOneByCode(DefaultRolesAttribute::CLIENT);
if (is_null($customerRole)) {
throw new NoRoleExistException();
}
$user->addRole($customerRole);
$user->setNicename($user->getNicename());
$user->setFirstname($user->getNicename());
$user->setLastname($user->getNicename());
$user->setDisplayName($user->getEmail());
$user->setConfirmationToken($tokenGenerator->generateConfirmationToken($user->getEmail()));
$entityManager->persist($user);
$entityManager->flush();
$url = $this->container->get('router')->generate(
'app_registration_confirm',
[
'confirmationToken' => $user->getConfirmationToken(),
],
UrlGeneratorInterface::NETWORK_PATH
);
$options = [
'confirmationUrl' => $url,
'siteName' => $siteParamsHelper->getSiteName(),
'siteUrl' => $siteParamsHelper->getSiteUrl(),
'address' => $siteParamsHelper->getSiteAddress(),
MailTemplateProvider::CODE => $registrationEmailConfirmTemplateConfig->getValue()
];
$email = (new TemplatedEmail())
->from(new Address($siteParamsHelper->getNoReplyEmail(), $siteParamsHelper->getSiteName()))
->to($user->getEmail())
->subject($translator->trans('Activate your account'))
->html($mailTemplateProvider->get($options));
$mailer->send($email);
return $this->render('@KobizoCore/frontend/register-email-sent.twig', [
'userConfirmForm' => $form->createView(),
'email' => $user->getEmail(),
]);
}
$googleCaptchaEnable = $googleCaptchaConfig->isGoogleCaptchaEnabled();
return $this->render('@KobizoCore/frontend/register.twig', [
'registrationForm' => $form->createView(),
'isGoogleCaptchaEnabled' => $googleCaptchaEnable,
'captchaPublicKey' => $googleCaptchaEnable ? $googleCaptchaPublicKeyConfig->getValue() : "",
]);
}
/**
* @Route("/confirm/{confirmationToken}", name="app_registration_confirm")
*/
public function confirmRegistration(
Request $request,
UserAuthenticatorInterface $userAuthenticator,
LoginFormAuthenticator $authenticator,
UserRepository $repository,
EntityManagerInterface $entityManager,
AdminUrlConfig $adminUrlConfig,
string $confirmationToken
) {
$user = $repository->findOneByConfirmationToken($confirmationToken);
if (null === $user) {
return $this->redirectToRoute('app_login', [], 302, true);
}
$user->setConfirmationToken(null);
$user->setActive(true);
$entityManager->persist($user);
$entityManager->flush();
$userAuthenticator->authenticateUser(
$user,
$authenticator,
$request,
);
if ($this->isGranted(DashboardResource::DASHBOARD_CRM) && $user->isAdmin()) {
return $this->redirectToRoute('dashboard_analytics', ['admin' => $adminUrlConfig->getValue()]);
}
if ($this->isGranted(DefaultRolesAttribute::CLIENT)) {
return $this->redirectToRoute('customer_account');
}
return $this->redirectToRoute('home');
}
}