用户授权
HDCMS / 更新于8个月前

用户授权

[TOC]

注册服务

artisan module:make-provider AuthServiceProvider Shop

修改内容如下:

use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Modules\Shop\Entities\ShopModule;
use Modules\Shop\Policies\ShopModulePolicy;
class AuthServiceProvider extends AuthServiceProvider
{
    protected $defer = false;
    protected $policies = [
        ShopModule::class => ShopModulePolicy::class,
    ];
    public function register()
    {
        $this->registerPolicies();
    }

module.json 文件中注册服务提供者如下:

"providers": [
    "Modules\\Shop\\Providers\\ShopServiceProvider",
    "Modules\\Shop\\Providers\\AuthServiceProvider"
]

授权类定义

下面是创建 ShopModule 模型的授权类

artisan module:make-policy ShopModulePolicy Shop

授权类部分代码如下,根据需要自行添加授权方法:

class ShopModulePolicy
{
    public function update(User $user, ShopModule $model)
    {
        //is_site_manage 函数判断是当前用户是否为管理员或操作员
        return $user['id'] == $model['user_id'] || is_site_manage();
    }
    public function delete(User $user,ShopModule $model){}
    public function create(User $user){}
}

修改控制器

控制器引入trait Illuminate\Foundation\Auth\Access\AuthorizesRequests 示例如下:

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
...
class ModuleController extends Controller
{
    //引入请求验证Trait
    use AuthorizesRequests;

    public function edit(ShopModel $model)
    {
        $this->authorize('update', $module);
    }
}
我们的使命:传播互联网前沿技术,帮助更多的人实现梦想
Copyright © 2010-2018 houdunren.com All Rights Reserved 京ICP备12048441号-3
: 010-86467608 : 2300071698@qq.com
编码: 海豚日记