请耐心等待,我是测试新手。
所以,我现在有这样的中间件结构:
class IsActive
{
public function handle($request, Closure $next)
{
if (self::active()) {
return $next($request);
}
Auth::guard('web')->logout();
return redirect('/');
}
protected function active()
{
if (Auth::guard('web')->check()) {
$state = Auth::guard('web')->user()->state;
if ($state == 'enabled') {
return true;
}
}
return false;
}
}
class IsAdmin extends IsActive
{
public function handle($request, Closure $next)
{
if (parent::active()) {
if (Auth::guard('web')->check()) {
$role = Auth::guard('web')->user()->role->name;
if ($role == 'admin' || $role == 'superAdmin') {
return $next($request);
}
}
return redirect('/');
}
Auth::guard('web')->logout();
return redirect('/');
}
}
这是路线
Route::group(['middleware' => 'admin'], function () {
Route::get('/', 'ReportingController@reportingPage');
});
//Its registered on RouteServiceProvider that these routes require IsActive and this specific route needs for the admin
在 Reporting Controller 中,我得到了这个函数
public function reportingPage(Request $request) {
return view('reporting.reporting');
}
到目前为止还不错。如果用户有访问权限,那很好,如果没有,它会被重定向。
现在进行测试,我想验证管理员是否可以查看它(未经授权的人不能,但对于这个问题,我试图找出管理员)
protected $user;
public function setUp()
{
parent::setUp();
$this->user = new \App\Models\User(['role_id' => 6, //admin
'name' => 'Admin',
'user' => 'admin',
'email' => 'admin@admin.com',
'state' => 'enabled',
'deleted_at' => null]);
$this->be($this->user);
}
public function testCanAccessReportingPage()
{
$this->get("/reporting/")->assertStatus(200);
}
这是我遇到的错误,我正在尝试弄清楚这个过程是什么。显然我做错了什么或者忘记了什么,因此非常感谢有关如何测试此授权的提示和想法。
编辑:
在经过一些重构和一些尝试后删除了一个答案后,我确定 Auth::guard('web')->user()
有一个用户,Auth::guard('web')->user()->role()
在测试环境中为空。我已经通过加载关系解决了问题,但我现在的问题是:为什么在测试环境中会发生这种情况。
最佳答案
可能创建的用户(模拟)未在 $this 上下文中使用。
如果您查看文档 https://laravel.com/docs/5.6/http-tests#session-and-authentication ,你看方法
$this->actingAs($user)
完整示例:
<?php
use App\User;
class ExampleTest extends TestCase
{
public function testApplication()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->get('/');
}
}
关于php - Laravel 测试路由授权,中间件授权问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51706997/