<?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Form\RequestPasswordType;
use AppBundle\Entity\Website;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
public function loginAction(Request $request, AuthenticationUtils $authenticationUtils)
{
$template = $this->renderProperTemplate($request, $authenticationUtils);
return $this->render($template[0], $template[1]);
}
public function loginCheckAction()
{
}
public function authenticateTokenAction(Request $request, EntityManagerInterface $em, $authenticationToken, $tuto = false)
{
$website = $em->getRepository(Website::class)->findOneByAuthenticationToken($authenticationToken);
if(!$website) {
throw $this->createNotFoundException("Cet utilisateur n'existe pas.");
}
$token = new UsernamePasswordToken($website, '', "website_secured_area", $website->getRoles());
$this->get("security.token_storage")->setToken($token);
$website->setAuthenticationToken(null);
$this->getDoctrine()->getManager()->persist($website);
$this->getDoctrine()->getManager()->flush();
//now dispatch the login event
// $event = new InteractiveLoginEvent($request, $token);
// $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
if($this->getParameter('current_website_by_domain') === true) {
if($tuto === "tuto") {
$url = $this->generateUrl('website_home_intro');
}
else {
$url = $this->generateUrl('website_home');
}
}
else {
if($tuto === "tuto") {
$url = $this->generateUrl('website_home_intro', ['website' => $website->getSlug()]);
}
else {
$url = $this->generateUrl('website_home', ['website' => $website->getSlug()]);
}
}
return $this->redirect($url);
}
/**
* Renders proper template
*
* @param Request $request
*
* @return array
*/
private function renderProperTemplate(Request $request, AuthenticationUtils $authenticationUtils)
{
$session = $request->getSession();
$route = $request->attributes->get('_route');
$routeTemplatesArray = ['admin_login' => 'Admin/login.html.twig', 'webmaster_login' => 'Website/login.html.twig'];
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
$form = null;
if($route == "webmaster_login") {
$form = $this->createForm(RequestPasswordType::class);
$form = $form->createView();
}
return [$routeTemplatesArray[$route], ['error' => $error, 'last_username' => $lastUsername, 'form' => $form]];
}
public function requestNewPasswordAction(Request $request, UserPasswordHasherInterface $encoder, MailerInterface $mailer)
{
$error = null;
$form = $this->createForm(RequestPasswordType::class);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$email = $form->get('email')->getData();
$websiteUser = $this->getDoctrine()->getRepository(Website::class)->findOneByEmail($email);
if(!$websiteUser) {
$error = "Aucun utilisateur n'existe avec cet email.";
}
else {
// generating new password and encoding it
$newPassword = substr(base_convert(uniqid('pass', true), 10, 36), 0, 5);
$encoded = $encoder->hashPassword($websiteUser, $newPassword);
$websiteUser->setPassword($encoded);
$em = $this->getDoctrine()->getManager();
$em->persist($websiteUser);
$em->flush();
$this->sendNewPasswordEmail($websiteUser, $newPassword, $mailer);
$this->addFlash('success', 'Votre mot de passe a bien été mis à jour, il vous a été envoyé par email');
return $this->redirectToRoute('homepage');
}
}
return $this->render('Security/requestNewPassword.html.twig', [
'form' => $form->createView(),
'error' => $error
]);
}
private function sendNewPasswordEmail(Website $website, $newPassword, MailerInterface $mailer)
{
$mailFrom = $this->getParameter('mail_from');
$email = (new Email())
->from($mailFrom)
->to($website->getEmail())
->subject('FFS - Les informations de connexion à l’administration de votre site')
->html($this->renderView('Mail/requestPassword.html.twig', ['newPassword' => $newPassword, 'website' => $website]));
$mailer->send($email);
}
public function switchUserAction($userId)
{
$this->get('session')->set('userid_to_switch', $userId);
return $this->redirectToRoute('user_switch');
}
public function switchAction(Request $request)
{
if ($this->get('session')->get('userid_to_switch'))
{
$user = $this->getDoctrine()->getEntityManager()->find(Website::class, $this->get('session')->get('userid_to_switch'));
if ($user)
{
$token = new UsernamePasswordToken($user, '', 'website_secured_area', $user->getRoles());
$this->get('security.token_storage')->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->get('event_dispatcher')->dispatch('security.interactive_login', $event);
if($this->getParameter('current_website_by_domain') === true) {
$url = $this->generateUrl('website_home');
}
else {
$url = $this->generateUrl('website_home', ['website' => $user->getSlug()]);
}
return $this->redirect($url);
}
}
return $this->redirectToRoute('sonata_admin_dashboard');
}
public function exitSwitchAction()
{
$this->get('session')->set('userid_to_switch', null);
$this->get('security.token_storage')->setToken(null);
return $this->redirectToRoute('sonata_admin_dashboard');
}
}