Skip to content

Commit

Permalink
forbid multiple bearer auths
Browse files Browse the repository at this point in the history
  • Loading branch information
yitznewton committed Feb 26, 2014
1 parent 954a7fa commit 9ce42c6
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 2 deletions.
14 changes: 12 additions & 2 deletions src/EasyBib/Guzzle/Plugin/BearerAuth/BearerAuth.php
Expand Up @@ -20,6 +20,11 @@ class BearerAuth implements EventSubscriberInterface
*/
private $session;

/**
* @var bool
*/
private $headerAlreadySet = false;

/**
* @param AbstractSession $session
*/
Expand All @@ -44,16 +49,21 @@ public static function getSubscribedEvents()
*/
public function onRequestBeforeSend(Event $event)
{
if ($this->headerAlreadySet) {
return;
}

$event['request']->setHeader(
'Authorization',
sprintf('Bearer %s', $this->session->getToken())
);

$this->headerAlreadySet = true;
}

/**
* @param Event $event
* @throws \Guzzle\Http\Exception\BadResponseException
* @throws \Guzzle\Http\Exception\BadResponseException
* @throws BadResponseException
*/
public function onRequestException(Event $event)
{
Expand Down
46 changes: 46 additions & 0 deletions tests/EasyBib/Tests/Guzzle/Plugin/BearerAuth/BearerAuthTest.php
@@ -0,0 +1,46 @@
<?php

namespace EasyBib\Tests\Guzzle\Plugin\BearerAuth;

use EasyBib\Guzzle\Plugin\BearerAuth\BearerAuth;
use EasyBib\OAuth2\Client\SimpleSession;
use Guzzle\Common\Event;
use Guzzle\Http\Message\Request;
use Symfony\Component\HttpFoundation\Session\Session;

class BearerAuthTest extends \PHPUnit_Framework_TestCase
{
/**
* @var \EasyBib\OAuth2\Client\SimpleSession
*/
private $session;

public function setUp()
{
parent::setUp();

$this->session = $this->getMockBuilder('\EasyBib\OAuth2\Client\SimpleSession')
->disableOriginalConstructor()
->getMock();

$this->session->expects($this->any())
->method('getToken')
->will($this->returnValue('token_123'));
}

public function testMultipleSendsSetOnlyOneHeader()
{
$plugin = new BearerAuth($this->session);

$request = $this->getMockBuilder('\Guzzle\Http\Message\Request')
->setConstructorArgs(['GET', '/'])
->getMock();

$request->expects($this->once())
->method('setHeader');

$event = new Event(['request' => $request]);
$plugin->onRequestBeforeSend($event);
$plugin->onRequestBeforeSend($event);
}
}
@@ -0,0 +1,18 @@
<?php

namespace EasyBib\Tests\Mocks\OAuth2\Client;

use EasyBib\OAuth2\Client\TokenRequestFactoryInterface;
use EasyBib\OAuth2\Client\TokenRequestInterface;

class MockTokenRequestFactory implements TokenRequestFactoryInterface
{
/**
* @throws \BadMethodCallException
* @return TokenRequestInterface
*/
public function create()
{
throw new \BadMethodCallException('create() not yet implemented');
}
}

0 comments on commit 9ce42c6

Please sign in to comment.