Laravel 5.1中间件用户键入重定向

时间:2015-12-06 08:35:04

标签: php laravel authentication laravel-5.1 laravel-middleware

我正在尝试在Laravel 5.1中制作应用程序。

在我的用户表中,我有3种类型的用户,管理员,代理和农民。在users表中有一个名为user_type_id的列,其中admin为user_type_id=1,agent为user_type_id=2,farm为user_type_id=3

管理员有权执行代理几乎没有权限的所有内容。

问题在于使用中间件时,我的Authenticate.php和AgentAuthenticate.php中间件文件就好像它们是相同的,这意味着代理正在获得管理员的所有权力。有什么逻辑错误吗?这是代码。

agentAuthenticate.php(中间件)

 public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('auth/login');
            }
        }
        if(! $this->auth->user()->user_type != 2) {
         return redirect()->guest('auth/login');   
        }
        return $next($request);
    } 

Authenticate.php

public function handle($request, Closure $next)
    {
        if ($this->auth->guest()) {
            if ($request->ajax()) {
                return response('Unauthorized.', 401);
            } else {
                return redirect()->guest('auth/login');
            }
        }
        if(! $this->auth->user()->user_type != 1) {
         return redirect()->guest('auth/login');   
        }
        return $next($request);
    }

routes.php文件

 //guest routes
    Route::resource('/farmerPoint','farmerPointController',['only' => ['index', 'show']]);
    Route::resource('/crop','cropController',['only' => ['index', 'show']]);

    //Admin routes
    Route::group(['middleware' => 'auth'], function () {
    Route::resource('agent','agentController');
    Route::resource('farmer','farmerController');
    Route::resource('farmer.crop','farmerCropController');
    Route::resource('cropType','cropTypeController');
    Route::resource('crop','cropController',['except' => ['index','show']]);
    Route::resource('farmerPoint','farmerPointController',['except' => ['index','show']]);
    Route::get('/AdminPanel',function(){
       return view('frontend.AdminPanel');
      });
    });
    //agent routes
       Route::group(['middleware' => 'agent'], function () {
       Route::resource('farmer','farmerController');
       Route::resource('farmer.crop','farmerCropController');
       Route::resource('agent','agentController',['only' => ['index','show']]);
       Route::get('/AgentPanel',function(){
        return view('frontend.AgentPanel'); 
       });
    });

1 个答案:

答案 0 :(得分:0)

Authenticate.php中应该是:

if($this->auth->user()->user_type != 1) {
   return redirect()->guest('auth/login');   
}

因为您想为类型不同于admin

的所有用户进行重定向

agentAuthenticate.php中应该是:

if(!in_array($this->auth->user()->user_type, [1,2])) {
   return redirect()->guest('auth/login');   
}

因为你想为类型不同于代理的所有用户进行重定向,但如果用户是admin,你也不想进行重定向(你提到Admin has permission to do everything