<?php
namespace Yurun\OAuthLogin\Github;
use Yurun\OAuthLogin\Base;
use Yurun\OAuthLogin\ApiException;
class OAuth2 extends Base
{
const AUTH_DOMAIN = 'https://github.com/';
const API_DOMAIN = 'https://api.github.com/';
public $allowSignup = false;
public function getAuthLoginUrl($name, $params = array())
{
return static::AUTH_DOMAIN . $name . (empty($params) ? '' : ('?' . $this->http_build_query($params)));
}
public function getUrl($name, $params = array())
{
return static::API_DOMAIN . $name . (empty($params) ? '' : ('?' . $this->http_build_query($params)));
}
public function getAuthUrl($callbackUrl = null, $state = null, $scope = null)
{
$option = array(
'client_id' => $this->appid,
'redirect_uri' => null === $callbackUrl ? $this->callbackUrl : $callbackUrl,
'scope' => null === $scope ? $this->scope : $scope,
'state' => $this->getState($state),
'allow_signup' => $this->allowSignup,
);
if(null === $this->loginAgentUrl)
{
return $this->getAuthLoginUrl('login/oauth/authorize', $option);
}
else
{
return $this->loginAgentUrl . '?' . $this->http_build_query($option);
}
}
protected function __getAccessToken($storeState, $code = null, $state = null)
{
$this->result = $this->http->accept('application/json')->get($this->getAuthLoginUrl('login/oauth/access_token', array(
'client_id' => $this->appid,
'client_secret' => $this->appSecret,
'code' => isset($code) ? $code : (isset($_GET['code']) ? $_GET['code'] : ''),
'redirect_uri' => $this->getRedirectUri(),
'state' => isset($state) ? $state : (isset($_GET['state']) ? $_GET['state'] : ''),
)))->json(true);
if(isset($this->result['error']))
{
throw new ApiException($this->result['error'], 0);
}
else
{
return $this->accessToken = $this->result['access_token'];
}
}
public function getUserInfo($accessToken = null)
{
$this->result = $this->http->ua('YurunOAuthLogin')->get($this->getUrl('user', array(
'access_token' => null === $accessToken ? $this->accessToken : $accessToken,
)))->json(true);
if(isset($this->result['message']))
{
throw new ApiException($this->result['message'], 0);
}
else
{
$this->openid = $this->result['id'];
return $this->result;
}
}
public function refreshToken($refreshToken)
{
return false;
}
public function validateAccessToken($accessToken = null)
{
try
{
$this->getUserInfo($accessToken);
return true;
}
catch(ApiException $e)
{
return false;
}
}
}