简体   繁体   English

Laravel Nova 限制资源视图

[英]Laravel Nova Restrict View of Resource

I have the following problem:我有以下问题:

Users (that are not admins) can view a resource (for example my resource documents) if they access it directly via a link.用户(不是管理员)可以查看资源(例如我的资源文档),如果他们通过链接直接访问它。

I've modified the indexquery so that they cannnot see the resource on the index view but they also should get a 403 when they try to access it directly via an url.我已经修改了 indexquery,以便他们无法在索引视图上看到资源,但是当他们尝试通过 url 直接访问它时,他们也应该得到 403。

I've already created a policy for my documents resource and I know that I somehow have to modify the view function.我已经为我的文档资源创建了一个策略,我知道我必须以某种方式修改视图函数。

  public function view(User $user, User $model){
    return true;
    // return canViewOwn($user); 
  }

I've tried creating a custom function in the documents model like so:我试过在文档模型中创建一个自定义函数,如下所示:

  public function canViewOwn($user){
    // This should test whether the current requested resource has the same user Id 
    //  as the currently logged in user

    if($user->id == auth()->user()->id) {
        return true;
    }
 }

My resource has a BelongsTo field which accepts the user id, but I dont know how to check for that in the resource model function.我的资源有一个 BelongsTo 字段,它接受用户 ID,但我不知道如何在资源模型函数中检查它。

In the end the user should only be able to see himself or the resources he created (which are linked through a belongsTo field).最后,用户应该只能看到他自己或他创建的资源(通过belongsTo 字段链接)。

I appreciate any help, thank you!我感谢任何帮助,谢谢!

I just figured it out by myself, I was too confused while working in the UserPolicy:我只是自己弄明白了,在UserPolicy中工作时我太困惑了:

It was just:这只是:

public function view(User $user, User $model){
    if($user->role === 'admin'){
        return true;
    } 
    return $model->id == $user->id;
}

And for any other Resource I used:对于我使用的任何其他资源:

public function view(User $user, Document $document){
    if($user->role === 'admin'){
        return true;
     } 
     return $document->user_id == $user->id;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM