7

因此,我正在阅读有关使用 laravel 策略授予对我的应用程序资源的权限的信息,但是尽管我遵循了教程,但那里似乎存在问题。

我有一个无法通过 HTTP 请求创建的用户模型,除非其他用户具有“管理员”或“经纪人”的委托角色。我理解并成功使其适用于索引用户等其他操作的内容如下:

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

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() 的参数尝试了多种变体,但无法让它像索引操作一样工作

4

1 回答 1

5

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

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

缺少论据User $user

也许这就是问题的原因。

于 2016-10-29T12:32:43.833 回答