Skip to content

Add support for two factor authentication #138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 17, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions doc/two_factor_authentication.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
## Two factor authentication
[Back to the navigation](index.md)


### Raising the exception

```php
try {
$authorization = $github->api('authorizations')->create();
} catch (Github\Exception\TwoFactorAuthenticationRequiredException $e {
echo sprintf("Two factor authentication of type %s is required.", $e->getType());
}
```

Once the code has been retrieved (by sms for example), you can create an authorization:

```
$authorization = $github->api('authorizations')->create(array('note' => 'Optional'), $code);
```
6 changes: 4 additions & 2 deletions lib/Github/Api/Authorizations.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ public function show($number)
return $this->get('authorizations/'.rawurlencode($number));
}

public function create(array $params)
public function create(array $params, $OTPCode = null)
{
return $this->post('authorizations', $params);
$headers = null === $OTPCode ? array() : array('X-GitHub-OTP' => $OTPCode);

return $this->post('authorizations', $params, $headers);
}

public function update($id, array $params)
Expand Down
19 changes: 19 additions & 0 deletions lib/Github/Exception/TwoFactorAuthenticationRequiredException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace Github\Exception;

class TwoFactorAuthenticationRequiredException extends RuntimeException
{
private $type;

public function __construct($type, $code = 0, $previous = null)
{
$this->type = $type;
parent::__construct('Two factor authentication is enabled on this account', $code, $previous);
}

public function getType()
{
return $this->type;
}
}
7 changes: 5 additions & 2 deletions lib/Github/HttpClient/HttpClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Github\HttpClient;

use Github\Exception\TwoFactorAuthenticationRequiredException;
use Guzzle\Http\Client as GuzzleClient;
use Guzzle\Http\ClientInterface;
use Guzzle\Http\Message\Request;
Expand Down Expand Up @@ -139,9 +140,11 @@ public function request($path, $body = null, $httpMethod = 'GET', array $headers
try {
$response = $this->client->send($request);
} catch (\LogicException $e) {
throw new ErrorException($e->getMessage());
throw new ErrorException($e->getMessage(), $e->getCode(), $e);
} catch (TwoFactorAuthenticationRequiredException $e) {
throw $e;
} catch (\RuntimeException $e) {
throw new RuntimeException($e->getMessage());
throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}

$this->lastRequest = $request;
Expand Down
9 changes: 9 additions & 0 deletions lib/Github/HttpClient/Listener/ErrorListener.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Github\HttpClient\Listener;

use Github\Exception\TwoFactorAuthenticationRequiredException;
use Github\HttpClient\Message\ResponseMediator;
use Guzzle\Common\Event;
use Guzzle\Http\Message\Response;
Expand Down Expand Up @@ -45,6 +46,14 @@ public function onRequestError(Event $event)
throw new ApiLimitExceedException($this->options['api_limit']);
}

if (401 === $response->getStatusCode()) {
if ($response->hasHeader('X-GitHub-OTP') && 0 === strpos((string) $response->getHeader('X-GitHub-OTP'), 'required;')) {
$type = substr((string) $response->getHeader('X-GitHub-OTP'), 9);

throw new TwoFactorAuthenticationRequiredException($type);
}
}

$content = ResponseMediator::getContent($response);
if (is_array($content) && isset($content['message'])) {
if (400 == $response->getStatusCode()) {
Expand Down
23 changes: 23 additions & 0 deletions test/Github/Tests/HttpClient/HttpClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,29 @@ public function shouldThrowExceptionWhenApiIsExceeded()
$httpClient->get($path, $parameters, $headers);
}

/**
* @test
* @expectedException \Github\Exception\TwoFactorAuthenticationRequiredException
*/
public function shouldForwardTwoFactorAuthenticationExceptionWhenItHappens()
{
$path = '/some/path';
$parameters = array('a = b');
$headers = array('c' => 'd');

$response = new Response(401);
$response->addHeader('X-GitHub-OTP', 'required; sms');

$mockPlugin = new MockPlugin();
$mockPlugin->addResponse($response);

$client = new GuzzleClient('http://123.com/');
$client->addSubscriber($mockPlugin);

$httpClient = new TestHttpClient(array(), $client);
$httpClient->get($path, $parameters, $headers);
}

protected function getBrowserMock(array $methods = array())
{
$mock = $this->getMock(
Expand Down
32 changes: 32 additions & 0 deletions test/Github/Tests/HttpClient/Listener/ErrorListenerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,38 @@ public function shouldNotPassWhen422IsSentWithErrorCode($errorCode)
$listener->onRequestError($this->getEventMock($response));
}

/**
* @test
* @expectedException \Github\Exception\TwoFactorAuthenticationRequiredException
*/
public function shouldThrowTwoFactorAuthenticationRequiredException()
{
$response = $this->getMockBuilder('Guzzle\Http\Message\Response')->disableOriginalConstructor()->getMock();
$response->expects($this->once())
->method('isClientError')
->will($this->returnValue(true));
$response->expects($this->any())
->method('getStatusCode')
->will($this->returnValue(401));
$response->expects($this->any())
->method('getHeader')
->will($this->returnCallback(function ($name) {
switch ($name) {
case 'X-RateLimit-Remaining':
return 5000;
case 'X-GitHub-OTP':
return 'required; sms';
}
}));
$response->expects($this->any())
->method('hasHeader')
->with('X-GitHub-OTP')
->will($this->returnValue(true));

$listener = new ErrorListener(array());
$listener->onRequestError($this->getEventMock($response));
}

public function getErrorCodesProvider()
{
return array(
Expand Down