src/Controller/Admin/AuthController.php line 62

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