Lomkit / laravel-rest-api

Generate Api in seconds
https://laravel-rest-api.lomkit.com/
MIT License
297 stars 18 forks source link

Fetching user owned models always returns all models #122

Closed CS76 closed 1 week ago

CS76 commented 2 weeks ago

Description

Trying to fetch all posts owned by a user or a specific post

POST: /posts/search

{
  "search": {
    "filters": [
        {
          "field": "user_id", "operator": ">", "value": 0  // "value": 24
        }
    ],
    "gates": ["view"],
    "page": 1,
    "limit": 10
  }
}

Here is a section of the Post Policy:

    /**
     * Determine whether the user can view any models.
     */
    public function viewAny(User $user): bool
    {
        return true;
    }

    /**
     * Determine whether the user can view any models.
     */
    public function viewAll(User $user): bool
    {
        return $user->can('view_any_role');
    }

    /**
     * Determine whether the user can view the model.
     */
    public function view(User $user, Post $post): bool
    {
        return $user->is_owner($post);
    }

Apparently:

Returning true with viewAny in policy, returns all posts irrespective of owner (can also retrieve specific posts owned by other users)

Returning false with viewAny, always returns unauthorised error.

I am kind of bit lost here, any help / pointers on "how to fetch the list of posts owned by the user" is much appreciated :)

Many thanks in advance.

CS76 commented 1 week ago

Update: I was able to extend the search query

    /**
     * Build a query for searching resource.
     *
     * @return \Illuminate\Contracts\Database\Eloquent\Builder
     */
    public function searchQuery(\Lomkit\Rest\Http\Requests\RestRequest $request, \Illuminate\Contracts\Database\Eloquent\Builder $query)
    {
        $user = Auth::user();

        return $query->where(function ($query) use ($user) {
            $query->whereHas('owner', function ($q) use ($user) {
                $q->where('user_id', $user->id);
            })->orWhereHas('users', function ($q) use ($user) {
                $q->where('user_id', $user->id);
            });
        });
    }

to restrict the results, but is there an elegant way of using policies (other than "viewAny") to restrict the search only to user-owned models? This is also the case with fetching relations

GautierDele commented 1 week ago

This is related to Laravel and would be counter performant

You did it the good way by extending the search query