首页 文章

Laravel Auth仅验证管理员/超级用户

提问于
浏览
6

我在Windows开发机器上使用Laravel 5 . 我想在整个应用程序中自定义和使用 Auth 中间件,以维护身份验证 . 我的用例是标准用例 . 有两个(或三个)类用户 - AdminRegular (常规将是所有非管理员用户) .

Admin具有后端管理的明显作用,因此具有单独的路由组 /admin/ ,它应该将未记录的用户重定向到 /admin/login . 我已经这样设置了..

Route::group(['middleware'=>'auth', 'prefix' => 'admin'], function() {
  Route::get('login','App\AuthController@getLogin');
  Route::post('login','App\AuthController@postLogin');
});

发布登录表单时, how do I ask Auth 添加过滤器

  • 或者只有 validate from among those users where 'is_admin' is true

  • 或要求它首先 join a User and a UserRoles table 仅识别具有管理员角色的用户?

2 回答

  • 5

    我建议您定义另一个中间件,用于检测用户是否为admin而不是修改auth . 现在将另一个中间件添加到只有管理员才能访问的路由中 .

    添加几个中间件来这样路由

    Route::group(['middleware' => ['auth','admin']], function() {
    

    中间件看起来像

    public function handle($request, Closure $next) {
      if (Auth::user()->role == "admin") {
        return $next($request);
      } else {
        return redirect("/")->withMyerror("You are not authorized for this action");
      }
    }
    
  • 0

    为什么不在处理Auth过滤器并尝试仅在某个条件下“验证”,在您的登录代码中,只需检查用户的类型是什么?

    这是我的高级代码:

    // get roles which are allowed to login to the admin panel
            $roles = $this->userService->adminRoles(); 
    
            $user = User::whereUsername(Input::get('username'))->whereIn('role_id', $roles)->first();
    
            if (is_null($user)) {
                // ...
            }
    
            // create our user data for the authentication
            $userdata = array(
                'username' => Input::get('username'),
                'password' => Input::get('password'),
            );
    
            // attempt to do the login
            // Auth::attempt($userdata) ....
    

    这样你只有在尝试登录时才这样做,就是这样吗?

相关问题