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


Laravel 5: how should I implement Auth::admin() as 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";
}]);

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

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

谢谢。

谢谢。

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

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

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

namespace App'Extensions;
use Illuminate'Auth'Guard;
class CustomGuard extends Guard
{
    public function admin()
    {
        if ($this->user()->isAdmin()) {
            return true;
        }
        return false;
    }
}

然后在您的应用程序服务提供商中,

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'

那你应该没事了。