|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace PhpList\WebFrontend\Controller; |
| 6 | + |
| 7 | +use Exception; |
| 8 | +use GuzzleHttp\Exception\GuzzleException; |
| 9 | +use PhpList\WebFrontend\Service\ApiClient; |
| 10 | +use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; |
| 11 | +use Symfony\Component\HttpFoundation\Request; |
| 12 | +use Symfony\Component\HttpFoundation\RequestStack; |
| 13 | +use Symfony\Component\HttpFoundation\Response; |
| 14 | +use Symfony\Component\HttpFoundation\Session\SessionInterface; |
| 15 | +use Symfony\Component\Routing\Attribute\Route; |
| 16 | + |
| 17 | +class SecurityController extends AbstractController |
| 18 | +{ |
| 19 | + private ApiClient $apiClient; |
| 20 | + private SessionInterface $session; |
| 21 | + |
| 22 | + public function __construct(ApiClient $apiClient, RequestStack $requestStack) |
| 23 | + { |
| 24 | + $this->apiClient = $apiClient; |
| 25 | + $this->session = $requestStack->getSession(); |
| 26 | + } |
| 27 | + |
| 28 | + #[Route('', name: 'login', methods: ['GET', 'POST'])] |
| 29 | + public function login(Request $request): Response |
| 30 | + { |
| 31 | + if ($this->session->has('auth_token')) { |
| 32 | + return $this->redirectToRoute('dashboard'); |
| 33 | + } |
| 34 | + |
| 35 | + $error = null; |
| 36 | + |
| 37 | + if ($request->isMethod('POST')) { |
| 38 | + $username = $request->request->get('username'); |
| 39 | + $password = $request->request->get('password'); |
| 40 | + |
| 41 | + try { |
| 42 | + $authData = $this->apiClient->authenticate($username, $password); |
| 43 | + |
| 44 | + // Store token in session |
| 45 | + $this->session->set('auth_token', $authData['token']); |
| 46 | + |
| 47 | + // Store user data if needed |
| 48 | + if (isset($authData['user'])) { |
| 49 | + $this->session->set('user', $authData['user']); |
| 50 | + } |
| 51 | + |
| 52 | + // Set token for future API requests |
| 53 | + $this->apiClient->setAuthToken($authData['token']); |
| 54 | + |
| 55 | + // Redirect to dashboard |
| 56 | + return $this->redirectToRoute('dashboard'); |
| 57 | + } catch (Exception $e) { |
| 58 | + $error = 'Invalid credentials or server error: ' . $e->getMessage(); |
| 59 | + } catch (GuzzleException $e) { |
| 60 | + $error = 'Invalid credentials or server error: ' . $e->getMessage(); |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return $this->render('security/login.html.twig', [ |
| 65 | + 'error' => $error, |
| 66 | + ]); |
| 67 | + } |
| 68 | + |
| 69 | + #[Route('/logout', name: 'logout')] |
| 70 | + public function logout(): Response |
| 71 | + { |
| 72 | + // Clear session data |
| 73 | + $this->session->remove('auth_token'); |
| 74 | + $this->session->remove('user'); |
| 75 | + |
| 76 | + return $this->redirectToRoute('login'); |
| 77 | + } |
| 78 | +} |
0 commit comments