1

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.

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.

In the end the user should only be able to see himself or the resources he created (which are linked through a belongsTo field).

I appreciate any help, thank you!

1 Answer 1

1

I just figured it out by myself, I was too confused while working in the 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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This does not work anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.