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

时间:2015-11-19 17:50:53

标签: php authentication laravel-5

我想获得管理员授权。所以我在中间件中有了新课

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";
}]);

但我想像Auth :: admin()一样使用它作为Auth :: guest(),我应该在哪里实现这个功能?我首先需要在Guard.php中使用抽象的admin()吗?

我可以使用Auth :: user() - > isAdmin(),但我仍然想知道正确的方法。

感谢。

感谢。

1 个答案:

答案 0 :(得分:1)

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

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

对于您的问题,首先,您需要扩展\Illuminate\Auth\Guard并使用它。假设您的app文件夹中有一个Extensions文件夹。

namespace App\Extensions;

use Illuminate\Auth\Guard;

class CustomGuard extends Guard
{
    public function admin()
    {
        if ($this->user()->isAdmin()) {
            return true;
        }
        return false;
    }
}

然后在您的AppService Provider中

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'

然后你应该没事。