<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use League\HTMLToMarkdown\HtmlConverter;
use App\Form\compteType;
use App\Form\lostType;
use App\Form\ResetPasswordType;
use App\Services\iresaService;
use App\Services\SendinblueService;
use App\Entity\compte;
use App\Entity\Language;
/**
* @Route("/{_locale}", requirements={"_locale": "en|fr"})
*/
class RegisterController extends AbstractController
{
private $tokenStorage;
private $eventDispatcher;
private $router;
private $translator;
private $passwordEncoder;
private $mailer;
private $em;
private $iresaService;
private $sendinblueService;
public function __construct(RouterInterface $router, TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher, TranslatorInterface $translator, UserPasswordEncoderInterface $passwordEncoder, MailerInterface $mailer, EntityManagerInterface $em, iresaService $iresaService, SendinblueService $sendinblueService)
{
$this->tokenStorage = $tokenStorage;
$this->eventDispatcher = $eventDispatcher;
$this->router = $router;
$this->translator = $translator;
$this->passwordEncoder = $passwordEncoder;
$this->mailer = $mailer;
$this->em = $em;
$this->iresaService = $iresaService;
$this->sendinblueService = $sendinblueService;
}
/**
*
* @Route("/compte", name="compte")
*/
public function accountAction(Request $request)
{
$session = $request->getSession();
$locale = $request->getLocale();
$lang = $this->em->getRepository(Language::class)->findOneByCode($locale);
$compte = new compte();
$compte->setLang($lang);
$form = $this->createForm(compteType::class, $compte);
$resetPasswordFrom = $this->createForm(lostType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$compte->setRoles(['ROLE_CUSTOMER']);
$password = $this->passwordEncoder->encodePassword($compte, $compte->getPassword());
$compte->setPassword($password);
$this->em->persist($compte);
$obj->debug = ['User-agent' => $request->headers->get('User-Agent'), "script" => "RegisterController:accountAction:38"];
$createUserIresa = $this->iresaService->iresaXFT("Create", "Customer", $compte);
if($createUserIresa != null) {
$key = intval($createUserIresa->Customer->Codes->Code[0]["Value"]);
$compte->setKeyiresa($key);
}
$this->em->persist($compte);
$this->em->flush();
$session->getFlashBag()->add('success', ['type' => 'success', 'title' => "", 'message' => $this->translator->trans('compte.register.inscription.success', array(), 'app')]);
//return $this->redirectToRoute('compte');
$token = new UsernamePasswordToken($compte, $compte->getPassword(), 'main_front', $compte->getRoles());
$this->tokenStorage->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->eventDispatcher->dispatch($event, SecurityEvents::INTERACTIVE_LOGIN);
if($session->has('ReservationId') ) {
$path = $session->get('loginRedirectPath');
$session->remove('ReservationId');
$session->remove('loginRedirectPath');
$response = new RedirectResponse($this->router->generate($path));
return $response;
}
}
$route = $request->query->get('route_name');
$params = $request->query->get('params');
return $this->render('/front/Compte/register.html.twig',[
'form' => $form->createView(),
'lostform' => $resetPasswordFrom->createView(),
"route_name" => $route,
"params" => $params
]);
}
/**
*
* @Route("/compte/reset_password", name="account_lost_password")
*/
public function lostPasswordAction(Request $request)
{
$session = $request->getSession();
$resetPasswordFrom = $this->createForm(lostType::class);
$resetPasswordFrom->handleRequest($request);
if ($resetPasswordFrom->isSubmitted() && $resetPasswordFrom->isValid()) {
$email = $resetPasswordFrom->getData()['email'];
$user = $this->getDoctrine()->getRepository(compte::class)->findOneBy(['email' => $email]);
if ($user) {
$token = md5(time() . rand());
$em = $this->getDoctrine()->getManager();
$user->setResetPasswordToken($token);
$this->em->persist($user);
$this->em->flush();
$params = [
'name' => $user->getprenom(),
'email' => $user->getEmail(),
'token' => $token,
'subject' => $this->translator->trans('compte.register.inscription.reinitialisation.email.sujet', array(), 'app'),
'view' => 'reset_password'
];
// template #933 Brevo - réinitialisation du mot de passe
$ret = $this->sendMail($params, 933);
$title="";
$message = $this->translator->trans('compte.register.inscription.reinitialisation.flash', array(), 'app');
$session->getFlashBag()->add('success', ['type' => 'success', 'title' => $title, 'message' => $message]);
return $this->redirectToRoute('compte');
}
$message = $this->translator->trans('compte.register.inscription.erreur.utilisateur_inconnu', array(), 'app');
$session->getFlashBag()->add('error', ['type' => 'success', 'title' => "", 'message' => $message]);
}
$message = $this->translator->trans('compte.register.inscription.erreur.formulaire_non_valide', array(), 'app');
$session->getFlashBag()->add('error', ['type' => 'success', 'title' => "", 'message' => $message]);
return $this->redirectToRoute('compte');
}
/**
* @Route("/reinitialiserMotDePasse", name="reinitialiserMotDePasse")
*
*/
public function confirmPasswordAction(Request $request)
{
$session = $request->getSession();
$email = $request->query->get('email');
$requestToken = $request->query->get('token');
$user = $this->em->getRepository(compte::class)->findOneBy(['email' => $email]);
$form = $this->createForm(ResetPasswordType::class);
$form->handleRequest($request);
if (!$form->isSubmitted() ) {
$csrfToken = $user->getResetPasswordToken();
if ($csrfToken != $requestToken) {
$resetPasswordFrom = $this->createForm(lostType::class);
return $this->render('security/change_error.html.twig', [
'lostform' => $resetPasswordFrom->createView(),
]);
}
}
if ($form->isSubmitted() && $form->isValid()) {
$password = $this->passwordEncoder->encodePassword($user, $form->getData()['plainPassword']);
$user->setPassword($password);
$user->setResetPasswordToken(null);
$this->em->persist($user);
$this->em->flush();
$token = new UsernamePasswordToken($user, $user->getPassword(), 'main_front', $user->getRoles());
$this->tokenStorage->setToken($token);
$session->set('_security_main', serialize($token));
$title="";
$message="Password changed!";
$session->getFlashBag()->add('success', ['type' => 'success', 'title' => $title, 'message' => $message]);
$params = [
'name' => $user->getprenom(),
'email' => $user->getEmail(),
'token' => $requestToken,
'subject' => 'Mot de passe réinitialisé avec succès',
'view' => 'reset_password_confirmation'
];
$this->sendMail($params, 934);
return $this->redirectToRoute('ac_platform_homepage');
}
$array = ['form' => $form->createView(), 'email' => $email, 'token' => $csrfToken];
return $this->render('security/confirm_password.html.twig', $array);
}
private function sendMail($params, $templateId = null)
{
if($templateId == null) {
$content = $this->renderView('/front/Compte/' . $params['view'] . '.html.twig', $params);
// Convertir le contenu HTML en texte brut
$converter = new HtmlConverter();
$texte = $converter->convert($content);
$message = (new Email())
->from(new Address('noreply@ateya.fr', "Ateya-vacances"))
->to(new Address($params['email'], $params['name']))
->subject($params['subject'])
->text($texte)
->html((string)$content)
;
try {
$this->mailer->send($message);
} catch (TransportExceptionInterface $e) {
throw new NotificationErrorSendingException(sprintf('error sending for %s', $notification->getRecipient()->getEmail()));
}
} else {
$vars = [
"EMAIL" => $params['email'],
"TOKEN" => $params['token']
];
$this->sendinblueService->setTemplateId($templateId);
$this->sendinblueService->setRecipient($params['email'], $params['name']);
$this->sendinblueService->setParams($vars);
try {
$ret = $this->sendinblueService->sendEmail();
} catch (Exception $e) {
echo $e->getMessage();
}
}
return "EMAIL";
}
}