编程语言
首页 > 编程语言> > php – 使用策略this-> authorize()检查store()方法中的laravel控制器

php – 使用策略this-> authorize()检查store()方法中的laravel控制器

作者:互联网

所以我正在阅读有关使用laravel策略授予权限的应用程序资源的权限,但是虽然我遵循了教程,但似乎存在问题.

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

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

class AuthServiceProvider extends ServiceProvider {

    protected $policies = [
        'App\Model' => 'App\Policies\ModelPolicy',
        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.

也许这就是问题的原因.

标签:php,laravel,policies,authorize,entrust
来源: https://codeday.me/bug/20190706/1393495.html