<?php
namespace App\Controller;
use App\Event\User\UserLoginWithoutPasswordEvent;
use App\Repository\UserRepository;
use App\Service\NotificationService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Company;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Mime\Address;
// use Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="app_login")
*/
public function login(AuthenticationUtils $authenticationUtils, Request $request, SessionInterface $session,EntityManagerInterface $entityManager,UrlMatcherInterface $urlMatcherInterface): Response
{
$url = $request->getUri();
$pattern = "/^(https?:\/\/)?([a-zA-Z0-9.-]+)/";
preg_match($pattern, $url, $matches);
$sousDomaine = $matches[2];
$company = $entityManager->getRepository(Company::class)->findCompanyBySubDomain($sousDomaine);
if (null !== $request->query->get('redirect_to')) {
$session->set('redirect_to', $request->query->get('redirect_to'));
return $this->redirectToRoute('app_login');
}
if ($this->getUser()) {
if (null !== $redirect = $session->get('redirect_to')) {
$session->remove('redirect_to');
}
return $this->redirectToRoute('mission_index');
}
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
if (isset($_COOKIE['PHPSESSID'])) {
setcookie('PHPSESSID', '', time() - 14444444444444444, '/', '.my-flow.fr', true, true);
}
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error,
'company' => $company
]);
}
/**
* @Route("/login/request-login-without-password", name="request_login_without_password")
*/
public function createAuthWithoutPassword(Request $request,EventDispatcherInterface $dispatcher, EntityManagerInterface $entityManager, UserRepository $userRepository): Response | JsonResponse
{
if($request->isMethod('POST')){
$email = $request->request->get('email');
if($email == null) {
return $this->redirectToRoute('request_login_without_password',['message_login_without_password'=>'unknown-email']);
}
$user = $userRepository->findOneBy(['email'=>$email]);
if($user == null ) {
return $this->redirectToRoute('request_login_without_password',['message_login_without_password'=>'unknown-email']);
}
$token = hash('sha256', uniqid(preg_replace('/\s/','-',$user->getFullName())));
$user->setOneTimeLoginToken($token);
$entityManager->flush();
$event = new UserLoginWithoutPasswordEvent($user, $token);
$dispatcher->dispatch($event, UserLoginWithoutPasswordEvent::NAME);
return $this->redirectToRoute('app_login',['message_login_without_password'=>'send-success']);
}
return $this->render('security/login_without_password.html.twig', []);
}
/**
* @Route("/login/{token}", name="login-without-passWord")
*/
public function loginWithoutPassWord( HttpClientInterface $httpClient, ParameterBagInterface $parameterBag, string $token,TokenStorageInterface $tokenStorage, UserRepository $userRepository,EntityManagerInterface $entityManager,Request $request): Response
{
if ($request->query->get('role')) {
$request->getSession()->set('role_current_user', $request->query->get('role'));
}
$user = $userRepository->findOneBy(['oneTimeLoginToken' => $token]);
if($user){
if($user->isDeleted() or !$user->isEnabled()){
return $this->redirectToRoute('app_login',['message_login_without_password'=>'not-enabled']);
}
$authenticatedToken = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$tokenStorage->setToken($authenticatedToken);
// $user->setOneTimeLoginToken(null);
// $entityManager->flush();
if (in_array("ROLE_ADMIN", $user->getRoles()) || in_array("ROLE_SUBCONTRACTOR",$user->getRoles())) {
return $this->redirectToRoute('mission_index');
}
///////////////
$redirectToWp = in_array("ROLE_AUTHOR", $user->getRoles()) || in_array("ROLE_EDITOR", $user->getRoles()) ? true : false;
// $response = $httpClient->request('GET', $parameterBag->get('front_website_url'), [
// 'query' => [
// 'tsso' => hash('sha256', $user->getEmail() . $user->getEmail()),
// 'discount'=> 0
// ],
// 'max_redirects' => 0,
// ]);
// $headers = $response->getHeaders(false);
// foreach ($headers['set-cookie'] ?? [] as $cookie) {
// $infos = explode(';', $cookie);
// [$name, $value] = explode('=', $infos[0]);
// foreach ($infos as $info) {
// if (preg_match('#path#', $info)) {
// [$str, $path] = explode('=', $info);
// }
// }
// setrawcookie($name, $value, 0, $path ?? '', str_replace('https://', '', $parameterBag->get('front_website_url')));
// }
////////////
$ch = curl_init();
$url = "{$parameterBag->get('front_website_url')}/?tsso=" . hash('sha256', $user->getEmail() . $user->getEmail());
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
//set session if switch connection is active
if ($request->query->get('role')) {
$request->getSession()->set('role_current_user', $request->query->get('role'));
}
//end set session
return $redirectToWp ? $this->redirect("{$parameterBag->get('front_website_url')}/wp-admin") : $this->redirectToRoute('mission_index');
}
return $this->redirectToRoute('app_login',['message_login_without_password'=>'unknown-token']);
}
/**
* @Route("/logout", name="app_logout")
*/
public function logout(): void
{
// This method intentionally left blank.
}
}