<?php
namespace App\Controller\Auth;
use App\Services\Api\Auth\AuthService;
use App\Services\TokenService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface;
use Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface;
class SecurityController extends AbstractController
{
private AuthService $authService;
protected TokenService $tokenService;
public function __construct(AuthService $authService, TokenService $tokenService)
{
$this->authService = $authService;
$this->tokenService = $tokenService;
}
/**
* @throws RedirectionExceptionInterface
* @throws ClientExceptionInterface
* @throws TransportExceptionInterface
* @throws ServerExceptionInterface
*/
#[Route('/login', name: 'app_login')]
public function login(Request $request, RequestStack $requestStack)
{
if ($request->isMethod('POST')) {
$session = $requestStack->getSession();
// Récupère les informations d'identification de l'utilisateur depuis le formulaire de connexion
$email = $request->request->get('email');
$password = $request->request->get('password');
//verification si les champ ne sont pas vide
if (!$email || !$password) {
$this->addFlash('danger', "le mot de passe ou l'adresse électronique n'est pas correct");
return $this->redirectToRoute('app_login');
}
$response = $this->authService->createAuthenticatedClient([
'email' => $email,
'password' => $password
]);
// dd($response->getContent());
if ($response->getStatusCode() == 200 || $response->getStatusCode() == 201) {
// Authentification réussie
// return $this->redirectToRoute('app_home');
} else {
// Authentification échouée
$this->addFlash("danger", json_decode($response->getContent(false), true)['message']);
return $this->redirectToRoute('app_login');
}
$data = json_decode($response->getContent(), true);
// Stocke le jeton d'authentification dans la session utilisateur
$this->tokenService->setToken($data['token']);
$user = $this->authService->getAllAboutMe();
$session->set('user', $user);
// Redirige l'utilisateur vers la page protégée
return $this->redirectToRoute('app_home');
}
return $this->render('frontend/security/login.html.twig', [
]);
}
#[Route('/logout', name: 'app_logout')]
public function logout()
{
$this->tokenService->empty();
if (!$this->tokenService->isTokenValid()) {
return $this->redirectToRoute('app_login');
}
}
}