2012-09-07 4 views
-1

Facebook 캔버스 앱이해야하는 기본 작업 중 하나는 사용 권한을 확인하고 사용자가 페이지에 액세스하도록 권한을 부여해야한다는 것입니다. 이 작업을 수행하는 좋은 방법은 무엇입니까?Facebook 캔버스 앱에서 필요한 권한을 확인하는 방법은 무엇입니까?

+0

이 되었습니까? 질문은 매우 모호합니다 – Igy

+0

해당 링크는 특정 권한을 확인하고 특정 권한을 요구하는 것은 아닙니다. 이는 제작 후 여러 페이지에서 수행됩니다. –

+0

가능한 [새로운 facebook javascript sdk로 확장 권한 확인] (http://facebook.stackoverflow.com/questions/3388367/check-for-extended-permissions-with-new-facebook-javascript-sdk) – Igy

답변

0

내 자신의 앱용으로 개발 한 시스템입니다. 당신의 코드를 다운로드 할 수 있습니다

http://developsocialapps.com/permissions-and-basic-graph-api-calls/

이 무거운 리프팅을 수행하는 라이브러리입니다. 권한을 확인하는 주된 방법은 requireAuthorization입니다. 먼저 initOauthUserFromSignedRequest을 사용하여 signed_request가 있는지 확인하고 사용이 인증되었는지 확인하고 사용자 ID와 토큰을 설정합니다. 그런 다음 hasAllPermissions을 사용하여 그래프 API의 me/permissions를 확인하여 사용자에게 필요한 모든 권한이 있는지 확인합니다. 모든 페이지로드시이 API를 사용하고 싶지 않기 때문에 쿠키에 사용 권한을 저장합니다. 사용자에게 권한이 없거나 승인되지 않은 경우 사용자에게 권한 대화 상자가 표시됩니다.

class FacebookApp {    

    public $appId; 
    private $appSecret; 
    private $nameSpace; 
    public $userId; 
    public $token; 
    public $tokenExpires; 

    // get your own from http://www.w3.org/P3P/ 
    public $p3p = 'P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"'; 

    /* construct object 
     appid, secret, and namespace from app settings */ 
    public function __construct($id, $secret, $namespace) { 
     $this->appId = $id; 
     $this->appSecret = $secret; 
     $this->nameSpace = $namespace; 
    } 

    /* return json data from a graph api object or false */ 
    function getGraphObject($object) { 
     $return = false; 
     $url = $this->getGraphUrl($object); 
     $response = $this->makeCurlRequest($url); 
     if ($repsonse !== false) { 
      $return = json_decode($response,true); 
      if (isset($return['error'])) { 
       $return = false; 
       // the request return an error, you can debug here 
      } 
     } 
     return $return; 
    } 

    /* constructs graphs url */ 
    public function getGraphUrl($object,$limit=false) { 
     $url = "https://graph.facebook.com/".$object; 
     if (strpos($url,"?") === false) $url .= "?"; 
     else $url .= "&"; 
     $url .= "access_token=".$this->token; 
     if ($limit !== false) $url .= "&limit=".$limit; 
     return $url; 
    } 

    /* uses curl to get a url */ 
    public function makeCurlRequest($url) { 
     $return = false; 
     try { 
      $ch = curl_init(); 
      curl_setopt($ch, CURLOPT_URL, $url); 
      curl_setopt($ch, CURLOPT_HEADER, false); 
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
      $response = curl_exec($ch); 
      $responseInfo = curl_getinfo($ch); 
      curl_close($ch); 
      if ($responseInfo['http_code']==200) { 
       $return = $response; 
      } 
     } catch (Exception $e) { 
      $return = false; 
     } 
     return $return; 
    } 

    /* sets userid and token from signed request, return true or false if authorized */ 
    public function initOauthUserFromSignedRequest() { 
     $authorized = false; 
     if (isset($_REQUEST['signed_request'])) { 
      $data = $this->parseSignedRequest($_REQUEST['signed_request']); 
      if ($data !== false) { 
       if (isset($data['user_id']) && isset($data['oauth_token'])) { 
        $this->userId = $data['user_id']; 
        $this->token = $data['oauth_token']; 
        $this->tokenExpires = $data['expires']; 
        $authorized = true; 
       } 
      } 
     } 
     return $authorized; 
    } 

    /* require user to authorize and have permissions for page 
     redirect_uri = url to return after user has authorized like redirect.php 
     success_uri = url to redirect to on successful authorization like mypage.php 
     scope = comma separted list of permissions */ 
    function requireAuthorization($redirect_uri,$success_uri=false,$scope=false) { 
     if ($success_uri === false) { 
      // if no success_uri use current page, all files for app must be in same directory 
      $success_uri = substr($_SERVER['REQUEST_URI'],strrpos($_SERVER['REQUEST_URI'],"/")+1); 
     } 
     $this->setCookie ("success_uri",$success_uri,0); // we will use this on the redirect_uri page 
     $requireauth = true; 
     if ($this->initOauthUserFromSignedRequest()) { // user has authorized 
      if (($scope === false) || ($this->hasAllPermissions($scope))) { // now check for perms 
       $requireauth = false; 
      } 
     } 
     if ($requireauth) { // user is either not authorized or doesn't have permissions 
      $url = $this->getAuthUrl($this->getCanvasUrl($redirect_uri),$scope); 
      echo "<html>\n<body>\n<script>\ntop.location.href='".$url."';\n</script></body></html>"; 
      exit(); 
     } 
    } 

    /* checks to see if has permissions, scope is comma separated list */ 
    public function hasAllPermissions($scope) { 
     $return = false; 
     $cookiename = "permissions_".$this->appId."_".$this->userId; 
     $requiredpermissions = explode(",",$scope); 
     // first check cookie 
     if (isset($_COOKIE[$cookiename])) { 
      $return = true; 
      $permissions = json_decode($_COOKIE[$cookiename],true); 
      foreach ($requiredpermissions as $perm) { 
       if ($permissions['data'][0][$perm] != 1) { 
        $return = false; 
        break; 
       } 
      } 
     } 
     // if didn't have all in cookie, then see if it is in graph 
     if ($return == false) { 
      $permissions = $this->getGraphObject("me/permissions"); 
      if ($permissions !== false) { 
       $this->setCookie($cookiename,json_encode($permissions),0); 
       $return = true; 
       foreach ($requiredpermissions as $perm) { 
        if ($permissions['data'][0][$perm] != 1) { 
         $return = false; 
         break; 
        } 
       } 
      } 
     } 
     return $return; 
    } 

    /* sets a cookie with p3p headers */ 
    public function setCookie($name,$value,$expires) { 
     if ($this->p3p != '') { 
      header($this->p3p); 
      $this->p3p = ''; 
     } 
     setcookie ($name,$value,$expires,"/"); 
    } 

    /* returns url for oauth authorization 
     redirect_uri = url to return after user has authorized 
     scope = comma separted list of permissions */ 
    public function getAuthUrl($redirect_uri,$scope=false) { 
     $url = "https://www.facebook.com/dialog/oauth/?client_id=".$this->appId."&redirect_uri=".rawurlencode($redirect_uri); 
     if ($scope !== false) $url .= "&scope=".rawurlencode($scope); 
     return $url; 
    } 


    /* returns url to app canvas page, $page like mypage.php?foo=bar */ 
    public function getCanvasUrl($page) { 
     if ($_SERVER['HTTPS'] == "on") $protocol = "https"; 
     else $protocol = "http"; 
     return $protocol."://apps.facebook.com/".$this->nameSpace."/".$page; 
    } 

    /* parses signed_request parameter and returns data object, returns false if sigs don't match */ 
    public function parseSignedRequest($signed_request) { 
     list($encoded_sig, $payload) = explode('.', $signed_request, 2); 
     $data = json_decode(base64_decode(strtr($payload, '-_', '+/')), true); 
     $sig = base64_decode(strtr($encoded_sig, '-_', '+/')); 
     $expected_sig = hash_hmac('sha256', $payload, $this->appSecret, true); 
     if ($sig == $expected_sig) { 
      return $data; 
     } else { 
      return false; 
     } 
    } 
} 

이 같은 페이지에서 사용 :

$facebookapp = new FacebookApp("id1234...","secret...","appnamespace"); 

$facebookapp->requireAuthorization("redirect.php","thispage.php","user_about_me,user_likes,more_permissions"); 

redirect.php는 사용자가 승인 또는 허가를 취소 한 경우 감지하는 페이지입니다. 승인 된 경우 다시 첫 번째 페이지로 리디렉션되며 취소 된 경우 메시지가 표시됩니다. 작동하지 않는 [캔버스 인증 (https://developers.facebook.com/docs/authentication/canvas/) 문서에 뭔가

<?php 
require_once("../lib/facebookapp.php"); 
require_once("config.php"); 

$facebookapp = new FacebookApp($GLOBALS['facebookAppId'],$GLOBALS['facebookAppSecret'],$GLOBALS['facebookNamespace']); 

if ((!isset($_GET['error'])) && isset($_GET['code'])) { 
    // user has auhtorized this app, go the the page from success_uri cookie 
    if (isset($_COOKIE['success_uri'])) $url = $facebookapp->getCanvasUrl($_COOKIE['success_uri']); 
    else $url = $facebookapp->getCanvasUrl(''); 
    echo "<html>\n<body>\n<script>\ntop.location.href='".$url."';\n</script></body></html>"; 
    exit(); 
} 

?><html> 
<body> 
<h1>Permission Denied</h1> 
<p>You have denied permissions to this app.</p> 
<p><a href="<?php echo $facebookapp->getCanvasUrl(''); ?>" target="_top">Home</a></p> 
</body> 
</html> 
관련 문제