Skip to content

Commit

Permalink
Add Basic Authentication to Uhura
Browse files Browse the repository at this point in the history
  • Loading branch information
colindecarlo committed Nov 21, 2015
1 parent be40561 commit e0cf497
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 6 deletions.
36 changes: 30 additions & 6 deletions src/Uhura.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@

class Uhura
{
private $api = '';
private $resource = '';
private $api;
private $http;

private $resource = '';
private $token = null;

public function __construct($api)
{
$this->api = $api;
Expand All @@ -29,36 +31,58 @@ public static function test($api)
return $uhura;
}

public function useBasicAuthentication($username, $password)
{
$token = base64_encode(sprintf("%s:%s", $username, $password));
return $this->authenticate(sprintf("Basic %s", $token));
}

public function authenticate($token)
{
$this->token = $token;
return $this;
}

public function getHttp()
{
return $this->http;
}

public function get()
{
return $this->http->get($this->resource);
return $this->request('GET');
}

public function create($payload)
{
return $this->http->post($this->resource, ['form_params' => $payload]);
return $this->request('POST', $payload);
}

public function update($payload)
{
return $this->http->put($this->resource, ['form_params' => $payload]);
return $this->request('PUT', $payload);
}

public function delete()
{
return $this->http->delete($this->resource);
return $this->request('DELETE');
}

public function url()
{
return sprintf("%s%s", $this->api, $this->resource);
}

private function request($method, $payload = null)
{
$options = array_filter([
'headers' => array_filter(['Authorization' => $this->token]),
'form_params' => $payload
]);

return $this->http->request($method, $this->resource, $options);
}

public function __get($name)
{
$this->resource .= sprintf("/%s", $name);
Expand Down
16 changes: 16 additions & 0 deletions tests/UhuraTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,20 @@ public function test_that_uhura_sends_a_delete_request_to_the_correct_url_when_d
$this->assertEquals('DELETE', $handler->getLastRequest()->getMethod());
$this->assertEquals('https://example.com/users/1', $handler->getLastRequest()->getUri());
}

public function test_that_uhura_sends_an_authorization_header_when_sending_authenticated_requests()
{
$handler = $this->uhura->getHttp()->getConfig('handler');
$handler->append(new Response);

$this->uhura->useBasicAuthentication('username', 'some_token');

$this->uhura->users->get();

$this->assertTrue($handler->getLastRequest()->hasHeader('Authorization'));
$this->assertEquals(
sprintf('Basic %s', base64_encode('username:some_token')),
$handler->getLastRequest()->getHeader('Authorization')[0]
);
}
}

0 comments on commit e0cf497

Please sign in to comment.