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

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