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