Skip to content

Commit

Permalink
Because we need a JWT not required mode
Browse files Browse the repository at this point in the history
  • Loading branch information
Craig Bass committed Oct 23, 2015
1 parent 1781f19 commit 174941a
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 3 deletions.
21 changes: 21 additions & 0 deletions src/JwtGuard.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php
namespace Clearbooks\Dilex;
use Clearbooks\Dilex\JwtGuard\NoJwtRequired;
use Clearbooks\Dilex\JwtGuard\RequestAuthoriser;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
Expand Down Expand Up @@ -27,10 +28,30 @@ public function __construct( RequestAuthoriser $authoriser )
*/
public function execute( Request $request )
{
$controllerClass = $request->attributes->get('_controller');
if( !($this->isJwtRequired($controllerClass))) {
return null;
}

if( !$this->authoriser->isAuthorised( $request ) ) {
return new JsonResponse( ['error' => 'Invalid token'], 403 );
}
return null;
}

/**
* @param $controllerClass
* @return bool
*/
private function isJwtRequired($controllerClass)
{
if ($controllerClass) {
$reflection = new \ReflectionClass($controllerClass);
$jwtRequired = !$reflection->implementsInterface(NoJwtRequired::class);
return $jwtRequired;
} else {
$jwtRequired = true;
return $jwtRequired;
}
}
}
10 changes: 10 additions & 0 deletions src/JwtGuard/NoJwtRequired.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php


namespace Clearbooks\Dilex\JwtGuard;


interface NoJwtRequired
{

}
9 changes: 9 additions & 0 deletions test/JwtGuard/MockNoJwtRequiredController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php


namespace Clearbooks\Dilex\JwtGuard;

class MockNoJwtRequiredController implements NoJwtRequired
{

}
15 changes: 12 additions & 3 deletions test/JwtGuardTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@
* Time: 11:44
*/

namespace Authentication;
namespace Clearbooks\Dilex\JwtGuard;


use Clearbooks\Dilex\JwtGuard;
use Emarref\Jwt\Algorithm\Hs512;
use Emarref\Jwt\Algorithm\None;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

Expand Down Expand Up @@ -58,4 +56,15 @@ public function givenValidRequest_whenExecuting_returnNull()
$guard = new JwtGuard( new JwtGuard\RequestAuthoriserStub( true ) );
$this->assertNull($guard->execute($this->request));
}

/**
* @test
*/
public function givenInvalidRequest_AndControllerDoesNotRequireJwt_whenExecuting_returnNull()
{
$guard = new JwtGuard( new JwtGuard\RequestAuthoriserStub( false ) );
$this->request->attributes->set('_controller', MockNoJwtRequiredController::class );
$this->assertNull($guard->execute($this->request));
}

}

0 comments on commit 174941a

Please sign in to comment.