Skip to content

Instantly share code, notes, and snippets.

@scrubmx
Created July 24, 2019 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scrubmx/d5d95b50f73e4e0f89780df04732f364 to your computer and use it in GitHub Desktop.
Save scrubmx/d5d95b50f73e4e0f89780df04732f364 to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Auth\Access\AuthorizationException;
class VerifyUserRole
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param array $roles
* @return mixed
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function handle($request, Closure $next, ...$roles)
{
if ($request->user()->roles->whereIn('slug', $roles)->isNotEmpty()) {
return $next($request);
}
throw new AuthorizationException;
}
}
<?php
namespace Tests\Unit\Http\Middleware;
use Illuminate\Http\Response;
use Tests\TestCase;
use App\Models\User;
use Illuminate\Support\Facades\Route;
use App\Http\Middleware\VerifyUserRole;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Auth\Access\AuthorizationException;
class VerifyUserRoleTest extends TestCase
{
use RefreshDatabase;
/**
* @var \Illuminate\Routing\Route
*/
protected $route;
/**
* Setup the test environment.
*
* @return void
*/
protected function setUp(): void
{
parent::setUp();
$this->route = Route::get('_test/middleware', function () {
return response('OK', 200);
});
}
/** @test */
public function it_throws_an_unauthorized_exception_if_the_user_does_not_have_the_provided_role()
{
$user = factory(User::class)->create();
$this->route->middleware('role:admin');
$this->actingAs($user)
->get($this->route->uri)
->assertStatus(Response::HTTP_FORBIDDEN)
->assertSeeText(__('Forbidden'));
}
/** @test */
public function it_does_nothing_if_the_user_does_have_the_provided_role()
{
$admin = factory(User::class)->state('admin')->create();
$this->route->middleware('role:admin');
$this->actingAs($admin)
->get($this->route->uri)
->assertSuccessful();
}
/** @test */
public function it_does_nothing_if_the_user_have_at_least_one_of_the_provided_roles()
{
$user = factory(User::class)->state('developer')->create();
$this->route->middleware('role:admin,developer');
$this->actingAs($user)
->get($this->route->uri)
->assertSuccessful();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment