app/Plugin/SiteKit42/Controller/Admin/ConfigController.php line 121

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of EC-CUBE
  4.  *
  5.  * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
  6.  *
  7.  * http://www.ec-cube.co.jp/
  8.  *
  9.  * For the full copyright and license information, please view the LICENSE
  10.  * file that was distributed with this source code.
  11.  */
  12. namespace Plugin\SiteKit42\Controller\Admin;
  13. use Eccube\Controller\AbstractController;
  14. use Eccube\Entity\Member;
  15. use Eccube\Repository\BaseInfoRepository;
  16. use Eccube\Service\SystemService;
  17. use Eccube\Util\CacheUtil;
  18. use Eccube\Util\StringUtil;
  19. use Google_Service_SiteVerification;
  20. use Google_Service_Webmasters;
  21. use GuzzleHttp\Client;
  22. use Plugin\SiteKit42\Entity\IdToken;
  23. use Plugin\SiteKit42\Repository\IdTokenRepository;
  24. use Plugin\SiteKit42\Service\Google_Site_Kit_Client;
  25. use Plugin\SiteKit42\Service\Google_Site_Kit_Proxy_Client;
  26. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  27. use Symfony\Component\Filesystem\Filesystem;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  31. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  32. use Symfony\Component\Routing\Annotation\Route;
  33. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  34. use Symfony\Component\Routing\RouterInterface;
  35. use Symfony\Component\Yaml\Yaml;
  36. class ConfigController extends AbstractController
  37. {
  38.     const SESSION_KEY_SITE_KIT_NONCE 'session.sitekit.nonce';
  39.     /**
  40.      * @var BaseInfoRepository
  41.      */
  42.     protected $baseInfoRepository;
  43.     /**
  44.      * @var IdTokenRepository
  45.      */
  46.     private $idTokenRepository;
  47.     /**
  48.      * @var Google_Site_Kit_Proxy_Client
  49.      */
  50.     private $siteKitClient;
  51.     /**
  52.      * ConfigController constructor.
  53.      */
  54.     public function __construct(BaseInfoRepository $baseInfoRepositoryIdTokenRepository $idTokenRepositoryGoogle_Site_Kit_Proxy_Client $siteKitClient)
  55.     {
  56.         $this->baseInfoRepository $baseInfoRepository;
  57.         $this->idTokenRepository $idTokenRepository;
  58.         $this->siteKitClient $siteKitClient;
  59.     }
  60.     /**
  61.      * @Route("/%eccube_admin_route%/site_kit/config", name="site_kit42_admin_config")
  62.      * @Template("@SiteKit42/admin/config.twig")
  63.      */
  64.     public function index(Request $request)
  65.     {
  66.         $nonce StringUtil::quickRandom();
  67.         $this->session->set(self::SESSION_KEY_SITE_KIT_NONCE$nonce);
  68.         $params http_build_query([
  69.             'name' => $this->baseInfoRepository->get()->getShopName(),
  70.             'url' => $this->generateUrl('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL),
  71.             'redirect_uri' => $this->generateUrl(
  72.                 'site_kit_callback',
  73.                 [],
  74.                 UrlGeneratorInterface::ABSOLUTE_URL),
  75.             'action_uri' => $this->generateUrl(
  76.                 'site_kit_action_callback',
  77.                 [],
  78.                 UrlGeneratorInterface::ABSOLUTE_URL),
  79.             'return_uri' => $this->generateUrl(
  80.                 'site_kit42_admin_config',
  81.                 [],
  82.                 UrlGeneratorInterface::ABSOLUTE_URL),
  83.             'analytics_redirect_uri' => $this->generateUrl(
  84.                 'site_kit_analytics_callback',
  85.                 [],
  86.                 UrlGeneratorInterface::ABSOLUTE_URL),
  87.             'application_name' => Google_Site_Kit_Client::CLIENT_NAME,
  88.             'nonce' => $nonce,
  89.             'supports' => 'credentials_retrieval file_verification',
  90.             'scope' => implode(' ', ['profile',
  91.                 Google_Service_SiteVerification::SITEVERIFICATION,
  92.                 Google_Service_Webmasters::WEBMASTERS,
  93.             ]),
  94.             'hl' => 'ja',
  95.         ]);
  96.         $oauthUrl 'https://sitekit.withgoogle.com/site-management/setup/?'.$params;
  97.         /* @var Member $Member */
  98.         return [
  99.             'oauth_url' => $oauthUrl,
  100.             'user_info' => $this->getUserInfo(),
  101.         ];
  102.     }
  103.     /**
  104.      * @Route("/%eccube_admin_route%/cube_kit/analytics_callback", name="site_kit_analytics_callback")
  105.      */
  106.     public function analyticsCallback()
  107.     {
  108.     }
  109.     public function siteVerification()
  110.     {
  111.         $file $this->eccubeConfig['plugin_data_realdir'].'/SiteKit42/google-site-verification.txt';
  112.         if (file_exists($file)) {
  113.             $verificationToken file_get_contents($file);
  114.             return new Response($verificationToken);
  115.         }
  116.         throw new NotFoundHttpException();
  117.     }
  118.     /**
  119.      * @Route("/%eccube_admin_route%/cube_kit/action_callback", name="site_kit_action_callback", methods={"GET"})
  120.      * @Route("/cube_kit/action_callback", methods={"GET"})
  121.      */
  122.     public function actionCallback(Request $requestCacheUtil $cacheUtilSystemService $systemServiceRouterInterface $router)
  123.     {
  124.         $nonce $this->session->get(self::SESSION_KEY_SITE_KIT_NONCE);
  125.         if ($nonce !== $request->get('nonce')) {
  126.             throw new BadRequestHttpException();
  127.         }
  128.         if ($request->get('googlesitekit_verification_token')) {
  129.             if ($request->get('googlesitekit_verification_token_type') == 'FILE') {
  130.                 $token $request->get('googlesitekit_verification_token');
  131.                 $filesystem = new Filesystem();
  132.                 $filesystem->dumpFile(
  133.                     $this->eccubeConfig['plugin_data_realdir'].'/SiteKit42/google-site-verification.txt',
  134.                     'google-site-verification: '.$token
  135.                 );
  136.                 $systemService->switchMaintenance(true);
  137.                 // ルーティング生成
  138.                 $yaml Yaml::dump([
  139.                     'site_kit_google_site_verification' => [
  140.                         'path' => '/'.$token,
  141.                         'controller' => 'Plugin\SiteKit42\Controller\Admin\ConfigController::siteVerification',
  142.                     ]
  143.                 ]);
  144.                 $filesystem->dumpFile(
  145.                     $this->eccubeConfig['plugin_data_realdir'].'/SiteKit42/routes.yaml',
  146.                     $yaml);
  147.                 $cacheUtil->clearCache();
  148.                 // sitekit.withgoogle.comへリダイレクトするため、画面描画後のメンテナンス解除ができない。
  149.                 // 従来のEventでのメンテナンス解除を行う
  150.                 $systemService->disableMaintenance();
  151.             }
  152.             $params http_build_query([
  153.                 'application_name' => 'ec-cube/google-site-kit/0.1.0',
  154.                 'nonce' => $nonce,
  155.                 'supports' => 'credentials_retrieval file_verification',
  156.                 'code' => $request->get('googlesitekit_code'),
  157.                 'site_code' => $request->get('googlesitekit_site_code'),
  158.                 'verify' => 'true',
  159.                 'verification_method' => 'FILE',
  160.                 'hl' => 'ja',
  161.             ]);
  162.             return $this->redirect('https://sitekit.withgoogle.com/site-management/setup/?'.$params);
  163.         }
  164.         $client = new Client();
  165.         $response $client->post('https://sitekit.withgoogle.com/o/oauth2/site/', [
  166.             'form_params' => [
  167.                 'code' => $request->get('googlesitekit_code'),
  168.                 'site_code' => $request->get('googlesitekit_site_code')
  169.             ]
  170.         ]);
  171.         if ($response->getStatusCode() == 200) {
  172.             $payload json_decode($response->getBody()->getContents(), true);
  173.             $BaseInfo $this->baseInfoRepository->get();
  174.             $BaseInfo->setSiteKitSiteId($payload['site_id']);
  175.             $BaseInfo->setSiteKitSiteSecret($payload['site_secret']);
  176.             $this->entityManager->persist($BaseInfo);
  177.             $this->entityManager->flush($BaseInfo);
  178.             $params http_build_query([
  179.                 'application_name' => 'ec-cube/google-site-kit/0.1.0',
  180.                 'nonce' => $nonce,
  181.                 'supports' => 'credentials_retrieval file_verification',
  182.                 'code' => $request->get('googlesitekit_code'),
  183.                 'site_id' => $payload['site_id'],
  184.             ]);
  185.             return $this->redirect('https://sitekit.withgoogle.com/site-management/setup/?'.$params);
  186.         }
  187.     }
  188.     /**
  189.      * @Route("/%eccube_admin_route%/cube_kit/callback", name="site_kit_callback")
  190.      * @Template("@SiteKit42/admin/config.twig")
  191.      *
  192.      * @param Request $request
  193.      *
  194.      * @return \Symfony\Component\HttpFoundation\RedirectResponse
  195.      */
  196.     public function callback(Request $request)
  197.     {
  198.         $code $request->query->get('code');
  199.         if (isset($code)) {
  200.             $baseInfo $this->baseInfoRepository->get();
  201.             $this->siteKitClient->setClientId($baseInfo->getSiteKitSiteId());
  202.             $this->siteKitClient->setClientSecret($baseInfo->getSiteKitSiteSecret());
  203.             $this->siteKitClient->setHttpClient($this->createDefaultHttpClient());
  204.             $this->siteKitClient->setRedirectUri($this->generateUrl('site_kit_callback', [], UrlGeneratorInterface::ABSOLUTE_URL));
  205.             $token $this->siteKitClient->fetchAccessTokenWithAuthCode($code);
  206.             // store in the session also
  207.             $this->session->set('site_kit_id_token'$token);
  208.             $this->siteKitClient->setAccessToken($token);
  209.             $IdToken $this->idTokenRepository->findByMember($this->getUser()) ?: new IdToken();
  210.             $IdToken->setMember($this->getUser());
  211.             $IdToken->setIdToken(json_encode($token));
  212.             $this->entityManager->persist($IdToken);
  213.             $this->entityManager->flush($IdToken);
  214.             // redirect back to the example
  215.             return $this->redirectToRoute('site_kit_dashboard');
  216.         }
  217.     }
  218.     /**
  219.      * @return Client
  220.      */
  221.     protected function createDefaultHttpClient()
  222.     {
  223.         $options = ['exceptions' => false];
  224.         $options['base_uri'] = 'https://www.googleapis.com';
  225.         $options['headers'] = ['User-Agent' => 'ec-cube/google-site-kit/0.1.0'];
  226.         return new Client($options);
  227.     }
  228.     private function getUserInfo()
  229.     {
  230.         /* @var Member $Member */
  231.         $Member $this->getUser();
  232.         if ($Member->getIdToken()) {
  233.             $client $this->siteKitClient->authorize();
  234.             $response $client->request('GET''https://www.googleapis.com/oauth2/v1/userinfo');
  235.             return json_decode($response->getBody()->getContents(), true);
  236.         }
  237.         return null;
  238.     }
  239. }