Advertisement
GetFocus

AmbersportStravaAuth

Jan 3rd, 2018
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.80 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Ambersport\Strava;
  4.  
  5. use Bitrix\Main\Localization\Loc;
  6. Loc::loadMessages(__FILE__);
  7.  
  8. class Auth extends \CSocServAuth {
  9.  
  10.     const ID = 'Strava';
  11.     protected $flexSSL = true;
  12.     protected $entityOAuth;
  13.  
  14.     public function isFlexSSL(){
  15.         return $this->flexSSL;
  16.     }
  17.  
  18.     public static function GetDescription() {
  19.         return [
  20.             [
  21.                 'ID' => 'Strava',
  22.                 'CLASS' => '\\Ambersport\\Strava\\Auth',
  23.                 'NAME' => 'Strava',
  24.                 'ICON' => 'strava',
  25.             ]
  26.         ];
  27.     }
  28.  
  29.     public function GetSettings() {
  30.         return [
  31.             [
  32.                 'client_id', 'Client ID', '', ['text', 40],
  33.             ],
  34.             [
  35.                 'client_token', 'Client Token', '', ['text', 40],
  36.             ],
  37.             [
  38.                 'client_secret', 'Client Secret', '', ['text', 40],
  39.             ]
  40.         ];
  41.     }
  42.  
  43.     public function GetFormHtml($arParams) {
  44.         $onclickJS = $this->GetOnClickJs($arParams);
  45.         return $arParams["FOR_INTRANET"]
  46.             ? array("ON_CLICK" => 'onclick="'.$onclickJS.'"')
  47.             : '<a href="javascript:void(0)" onclick="'.$onclickJS.'" class="strava-button"></a>';
  48.     }
  49.  
  50.     public function GetOnClickJs($arParams) {
  51.         $redirect_uri = \CSocServUtil::GetCurUrl('auth_service_id='.self::ID.'&check_key='.$_SESSION['UNIQUE_KEY']);
  52.         // Only for CloudFlare flexible SSL
  53.         if($this->isFlexSSL()){
  54.           $redirect_uri = str_replace('http://', 'https://', $redirect_uri);
  55.         }
  56.         $queryParams = [
  57.             'redirect_uri' => $redirect_uri,
  58.             'client_id' => trim(self::getOption('client_id')),
  59.             'response_type' => 'code',
  60.         ];
  61.         $url = 'https://www.strava.com/oauth/authorize?'.http_build_query($queryParams);
  62.         return "BX.util.popup('".$url."', 660, 425)";
  63.     }
  64.  
  65.     public function getEntityOAuth($code = false)
  66.     {
  67.         if (!$this->entityOAuth)
  68.         {
  69.             $this->entityOAuth = new \Ambersport\Strava\OAuth();
  70.         }
  71.  
  72.         if ($code !== false)
  73.         {
  74.             $this->entityOAuth->setCode($code);
  75.         }
  76.  
  77.         return $this->entityOAuth;
  78.     }
  79.  
  80.     public function prepareUser($arStravaUser, $short = false)
  81.     {
  82.         $first_name = $last_name = $gender = "";
  83.  
  84.         if ($arStravaUser['firstname'] <> '')
  85.         {
  86.             $first_name = $arStravaUser['firstname'];
  87.         }
  88.  
  89.         if ($arStravaUser['lastname'] <> '')
  90.         {
  91.             $last_name = $arStravaUser['lastname'];
  92.         }
  93.  
  94.         if (isset($arStravaUser['sex']) && $arStravaUser['sex'] != '')
  95.         {
  96.             $gender = $arStravaUser['sex'];
  97.         }
  98.  
  99.         $arFields = array(
  100.             'EXTERNAL_AUTH_ID' => self::ID,
  101.             'XML_ID' => $arStravaUser['id'],
  102.             'LOGIN' => "StravaUser_" . $arStravaUser['id'],
  103.             'EMAIL' => $this->entityOAuth->GetCurrentUserEmail(),
  104.             'NAME' => $first_name,
  105.             'LAST_NAME' => $last_name,
  106.             'PERSONAL_GENDER' => $gender,
  107.             'OATOKEN' => $this->entityOAuth->getToken(),
  108.             'OATOKEN_EXPIRES' => $this->entityOAuth->getAccessTokenExpires(),
  109.         );
  110.  
  111.         if (isset($arStravaUser['profile']) && self::CheckPhotoURI($arStravaUser['profile']))
  112.         {
  113.             if (!$short)
  114.             {
  115.                 $arPic = \CFile::MakeFileArray($arStravaUser['profile']);
  116.                 if ($arPic)
  117.                 {
  118.                     $arFields["PERSONAL_PHOTO"] = $arPic;
  119.                 }
  120.             }
  121.  
  122.             if (strlen(SITE_ID) > 0)
  123.             {
  124.                 $arFields["SITE_ID"] = SITE_ID;
  125.             }
  126.         }
  127.  
  128.         return $arFields;
  129.     }
  130.  
  131.     public function Authorize()
  132.     {
  133.         $GLOBALS["APPLICATION"]->RestartBuffer();
  134.         $bSuccess = SOCSERV_AUTHORISATION_ERROR;
  135.  
  136.         if ((isset($_REQUEST["code"]) && $_REQUEST["code"] <> '') && \CSocServAuthManager::CheckUniqueKey())
  137.         {
  138.             if (IsModuleInstalled('bitrix24') && defined('BX24_HOST_NAME'))
  139.                 $redirect_uri = self::CONTROLLER_URL . "/redirect.php";
  140.             else
  141.                 $redirect_uri = \CHTTP::URN2URI($GLOBALS['APPLICATION']->GetCurPage()) . '?auth_service_id=' . self::ID;
  142.  
  143.             if($this->isFlexSSL()){
  144.               $redirect_uri = str_replace('http://', 'https://',  $redirect_uri);
  145.             }
  146.             $this->entityOAuth = $this->getEntityOAuth($_REQUEST['code']);
  147.             if ($this->entityOAuth->GetAccessToken($redirect_uri) !== false)
  148.             {
  149.                 $arStravaUser = $this->entityOAuth->GetCurrentUser();
  150.                 if (is_array($arStravaUser) && ($arStravaUser['id'] <> ''))
  151.                 {
  152.                     $arFields = $this->prepareUser($arStravaUser);
  153.                     $bSuccess = $this->AuthorizeUser($arFields);
  154.                 }
  155.             }
  156.         }
  157.  
  158.         $url = ($GLOBALS["APPLICATION"]->GetCurDir() == "/login/") ? "" : $GLOBALS["APPLICATION"]->GetCurDir();
  159.         $aRemove = array("logout", "auth_service_error", "auth_service_id", "code", "error_reason", "error", "error_description", "check_key", "current_fieldset");
  160.  
  161.  
  162.         if (isset($_REQUEST['backurl']) || isset($_REQUEST['redirect_url']))
  163.         {
  164.             $parseUrl = parse_url(isset($_REQUEST['redirect_url']) ? $_REQUEST['redirect_url'] : $_REQUEST['backurl']);
  165.  
  166.             $urlPath = $parseUrl["path"];
  167.             $arUrlQuery = explode('&', $parseUrl["query"]);
  168.  
  169.             foreach ($arUrlQuery as $key => $value)
  170.             {
  171.                 foreach ($aRemove as $param)
  172.                 {
  173.                     if (strpos($value, $param . "=") === 0)
  174.                     {
  175.                         unset($arUrlQuery[$key]);
  176.                         break;
  177.                     }
  178.                 }
  179.             }
  180.             $url = (!empty($arUrlQuery)) ? $urlPath . '?' . implode("&", $arUrlQuery) : $urlPath;
  181.         }
  182.  
  183.         if ($bSuccess === SOCSERV_REGISTRATION_DENY)
  184.         {
  185.             $url = (preg_match("/\?/", $url)) ? $url . '&' : $url . '?';
  186.             $url .= 'auth_service_id=' . self::ID . '&auth_service_error=' . $bSuccess;
  187.         }
  188.         elseif ($bSuccess !== true)
  189.         {
  190.             $url = (isset($urlPath)) ? $urlPath . '?auth_service_id=' . self::ID . '&auth_service_error=' . $bSuccess : $GLOBALS['APPLICATION']->GetCurPageParam(('auth_service_id=' . self::ID . '&auth_service_error=' . $bSuccess), $aRemove);
  191.         }
  192.  
  193.         if (\CModule::IncludeModule("socialnetwork") && strpos($url, "current_fieldset=") === false)
  194.         {
  195.             $url = (preg_match("/\?/", $url)) ? $url . "&current_fieldset=SOCSERV" : $url . "?current_fieldset=SOCSERV";
  196.         }
  197.  
  198.         echo '
  199.        <script type="text/javascript">
  200.        if(window.opener)
  201.        {
  202.            window.opener.location = \'' . \CUtil::JSEscape($url) . '\';
  203.        }
  204.        window.close();
  205.        </script>
  206.        ';
  207.         die();
  208.     }
  209. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement