2015-11-19 71 views
1

我想要管理員授權。所以我在中間件有新類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()? –

回答

1

首先,您不需要在路由中包含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' 

然後你應該沒問題。