Skip to content

Instantly share code, notes, and snippets.

@ralphschindler
Created September 13, 2012 15:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralphschindler/3714910 to your computer and use it in GitHub Desktop.
Save ralphschindler/3714910 to your computer and use it in GitHub Desktop.
<?php
namespace GitHub\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Http\ClientStatic;
use GitHubAPIv3\UserAPI;
class GitHubController extends AbstractActionController
{
public function indexAction()
{
$session = $this->getServiceLocator()->get('github-session');
$vars = array();
if (isset($session['access_token'])) {
$token = $session['access_token'];
$client = new UserAPI($token);
$user = $client->getAuthenticatedUser();
//$vars['user'] = $user;
$vars['user'] = $client->getUser('weierophinney');
}
$vm = new ViewModel($vars);
$vm->setTemplate('github/github/index');
return $vm;
}
public function sendToGitHubAction()
{
/** @var $session \Zend\Session\Container */
$session = $this->getServiceLocator()->get('github-session');
$session['state'] = $login_state = uniqid('state', true);
$config = $this->serviceLocator->get('config');
$loginConfig = $config['login'];
$url = 'https://github.com/login/oauth/authorize?';
$url .= 'client_id=' . $loginConfig['github_client_id'];
$url .= '&scope=repo';
$url .= '&state=' . $login_state;
return $this->redirect()->toUrl($url);
}
public function completeAction()
{
/** @var $request \Zend\Http\Request */
$request = $this->getRequest();
$code = $request->getQuery('code');
$state = $request->getQuery('state');
if ($code == '' || $state == '') {
return $this->redirect()->toRoute('github', array('action' => 'index'));
}
/** @var $session \Zend\Session\Container */
$session = $this->getServiceLocator()->get('github-session');
if ($state !== $session['state']) {
throw new \Exception('Invalid state.');
}
$config = $this->serviceLocator->get('config');
$loginConfig = $config['login'];
$response = ClientStatic::post(
'https://github.com/login/oauth/access_token',
array(
'client_id' => $loginConfig['github_client_id'],
'client_secret' => $loginConfig['github_client_secret'],
'code' => $code,
'state' => $state
),
array(
'Accept' => 'application/json'
)
);
unset($session['state']);
$body = $response->getBody();
$response = json_decode($body);
$session['access_token'] = $response->access_token;
$vm = new ViewModel();
$vm->setTemplate('github/github/complete');
return $vm;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment