加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – 使用策略this-> authorize()检查store()方法中的larav

发布时间:2020-12-14 19:40:14 所属栏目:大数据 来源:网络整理
导读:所以我正在阅读有关使用laravel策略授予权限的应用程序资源的权限,但是虽然我遵循了教程,但似乎存在问题. 我有一个无法通过HTTP请求创建的用户模型,除了具有Entrust角色“Admin”或“Broker”的其他用户.我理解并成功使其适用于索引用户等其他操作的内容如下
所以我正在阅读有关使用laravel策略授予权限的应用程序资源的权限,但是虽然我遵循了教程,但似乎存在问题.

我有一个无法通过HTTP请求创建的用户模型,除了具有Entrust角色“Admin”或“Broker”的其他用户.我理解并成功使其适用于索引用户等其他操作的内容如下:

在私有$policies数组中的AuthServiceProvider.php内部,我使用UserPolicy类注册了那个User类

class AuthServiceProvider extends ServiceProvider {

    protected $policies = [
        'AppModel' => 'AppPoliciesModelPolicy',User::class => UserPolicy::class,Insured::class => InsuredPolicy::class
    ];

    public function boot(GateContract $gate)
    {
        $this->registerPolicies($gate);
    }
}

定义UserPolicy控制器类:

class UserPolicy {

    use HandlesAuthorization;

    protected $user;

    public function __construct(User $user) {
        $this->user = $user;
    }

    public function index(User $user) {
        $is_authorized = $user->hasRole('Admin');
        return $is_authorized;
    }

    public function show(User $user,User $user_res) {

        $is_authorized = ($user->id == $user_res->id);
        return $is_authorized;    
    }

    public function store() {
        $is_authorized = $user->hasRole('Admin');
        return $is_authorized;
    }
}

然后在UserController类内部,在执行关键操作之前,我使用this-> authorize()检查停止或继续,具体取决于用户的权限

class UserController extends Controller
{

    public function index()
    {
        //temporary authentication here
        $users = User::all();
        $this->authorize('index',User::class);
        return $users;
    }

    public function show($id)
    {
        $user = User::find($id);
        $this->authorize('show',$user);
        return $user;
    }

    public function store(Request $request) {


        $user = new User;
        $user->name = $request->get('name');
        $user->email = $request->get('email');
        $user->password = Hash::make($request->get('password'));

        $this->authorize('store',User::class);

        $user->save();

        return $user;

    }
}

问题是$this-> authorize()总是停止存储操作返回异常的进程:此操作未经授权.

我为authorize()的参数尝试了多种变体,并且不能像索引操作那样使它工作

解决方法

在UserPolicy :: class的store()函数中,您没有传递User模型对象:

public function store(User $user) {
   $is_authorized = $user->hasRole('Admin');
   return true;
}

缺少参数User $user.

也许这就是问题的原因.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读