-
-
Save EvanDotPro/eb18537ca9363273922d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace EdpGithub\Authentication\Adapter; | |
use EdpUser\Authentication\Adapter\AbstractAdapter, | |
EdpUser\Authentication\AuthEvent, | |
EdpGithub\Module, | |
EdpGithub\ApiClient\ApiClient, | |
Zend\Http\ClientStatic, | |
Zend\Http\PhpEnvironment\Response; | |
class EdpUserGithub extends AbstractAdapter | |
{ | |
public function authenticate(AuthEvent $e) | |
{ | |
if ($this->isSatisfied()) return; | |
$request = $e->getRequest(); | |
if ($request->query()->get('code')) { | |
if (!$this->validateCallbackCode($request->query()->get('code'))) { | |
$this->setSatisfied(false); | |
$e->setIdentity(null); | |
die('fail!'); | |
// redirect them back to some error page | |
return false; | |
} | |
$this->setSatisfied(true); | |
$response = new Response(); | |
$response->headers()->addHeaderLine('Location', '/user'); | |
$response->setStatusCode(302); | |
return $response; | |
} | |
$params = array('client_id' => Module::getOption('github_client_id')); | |
if (Module::getOption('github_callback_url')) { | |
$params['redirect_uri'] = Module::getOption('github_callback_url'); | |
} | |
$queryString = http_build_query($params); | |
$url = 'https://github.com/login/oauth/authorize?' . $queryString; | |
$e->setIdentity(null); | |
$response = new Response(); | |
$response->headers()->addHeaderLine('Location', $url); | |
$response->setStatusCode(302); | |
return $response; | |
} | |
protected function validateCallbackCode($code) | |
{ | |
$url = 'https://github.com/login/oauth/access_token'; | |
$params = array( | |
'client_id' => Module::getOption('github_client_id'), | |
'client_secret' => Module::getOption('github_client_secret'), | |
'code' => $code, | |
); | |
$content = ClientStatic::post($url, $params)->getContent(); | |
parse_str($content, $response); | |
if (isset($response['access_token']) | |
&& isset($response['token_type']) | |
&& ('bearer' === $response['token_type']) | |
) { | |
$this->setSatisfied(true); | |
return true; | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment