Skip to content

Commit

Permalink
add basic auth support
Browse files Browse the repository at this point in the history
  • Loading branch information
clarkeash committed Oct 15, 2017
1 parent 322ccd1 commit c78cc8c
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Support/BasicAuth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace Shield\Shield\Support;

use Illuminate\Http\Request;

trait BasicAuth
{
/**
* @param \Illuminate\Http\Request $request
* @param string $username
* @param string $password
*
* @return bool
*/
public function checkBasic(Request $request, string $username, string $password): bool
{
if ($request->hasHeader('PHP-AUTH-USER') && $request->hasHeader('PHP-AUTH-PW')) {
return $request->header('PHP-AUTH-USER') == $username && $request->header('PHP-AUTH-PW') == $password;
}

return false;
}
}
69 changes: 69 additions & 0 deletions tests/Unit/Support/BasicAuthTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
<?php

namespace Shield\Shield\Test\Unit\Support;

use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use PHPUnit\Framework\Assert;
use Shield\Shield\Contracts\Service;
use Shield\Shield\Support\BasicAuth;
use Shield\Testing\TestCase;

/**
* Class BasicAuthTest
*
* @package \Shield\Shield\Test\Unit\Support
*/
class BasicAuthTest extends TestCase
{
/**
* @var \Shield\Shield\Test\Unit\Support\Example
*/
private $service;

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

$this->service = new Example;
}

/** @test */
public function it_will_fail_if_invalid_credentials()
{
$request = $this->request();
$request->headers->add([
'PHP-AUTH-USER' => 'user',
'PHP-AUTH-PW' => 'password',
]);

Assert::assertFalse($this->service->checkBasic($request, 'user', 'pass'));
}

/** @test */
public function it_will_pass_if_correct_credentials()
{
$request = $this->request();
$request->headers->add([
'PHP-AUTH-USER' => 'user',
'PHP-AUTH-PW' => 'pass',
]);

Assert::assertTrue($this->service->checkBasic($request, 'user', 'pass'));
}
}

class Example implements Service {

use BasicAuth;

public function verify(Request $request, Collection $config): bool
{
return true;
}

public function headers(): array
{
return [];
}
}

0 comments on commit c78cc8c

Please sign in to comment.