vendor/pimcore/pimcore/bundles/AdminBundle/Controller/Admin/LoginController.php line 54

Open in your IDE?
  1. <?php
  2. /**
  3.  * Pimcore
  4.  *
  5.  * This source file is available under two different licenses:
  6.  * - GNU General Public License version 3 (GPLv3)
  7.  * - Pimcore Commercial License (PCL)
  8.  * Full copyright and license information is available in
  9.  * LICENSE.md which is distributed with this source code.
  10.  *
  11.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  12.  *  @license    http://www.pimcore.org/license     GPLv3 and PCL
  13.  */
  14. namespace Pimcore\Bundle\AdminBundle\Controller\Admin;
  15. use Pimcore\Bundle\AdminBundle\Controller\AdminAbstractController;
  16. use Pimcore\Bundle\AdminBundle\Controller\BruteforceProtectedControllerInterface;
  17. use Pimcore\Bundle\AdminBundle\Security\Authenticator\AdminLoginAuthenticator;
  18. use Pimcore\Bundle\AdminBundle\Security\BruteforceProtectionHandler;
  19. use Pimcore\Bundle\AdminBundle\Security\CsrfProtectionHandler;
  20. use Pimcore\Config;
  21. use Pimcore\Controller\KernelControllerEventInterface;
  22. use Pimcore\Controller\KernelResponseEventInterface;
  23. use Pimcore\Event\Admin\Login\LoginRedirectEvent;
  24. use Pimcore\Event\Admin\Login\LostPasswordEvent;
  25. use Pimcore\Event\AdminEvents;
  26. use Pimcore\Extension\Bundle\PimcoreBundleManager;
  27. use Pimcore\Http\ResponseHelper;
  28. use Pimcore\Logger;
  29. use Pimcore\Model\User;
  30. use Pimcore\Security\SecurityHelper;
  31. use Pimcore\Tool;
  32. use Pimcore\Tool\Authentication;
  33. use Symfony\Component\HttpFoundation\RedirectResponse;
  34. use Symfony\Component\HttpFoundation\Request;
  35. use Symfony\Component\HttpFoundation\Response;
  36. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  37. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  38. use Symfony\Component\RateLimiter\RateLimiterFactory;
  39. use Symfony\Component\Routing\Annotation\Route;
  40. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  41. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  42. use Symfony\Component\Security\Core\Security;
  43. use Symfony\Component\Security\Core\User\UserInterface;
  44. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  45. use Symfony\Contracts\Translation\LocaleAwareInterface;
  46. use Symfony\Contracts\Translation\TranslatorInterface;
  47. /**
  48.  * @internal
  49.  */
  50. class LoginController extends AdminAbstractController implements BruteforceProtectedControllerInterfaceKernelControllerEventInterfaceKernelResponseEventInterface
  51. {
  52.     public function __construct(
  53.         protected ResponseHelper $responseHelper,
  54.         protected TranslatorInterface $translator,
  55.         protected PimcoreBundleManager $bundleManager,
  56.         protected EventDispatcherInterface $eventDispatcher,
  57.     ) {
  58.     }
  59.     /**
  60.      * @param ControllerEvent $event
  61.      */
  62.     public function onKernelControllerEvent(ControllerEvent $event)
  63.     {
  64.         // use browser language for login page if possible
  65.         $locale 'en';
  66.         $availableLocales Tool\Admin::getLanguages();
  67.         foreach ($event->getRequest()->getLanguages() as $userLocale) {
  68.             if (in_array($userLocale$availableLocales)) {
  69.                 $locale $userLocale;
  70.                 break;
  71.             }
  72.         }
  73.         if ($this->translator instanceof LocaleAwareInterface) {
  74.             $this->translator->setLocale($locale);
  75.         }
  76.     }
  77.     /**
  78.      * {@inheritdoc}
  79.      */
  80.     public function onKernelResponseEvent(ResponseEvent $event)
  81.     {
  82.         $response $event->getResponse();
  83.         $response->headers->set('X-Frame-Options''deny'true);
  84.         $this->responseHelper->disableCache($responsetrue);
  85.     }
  86.     /**
  87.      * @Route("/login", name="pimcore_admin_login")
  88.      * @Route("/login/", name="pimcore_admin_login_fallback")
  89.      */
  90.     public function loginAction(Request $requestCsrfProtectionHandler $csrfProtectionConfig $config)
  91.     {
  92.         $queryParams $request->query->all();
  93.         if ($request->get('_route') === 'pimcore_admin_login_fallback') {
  94.             return $this->redirectToRoute('pimcore_admin_login'$queryParamsResponse::HTTP_MOVED_PERMANENTLY);
  95.         }
  96.         $redirectUrl $this->dispatchLoginRedirect($queryParams);
  97.         if ($this->generateUrl('pimcore_admin_login'$queryParams) != $redirectUrl) {
  98.             return new RedirectResponse($redirectUrl);
  99.         }
  100.         $csrfProtection->regenerateCsrfToken();
  101.         $user $this->getAdminUser();
  102.         if ($user instanceof UserInterface) {
  103.             return $this->redirectToRoute('pimcore_admin_index');
  104.         }
  105.         $params $this->buildLoginPageViewParams($config);
  106.         $session_gc_maxlifetime ini_get('session.gc_maxlifetime');
  107.         if (empty($session_gc_maxlifetime)) {
  108.             $session_gc_maxlifetime 120;
  109.         }
  110.         $params['csrfTokenRefreshInterval'] = ((int)$session_gc_maxlifetime 60) * 1000;
  111.         if ($request->get('too_many_attempts')) {
  112.             $params['error'] = SecurityHelper::convertHtmlSpecialChars($request->get('too_many_attempts'));
  113.         }
  114.         if ($request->get('auth_failed')) {
  115.             $params['error'] = 'error_auth_failed';
  116.         }
  117.         if ($request->get('session_expired')) {
  118.             $params['error'] = 'error_session_expired';
  119.         }
  120.         if ($request->get('deeplink')) {
  121.             $params['deeplink'] = true;
  122.         }
  123.         $params['browserSupported'] = $this->detectBrowser();
  124.         $params['debug'] = \Pimcore::inDebugMode();
  125.         return $this->render('@PimcoreAdmin/Admin/Login/login.html.twig'$params);
  126.     }
  127.     /**
  128.      * @Route("/login/csrf-token", name="pimcore_admin_login_csrf_token")
  129.      */
  130.     public function csrfTokenAction(Request $requestCsrfProtectionHandler $csrfProtection)
  131.     {
  132.         if (!$this->getAdminUser()) {
  133.             $csrfProtection->regenerateCsrfToken();
  134.         }
  135.         return $this->json([
  136.            'csrfToken' => $csrfProtection->getCsrfToken(),
  137.         ]);
  138.     }
  139.     /**
  140.      * @Route("/logout", name="pimcore_admin_logout" , methods={"POST"})
  141.      */
  142.     public function logoutAction()
  143.     {
  144.         // this route will never be matched, but will be handled by the logout handler
  145.     }
  146.     /**
  147.      * Dummy route used to check authentication
  148.      *
  149.      * @Route("/login/login", name="pimcore_admin_login_check")
  150.      *
  151.      * @see AdminLoginAuthenticator for the security implementation
  152.      * @see AdminAuthenticator for the security implementation (Authenticator Based Security)
  153.      */
  154.     public function loginCheckAction()
  155.     {
  156.         // just in case the authenticator didn't redirect
  157.         return new RedirectResponse($this->generateUrl('pimcore_admin_login'));
  158.     }
  159.     /**
  160.      * @Route("/login/lostpassword", name="pimcore_admin_login_lostpassword")
  161.      */
  162.     public function lostpasswordAction(Request $request, ?BruteforceProtectionHandler $bruteforceProtectionHandlerCsrfProtectionHandler $csrfProtectionConfig $configRateLimiterFactory $resetPasswordLimiter)
  163.     {
  164.         $params $this->buildLoginPageViewParams($config);
  165.         $error null;
  166.         if ($request->getMethod() === 'POST' && $username $request->get('username')) {
  167.             $user User::getByName($username);
  168.             if (!$user instanceof User) {
  169.                 $error 'user_unknown';
  170.             }
  171.             // TODO Pimcore 11: remove this BC layer, only the RateLimiter would be valid
  172.             if ($bruteforceProtectionHandler) {
  173.                 try {
  174.                     $bruteforceProtectionHandler->checkProtection($username$request);
  175.                 } catch (\Exception $e) {
  176.                     $error 'user_reset_password_too_many_attempts';
  177.                 }
  178.             } else {
  179.                 $limiter $resetPasswordLimiter->create($request->getClientIp());
  180.                 if (false === $limiter->consume(1)->isAccepted()) {
  181.                     $error 'user_reset_password_too_many_attempts';
  182.                 }
  183.             }
  184.             if (!$error) {
  185.                 if (!$user->isActive()) {
  186.                     $error 'user_inactive';
  187.                 }
  188.                 if (!$user->getEmail()) {
  189.                     $error 'user_no_email_address';
  190.                 }
  191.                 if (!$user->getPassword()) {
  192.                     $error 'user_no_password';
  193.                 }
  194.             }
  195.             if (!$error) {
  196.                 $token Authentication::generateToken($user->getName());
  197.                 $loginUrl $this->generateUrl('pimcore_admin_login_check', [
  198.                     'token' => $token,
  199.                     'reset' => 'true',
  200.                 ], UrlGeneratorInterface::ABSOLUTE_URL);
  201.                 try {
  202.                     $event = new LostPasswordEvent($user$loginUrl);
  203.                     $this->eventDispatcher->dispatch($eventAdminEvents::LOGIN_LOSTPASSWORD);
  204.                     // only send mail if it wasn't prevented in event
  205.                     if ($event->getSendMail()) {
  206.                         $mail Tool::getMail([$user->getEmail()], 'Pimcore lost password service');
  207.                         $mail->setIgnoreDebugMode(true);
  208.                         $mail->text("Login to pimcore and change your password using the following link. This temporary login link will expire in 24 hours: \r\n\r\n" $loginUrl);
  209.                         $mail->send();
  210.                     }
  211.                     // directly return event response
  212.                     if ($event->hasResponse()) {
  213.                         return $event->getResponse();
  214.                     }
  215.                 } catch (\Exception $e) {
  216.                     Logger::error('Error sending password recovery email: ' $e->getMessage());
  217.                     $error 'lost_password_email_error';
  218.                 }
  219.             }
  220.             if ($error) {
  221.                 Logger::error('Lost password service: ' $error);
  222.                 $bruteforceProtectionHandler?->addEntry($request->get('username'), $request);
  223.             }
  224.         }
  225.         $csrfProtection->regenerateCsrfToken();
  226.         if ($error) {
  227.             $params['reset_error'] = 'Please make sure you are entering a correct input.';
  228.             if ($error === 'user_reset_password_too_many_attempts') {
  229.                 $params['reset_error'] = 'Too many attempts. Please retry later.';
  230.             }
  231.         }
  232.         return $this->render('@PimcoreAdmin/Admin/Login/lostpassword.html.twig'$params);
  233.     }
  234.     /**
  235.      * @Route("/login/deeplink", name="pimcore_admin_login_deeplink")
  236.      */
  237.     public function deeplinkAction(Request $request)
  238.     {
  239.         // check for deeplink
  240.         $queryString $_SERVER['QUERY_STRING'];
  241.         if (preg_match('/(document|asset|object)_([0-9]+)_([a-z]+)/'$queryString$deeplink)) {
  242.             $deeplink $deeplink[0];
  243.             $perspective strip_tags($request->get('perspective'''));
  244.             if (strpos($queryString'token')) {
  245.                 $url $this->dispatchLoginRedirect([
  246.                     'deeplink' => $deeplink,
  247.                     'perspective' => $perspective,
  248.                 ]);
  249.                 $url .= '&' $queryString;
  250.                 return $this->redirect($url);
  251.             } elseif ($queryString) {
  252.                 $url $this->dispatchLoginRedirect([
  253.                     'deeplink' => 'true',
  254.                     'perspective' => $perspective,
  255.                 ]);
  256.                 return $this->render('@PimcoreAdmin/Admin/Login/deeplink.html.twig', [
  257.                     'tab' => $deeplink,
  258.                     'redirect' => $url,
  259.                 ]);
  260.             }
  261.         }
  262.     }
  263.     protected function buildLoginPageViewParams(Config $config): array
  264.     {
  265.         return [
  266.             'config' => $config,
  267.             'pluginCssPaths' => $this->bundleManager->getCssPaths(),
  268.         ];
  269.     }
  270.     /**
  271.      * @Route("/login/2fa", name="pimcore_admin_2fa")
  272.      */
  273.     public function twoFactorAuthenticationAction(Request $request, ?BruteforceProtectionHandler $bruteforceProtectionHandlerConfig $config)
  274.     {
  275.         $params $this->buildLoginPageViewParams($config);
  276.         if ($request->hasSession()) {
  277.             // we have to call the check here manually, because BruteforceProtectionListener uses the 'username' from the request
  278.             $bruteforceProtectionHandler?->checkProtection($this->getAdminUser()->getName(), $request);
  279.             $session $request->getSession();
  280.             $authException $session->get(Security::AUTHENTICATION_ERROR);
  281.             if ($authException instanceof AuthenticationException) {
  282.                 $session->remove(Security::AUTHENTICATION_ERROR);
  283.                 $params['error'] = $authException->getMessage();
  284.                 $bruteforceProtectionHandler?->addEntry($this->getAdminUser()->getName(), $request);
  285.             }
  286.         } else {
  287.             $params['error'] = 'No session available, it either timed out or cookies are not enabled.';
  288.         }
  289.         return $this->render('@PimcoreAdmin/Admin/Login/twoFactorAuthentication.html.twig'$params);
  290.     }
  291.     /**
  292.      * @Route("/login/2fa-verify", name="pimcore_admin_2fa-verify")
  293.      *
  294.      * @param Request $request
  295.      */
  296.     public function twoFactorAuthenticationVerifyAction(Request $request)
  297.     {
  298.     }
  299.     /**
  300.      * @return bool
  301.      */
  302.     public function detectBrowser()
  303.     {
  304.         $supported false;
  305.         $browser = new \Browser();
  306.         $browserVersion = (int)$browser->getVersion();
  307.         if ($browser->getBrowser() == \Browser::BROWSER_FIREFOX && $browserVersion >= 72) {
  308.             $supported true;
  309.         }
  310.         if ($browser->getBrowser() == \Browser::BROWSER_CHROME && $browserVersion >= 84) {
  311.             $supported true;
  312.         }
  313.         if ($browser->getBrowser() == \Browser::BROWSER_SAFARI && $browserVersion >= 13.1) {
  314.             $supported true;
  315.         }
  316.         if ($browser->getBrowser() == \Browser::BROWSER_EDGE && $browserVersion >= 90) {
  317.             $supported true;
  318.         }
  319.         return $supported;
  320.     }
  321.     private function dispatchLoginRedirect(array $routeParams = []): string
  322.     {
  323.         $event = new LoginRedirectEvent('pimcore_admin_login'$routeParams);
  324.         $this->eventDispatcher->dispatch($eventAdminEvents::LOGIN_REDIRECT);
  325.         return $this->generateUrl($event->getRouteName(), $event->getRouteParams());
  326.     }
  327. }