Martinkovic
1 year ago
348
10
Laravel

Applying authorisation policy for nested resource

Posted 1 year ago by Martinkovic

Hi,

I'm listing answers to specific question by this route: GET api/question/{question}/answer . Currently, I am trying to apply policy that will ensure that only owner of the question can list respective answers to it.

I've managed to implement this policy by assigning it to answer model in AuthServiceProvider. However I'm wondering if it should be assigned to answer or to question model. For example there is situation when there are no answers to the question and policy authorisation is based on retrieval of question_id and respective owner_id from relations with answers, but when there is no answer, my answer policy is unable to retrieve and validate these ids and therefore throws action unauthorised exception.

If the policy will be assigned to question model there will be no such problem, however I'm not sure if it's semantically correct to assign it to question model when I want to check rights to indexing of answers and not questions.

Chunks of related code:

index method:

public function index(Question $question){
    $this->authorize('index',$question->answers()->first());

    return QuestionAnswerResource::collection($question->answers);
}

AnswerPolicy:

public function index(User $user, QuestionAnswer $answer)
    {
        $campaign = Campaign::find($answer->question->campaign_id);

        return $user->id == $campaign->user->id;
    }

Thanks!

Please sign in or create an account to participate in this conversation.