まず、GitHubのアプリは
https://github.com/settings/applications/new
で登録できます。
アプリを登録すると、Client IDとClient Secretが手に入ります。
PHP用のGitHubライブラリは
http://developer.github.com/v3/libraries/
に記載があるのですが、単に認証にだけ使いたい場合は、以下の方法で可能でした。
コントローラ(classes/controller/github.php)
<?php
class Controller_Github extends Controller
{
private static $client_id = 'xxxxxxxxxx';
private static $client_secret = 'yyyyyyyyyy';
public function action_signin()
{
Github::authorize(static::$client_id);
}
public function action_callback()
{
$code = Input::get('code', false);
if($code === false)
{
throw new Exception('Invalid code.');
}
$access_token = Github::get_access_token(static::$client_id, static::$client_secret, $code);
$user = Github::get_user($access_token['access_token']);
Debug::dump($user);
exit();
}
}
Githubクラス(classes/github.php)
<?php
class Github
{
const AUTHORIZE_URL = 'https://github.com/login/oauth/authorize';
const GET_ACCESS_TOKEN_URL = 'https://github.com/login/oauth/access_token';
const GET_USER_URL = 'https://api.github.com/user';
public static function authorize($client_id, $params = array())
{
$params = array_merge(array('client_id' => $client_id), $params);
Response::redirect(static::AUTHORIZE_URL.'?'.http_build_query($params));
}
public static function get_access_token($client_id, $client_secret, $code, $params = array())
{
$params = array_merge(
array(
'client_id' => $client_id,
'client_secret' => $client_secret,
'code' => $code,
),
$params
);
$context = stream_context_create(array('http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($params),
)));
$access_token = file_get_contents(static::GET_ACCESS_TOKEN_URL, false, $context);
parse_str($access_token, $access_token);
return $access_token;
}
public static function get_user($access_token, $params = array())
{
$params = array_merge(array('access_token' => $access_token), $params);
$json = file_get_contents(static::GET_USER_URL.'?'.http_build_query($params));
return json_decode($json);
}
}
Githubクラスの各メソッドの引数で$params = array()とありますが、これを調整すればscopeの指定も出来るのかなーと思います。(実際にはやってません。。。)
尚、Githubクラスは
https://github.com/mp-php/fuel-myapp/blob/master/classes/my/github.php
にも置いてあります。(名前が少し違いますが。)
開発者向けのサイトなら、Github認証オンリーも有りなのかなーと思っていたりします。
No comments:
Post a Comment