Laravel 5:我应该如何实现Auth :: admin()作为Auth :: guest()?

问题描述:

我想要管理员授权。所以我在中间件有新类Laravel 5:我应该如何实现Auth :: admin()作为Auth :: guest()?

class Admin { 

public function handle($request, Closure $next) 
{ 

    if (Auth::check() && Auth::user()->isAdmin()) 
    { 
     return $next($request); 
    } 

    Session::flash('message', 'You need to be an administrator to visit this page.'); 

    return redirect('/'); 

} 

} 

然后在Kernel.php在我的用户模型加入

protected $routeMiddleware = [ 
    'auth' => \App\Http\Middleware\Authenticate::class, 
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 
    'admin' => \App\Http\Middleware\Admin::class, //added line 
]; 

我也定义isAdmin()注册。它的工作原理我做这个时,在路线:

get('protected', ['middleware' => ['auth', 'admin'], function() { 
    return "this page requires that you be logged in and an Admin"; 
}]); 

但我想使用它像验证::管理员()作为验证::客(),我应该在哪里实现这个功能呢?我需要在Guard.php中的抽象admin()吗?

我可以解决Auth :: user() - > isAdmin(),但我仍然想知道正确的方法来做到这一点。

谢谢。

谢谢。

+0

我可以知道你想实施这个吗? –

+0

我想在你的控制器的网页 – daolincheng

+0

做Auth :: admin()? –

首先,您不需要在路由中包含auth和admin中间件,因为您已经在管理中间件中检查了身份验证。

get('protected', ['middleware' => ['admin'], function() { 
    return "this page requires that you be logged in and an Admin"; 
}]); 

对于你的问题,首先,你需要扩展\Illuminate\Auth\Guard,并用它来代替。假设您的应用程序文件夹中有一个扩展文件夹。

namespace App\Extensions; 

use Illuminate\Auth\Guard; 

class CustomGuard extends Guard 
{ 
    public function admin() 
    { 
     if ($this->user()->isAdmin()) { 
      return true; 
     } 
     return false; 
    } 
} 
在AppService服务提供商

然后,

namespace App\Providers; 

use Illuminate\Support\ServiceProvider; 
use Illuminate\Auth\EloquentUserProvider; 
use App\Extensions\CustomGuard; 

class AppServiceProvider extends ServiceProvider 
{ 
    /** 
    * Bootstrap any application services. 
    * 
    * @return void 
    */ 
    public function boot() 
    { 
     Auth::extend('eloquent.admin', function ($app) { 
      $model = $app['config']['auth.model']; 
      $provider = new EloquentUserProvider($app['hash'], $model); 
      return new CustomGuard($provider, \App::make('session.store')); 
     }); 
    } 

    /** 
    * Register any application services. 
    * 
    * @return void 
    */ 
    public function register() 
    { 
     // 
    } 
} 

最后,在config/auth.php文件,更改如下行。

'driver' => 'eloquent.admin' 

然后你应该没问题。