src/AppBundle/Controller/ui/LoginController.php line 39

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Controller\ui;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\HttpFoundation\Cookie;
  8. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
  11. use Psr\Log\LoggerInterface;
  12. use AppBundle\Service\HttpHelper;
  13. use AppBundle\Security\ApiKeyUserProvider;
  14. use AppBundle\CSPro\User\User;
  15. class LoginController extends AbstractController {
  16.     private $userName;
  17.     private $lastError;
  18.     private $lastErrorDetails;
  19.     public function __construct(private HttpHelper $client, private TokenStorageInterface $tokenStorage, private ApiKeyUserProvider $apikeyUserProvider, private LoggerInterface $logger) {
  20.         
  21.     }
  22.     #[Route('/', name: 'login', methods: ['GET'])]
  23.     public function login(): Response {
  24.         $configExists = file_exists(realpath(__DIR__ . '/../../config.php'));
  25.         if ($configExists === false) {
  26.             return new Response('This application needs to be configured. Please run <a href="/setup/index.php">setup</a>', Response::HTTP_FORBIDDEN);
  27.         }
  28.         return $this->render('login.twig', ['error' => $this->lastError, 'errorDetails' => $this->lastErrorDetails, 'last_username' => $this->userName]);
  29.     }
  30.     #[Route('/', name: 'login_check', methods: ['POST'])]
  31.     public function loginAction(Request $request): Response {
  32.         $this->userName = trim($_POST['_username']);
  33.         $password = trim($_POST['_password']);
  34.         $requestBody = json_encode(["client_id" => "cspro_android", "client_secret" => "cspro", "grant_type" => "password", "username" => $this->userName, "password" => $password], JSON_THROW_ON_ERROR);
  35.         $response = $this->client->request('POST', 'token', $requestBody, ['Content-Type' => 'application/json',
  36.             'Accept' => 'application/json']);
  37.         $this->logger->debug('login user "' . $this->userName . '" status=' . $response->getStatusCode());
  38.         $jsonResponse = json_decode($response->getBody(), true, 512, JSON_THROW_ON_ERROR);
  39.         //if the authentication failed.  redirect to the login page and set the lastError and the lastUserName 
  40.         if (isset($jsonResponse['error_description'])) {
  41.             $this->lastError = $jsonResponse['error_description'];
  42.             $this->logger->warning('Login failed:' . $this->lastError);
  43.             return $this->login();
  44.         } else if ($response->getStatusCode() == 401 && isset($jsonResponse['message'])) {
  45.             $this->lastError = $jsonResponse['message'];
  46.             $this->logger->warning('Login failed:' . $this->lastError);
  47.             return $this->login();
  48.         } else if ($response->getStatusCode() == 200 && isset($jsonResponse['access_token'])) {
  49.             $apiKey = $jsonResponse['access_token'];
  50.             $user = $this->apikeyUserProvider->loadUserByApiKey($apiKey);
  51.             $roles = $user->getRoles();
  52.             $providerKey = 'cspro_oauth_provider';
  53.             /*  $tokenStorage = new PreAuthenticatedToken(
  54.               $user, $apiKey, $providerKey, $roles
  55.               ); */ //deprecation https://github.com/symfony/symfony/issues/44396
  56.             $tokenStorage = new PreAuthenticatedToken(
  57.                     $user, $providerKey, $roles
  58.             );
  59.             //set tokenstorage for authorization
  60.             $this->tokenStorage->setToken($tokenStorage);
  61.             if (!$this->canUserLogin($user)) {
  62.                 return $this->login(); //redirect ??
  63.             }
  64.             //check if the access_token in available and then set the cookie 
  65.             //if it succeeds redirect to the targetpath with the cookie set correctly with the token.
  66.             $targetPath = $this->getLandingPage();
  67.             $response = $this->redirect($targetPath);
  68.             $response->headers->setCookie(new Cookie("access_token", $jsonResponse['access_token']));
  69.             $response->headers->setCookie(new Cookie("username", $this->userName));
  70.             return $response;
  71.         } else {
  72.             $this->logger->error('Failed to contact API:' . $response->getBody());
  73.             $this->lastError = 'Failed to contact authentication server. Please contact your site administrator.';
  74.             $this->lastErrorDetails = "Error code: {$response->getStatusCode()}. Message: {$response->getBody()}";
  75.             return $this->login(); //redirect ??
  76.         }
  77.     }
  78.     public function canUserLogin($user) {
  79.         //check is granted for the user
  80.         $hasLoginAccess = $this->isGranted('ROLE_USERS_ALL') || $this->isGranted('ROLE_DATA_ALL') ||
  81.                 $this->isGranted('ROLE_REPORTS_ALL') || $this->isGranted('ROLE_APPS_ALL') || $this->isGranted('ROLE_ROLES_ALL') || $this->isGranted('ROLE_SETTINGS_ALL');
  82.         if (empty($user)) {
  83.             $this->logger->warning('Login failed. User not found.');
  84.             $this->lastError = 'Login failed. Unable to retrieve user information';
  85.         } elseif ($user->getRoleId() == User::STANDARD_USER) {
  86.             $this->logger->warning('Login failed. User is standard user.');
  87.             $this->lastError = 'Login failed. Insufficient privileges.';
  88.         } elseif ($hasLoginAccess || $user->getRoleId() == User::ADMINISTRATOR) {//built-in administrator
  89.             return true;
  90.         } else { //any other user
  91.             $this->logger->warning('Login failed. User does not have login access. Role=' . $user->getRoleId());
  92.             $this->lastError = 'Login failed. Insufficient privileges.';
  93.         }
  94.         return false;
  95.     }
  96.     #[Route('/logout', name: 'logout', methods: ['GET'])]
  97.     public function logoutAction(): Response {
  98.         $this->lastError = "";
  99.         $this->lastErrorDetails = "";
  100.         $this->userName = "";
  101.         $response = $this->redirectToRoute('login');
  102.         $response->headers->clearCookie('access_token');
  103.         $response->headers->clearCookie('username');
  104.         return $response;
  105.     }
  106.     public function getLandingPage() {
  107.         $targetPath = '';
  108.         if ($this->isGranted('ROLE_DATA_ALL')) {
  109.             $targetPath = 'dashboard';
  110.         } elseif ($this->isGranted('ROLE_REPORTS_ALL')) {
  111.             $targetPath = 'sync-report';
  112.         } elseif ($this->isGranted('ROLE_APPS_ALL')) {
  113.             $targetPath = 'apps';
  114.         } elseif ($this->isGranted('ROLE_USERS_ALL')) {
  115.             $targetPath = 'users';
  116.         } elseif ($this->isGranted('ROLE_ROLES_ALL')) {
  117.             $targetPath = 'roles';
  118.         }
  119.         return $targetPath;
  120.     }
  121. }