首页 文章

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

提问于
浏览
1

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

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 回答

  • 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'
    

    那你应该没问题 .

相关问题