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

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