Laravel策略不断允许用户

时间:2020-06-08 06:25:13

标签: php laravel policy

我在App\Policies\UserPolicy下为UserController创建了一个用户策略,以仅允许ID为2的用户访问。但是,现在即使ID为1的用户也可以访问而不会引发任何错误。

/**
 * Determine whether the user can create models.
 *
 * @param  \App\Models\Auth\User  $user
 * @return mixed
 */
public function create(User $user)
{
    return $user->id === 2 ? Response::allow()
    : Response::deny('You do not own this users.');;
}

路线

Route::get('user/createProfile' , [UserController::class, 'showCreateProfileForm'])->name('user.profile.createProfile');

控制器UserController.php

public function showCreateProfileForm()
{
    $user = Auth::user();
    $this->authorize('create' , $user);
    return view('backend.auth.user.profile.create');
}

提供商AuthServiceProvider.php

<?php

namespace App\Providers;

use Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use App\Models\Auth\User;
use App\Policies\UserPolicy;

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */ 
    protected $policies = [
        User::class => UserPolicy::class,
    ];

    /**
     * Register any authentication / authorization services.
     */
    public function boot()
    {
        $this->registerPolicies();

    }
}

当我从$this->authorize('create' , $user);返回UserController@showCreateProfileForm时,它一直在返回

{
  "allowed": true,
  "message": null,
  "code": null
}

1 个答案:

答案 0 :(得分:0)

只是发现AuthServiceProvider @ boot中有此方法

Gate::before(function ($user, $ability) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});

因此,我所有的授权一直失败。

解决方案将其更改为

Gate::after(function ($user, $ability) {
    if ($user->isSuperAdmin()) {
        return true;
    }
});

谢谢