Home  >  Q&A  >  body text

php - laravel5.3如何兼容两套ACL权限管理?

求指教,按照http://9iphp.com/web/laravel/... 这个教程,在一个项目中实现了前后端用户分开的两套ACL,就是现在/app/Providers/AuthServiceProvider.php 中,boot方法,该怎样判断用户是前端还是后端用户啊,根本没办法获取用户信息,auth也没办法获取,求指教怎么处理?谢谢

巴扎黑巴扎黑2653 days ago294

reply all(2)I'll reply

  • 阿神

    阿神2017-04-11 10:22:54

    最终自己解决了,因为有一个BaseContorller __construct方法,这里设计来限制用户单浏览器登录的,每次前置执行一下,然后判断用户的session_id和当前的session_id

    在这里给用户
    Auth::user()->isAdmin = false;

    然后因为每次登录后,跳去首页或者任何页面,都会经过__construct方法,

    在/app/Providers/AuthServiceProviders.php 的boot方法中,这样进行判断:

     Gate::before(function($user) {
    
                if (!$user->isAdmin) {
                    $permissions = \App\UserPermission::with('roles')->get();
                } else {
                    $permissions = \App\Permission::with('roles')->get();
                }
    
                foreach ($permissions as $permission) {
                    Gate::define($permission->name, function($user) use ($permission) {
                        return $user->hasPermission($permission);
                    });
                }
            });

    这样就去分开了两套ACL权限

    reply
    0
  • ringa_lee

    ringa_lee2017-04-11 10:22:54

    用 Auth::guard(...) , 官方文档讲的很清楚。这里也有个中文示范,可以参考下 https://phphub.org/topics/2777

    官方是默认使用 Auth::guard 来获取当前的 auth 配置(是 adminUser 还是 user,是 session 登录机制还是 token 机制,等相关)。

    还有一种是在运行时改变默认的 guard,我的项目都是这么弄的。首先配置 config/auth.php,然后在 AppServiceProvider 里动态改变 config/authdefaults 值。

    比如默认的auth配置是:

    'defaults' => [
            'guard' => 'web',
            'passwords' => 'users',
        ],

    默认使用 web guard:session机制,网站上用的。

    然后在 AppServiceProvider 的 register 方法中,根据受访域名或url的前缀判断当前的 request 是要访问PC网页还是管理后台还是JSON Api,并设置相应的 auth defaults:

    if ($this->app['request']->is('admin/*')) {
        config('auth.defaults', [
            'guard' => 'admin',
            'passwords' => 'admin_users',
        ]);
    } else if (request_is_api()) {
        //...
    }

    这样动态配置后,在代码中都是直接使用 Auth 了,比如 Auth::user() 在后台代码中就是当前管理员在网站中就是当前登录的普通用户。如果要在管理员中访问用户auth(尽管一般不会这么做的), 则使用 Auth::guard('web)->user()`

    reply
    0
  • Cancelreply