src/Controller/Admin/AuthController.php line 64

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
  9. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  10. use Pimcore\Controller\FrontendController;
  11. use Pimcore\Bundle\AdminBundle\HttpFoundation\JsonResponse;
  12. use Pimcore\Tool;
  13. use Pimcore\Tool\Session;
  14. use Pimcore\Tool\Authentication;
  15. use Pimcore\Bundle\AdminBundle\Security\BruteforceProtectionHandler;
  16. use Pimcore\Bundle\AdminBundle\Security\Exception\BruteforceProtectionException;
  17. use App\Helper\APIHelper;
  18. use App\Helper\LogHelper;
  19. use App\Model\Admin;
  20. use Defuse\Crypto\Crypto;
  21. use App\Services\AppLogService;
  22. use App\Services\AuthenService;
  23. /**
  24.  * @Route("/auth-admin")
  25.  * @Template
  26.  */
  27. class AuthController extends FrontendController
  28. {
  29.     CONST URL_TENANT_ID_KEY '<tenant-id>';
  30.     public function loginSuccess($user)
  31.     {
  32.         Session::get()->unlock();
  33.         Session::get()->set('user'$user);
  34.         AuthenService::checkOneSession($userSession::getSessionId());
  35.         AppLogService::insert('Login', [
  36.             'pimcoreAdmin' => $user
  37.         ]);
  38.         return $this->redirectToRoute("pimcore_admin_login");
  39.     }
  40.     public function loginFail($error)
  41.     {
  42.         $error 'Login failure!';
  43.         return $this->redirectToRoute("auth-admin-login", ['error' => $error]);
  44.     }
  45.     /**
  46.      * @Route("/login", name="auth-admin-login")
  47.      */
  48.     public function loginAction(
  49.         Request $request,
  50.         ?BruteforceProtectionHandler $bruteforceProtectionHandler null
  51.     )
  52.     {
  53.         $error $request->get('error');
  54.         $username '';
  55.         try {
  56.             $adminUser Session::get()->get('user');
  57.             if ($adminUser) {
  58.                 return $this->redirectToRoute("pimcore_admin_login");
  59.             }
  60.             if ($request->get('id')) {
  61.                 $token $request->get('id');
  62.                 $secret getenv('APP_PARAMETERS_SECRET');
  63.                 $decrypted Crypto::decryptWithPassword($token$secret);
  64.                 $decrypted explode('|'$decrypted);
  65.                 list($timestamp$username) = $decrypted;
  66.                 $user \Pimcore\Model\User::getByName($username);
  67.                 if ($user) {
  68.                     if ($user->getActive()) {
  69.                         return $this->loginSuccess($user);
  70.                     }
  71.                 }
  72.                 AppLogService::insert('Login', [
  73.                     'error' => [],
  74.                     'username' => $username
  75.                 ], 400AppLogService::FAILED);
  76.                 return $this->loginFail($error);
  77.             } else {
  78.                 if ($request->getMethod() == Request::METHOD_POST) {
  79.                     $username $request->get('username');
  80.                     $password $request->get('password');
  81.                     $bruteforceProtectionHandler?->checkProtection($username$request);
  82.                     $adminUser Authentication::authenticatePlaintext($username$password);
  83.                     if ($adminUser) {
  84.                         return $this->loginSuccess($adminUser); 
  85.                     } else {
  86.                         $bruteforceProtectionHandler?->addEntry($username$request);
  87.                         $error "Null account or error password or deactive!";
  88.                     }
  89.                 }
  90.             }
  91.         } catch (BruteforceProtectionException $e) {
  92.             $error $e->getMessage();
  93.         } catch (\Throwable $e) {
  94.             $error "Login failure!";
  95.         }
  96.         if ($error) {
  97.             AppLogService::insert('Login', [
  98.                 'error' => $error,
  99.                 'username' => $username
  100.             ], 400AppLogService::FAILED);
  101.         }
  102.         $errorMessage '';
  103.         if ($error) {
  104.             $errorMessage strpos($error'Too many login attempts') !== false
  105.                 $error
  106.                 'Login failure!';
  107.         }
  108.         return [
  109.             'error' => $errorMessage
  110.         ];
  111.     }
  112.     /**
  113.      * @Route("/connect-azure", name="auth-admin-connect-azure")
  114.      */
  115.     public function connectAzureAction()
  116.     {
  117.         $redirectUrl getenv('AZURE_URL_LOGIN') ."/"getenv('AZURE_TENANT'). getenv('AZURE_PATH_AUTHORIZE');
  118.         $redirectUrl .= '?app=SGPlatform';
  119.         $params = [
  120.             'client_id' => getenv('AZURE_SSO_CLIENT_ID'),
  121.             'redirect_uri' => $this->getCurrentDomain() . '/auth-admin/check-azure',
  122.             'response_type' => getenv('AZURE_RESPONSE_TYPE'),
  123.             'scope' => getenv('AZURE_SSO_SCOPE'),
  124.             'state' => $this->randString(),
  125.             'response_mode' => getenv('AZURE_RESPONSE_MODE')
  126.         ];
  127.         foreach ($params as $field => $value) {
  128.             $redirectUrl .= '&'$field .'='$value;
  129.         }
  130.         return $this->redirect($redirectUrl);
  131.     }
  132.     /**
  133.      * @Route("/check-azure", name="auth-admin-check-azure")
  134.      */
  135.     public function checkAzureAction(
  136.         Request $request,
  137.         Admin $adminModel
  138.     )
  139.     {
  140.         $method 'POST';
  141.         $url str_replace(self::URL_TENANT_ID_KEYgetenv('AZURE_TENANT'), getenv('AZURE_URL_GET_TOKEN'));
  142.         $headers = [
  143.             // 'Content-Type' => 'application/x-www-url-form-urlencoded'
  144.         ];
  145.         $body = [
  146.             'client_id' => getenv('AZURE_SSO_CLIENT_ID'),
  147.             'scope' => getenv('AZURE_SSO_SCOPE'),
  148.             'redirect_uri' => $this->getCurrentDomain() . '/auth-admin/check-azure',
  149.             'grant_type' => getenv('AZURE_GRANT_TYPE'),
  150.             'client_secret' => getenv('AZURE_SSO_CLIENT_SECRET'),
  151.             'code' => $request->get('code')
  152.         ];
  153.         $response APIHelper::callFormParams($method$url$headers$body);
  154.         if ($response['status'] == 200) {
  155.             $tokenType $response['response']['token_type'];
  156.             $accessToken $response['response']['access_token'];
  157.             $authorization $tokenType .' '$accessToken;
  158.             $url getenv('AZURE_URL_GET_PROFILE');
  159.             $headers = [
  160.                 'Authorization' => $authorization
  161.             ];
  162.             $response APIHelper::callGET($url$headers);
  163.             if ($response['status'] == 200) {
  164.                 $admin $adminModel->getAdmin($response['response']);
  165.                 if ($admin) {
  166.                     $userAdmin $admin->getUser();
  167.                     if ($userAdmin) {
  168.                         $response['pimcoreAdmin'] = $userAdmin;
  169.                         $user \Pimcore\Model\User::getById($userAdmin);
  170.                         if ($user->getActive()) {
  171.                             $token \Pimcore\Tool\Authentication::generateToken($user->getName());
  172.                             AppLogService::insert('Login'$response);
  173.                             return [
  174.                                 'token' => $token
  175.                             ];
  176.                         }
  177.                     }
  178.                 }
  179.                 AppLogService::insert('Login'$response400AppLogService::FAILED);
  180.                 return $this->loginFail("Login failure!");
  181.             } else {
  182.                 $error "Can access account from Azure AD";
  183.                 if (array_key_exists('error'$response)) {
  184.                     $error $response['error'];
  185.                 }
  186.                 AppLogService::insert('Login'$response400AppLogService::FAILED);
  187.                 return $this->loginFail($error);
  188.             }
  189.         } else {
  190.             $error "Can access account from Azure AD";
  191.             if (array_key_exists('error'$response)) {
  192.                 $error $response['error'];
  193.             }
  194.             AppLogService::insert('Login'$response400AppLogService::FAILED);
  195.             return $this->loginFail($error);
  196.         }
  197.     }
  198.     /**
  199.      * @Route("/logout", name="auth-admin-logout")
  200.      */
  201.     public function logoutAction(Request $request)
  202.     {
  203.         try {
  204.             $adminUser Session::get()->get('user');
  205.             AppLogService::insert('Logout', [
  206.                 'pimcoreAdmin' => $adminUser
  207.             ]);
  208.             AuthenService::logoutSession($adminUser);
  209.         } catch (\Throwable $e) {}
  210.         Session::get()->unlock();
  211.         Session::get()->set('user'null);
  212.         return $this->redirectToRoute('auth-admin-login');
  213.     }
  214.     private function randString($length 128) {
  215.         return bin2hex(random_bytes($length));
  216.     }
  217.     private function getCurrentDomain()
  218.     {
  219.         $domain "https://"$_SERVER['HTTP_HOST'];
  220.         return $domain;
  221.     }
  222. }