Tarasovych
Tarasovych

Reputation: 2398

Return additional column if user is authorized - API

I have an Laravel-base API which handles both client and admin endpoints (there are two sites like domain.com and admin.domain.com). My auth is based on cookie, which domain is <.domain.com>. As you can see, this cookie is acceptable for both domains.
I use Eloquent Api Resources for transformation data layer. Is my when() route check here safe and right?

public function toArray($request)
{
    return [
        'name' => $this->name,
        'created_at' => (string)$this->created_at,
        'status' => $this->when($request->route()->getName() === 'api.admin.users.index', $this->status)
    ];
}

Before I used $this->when(Auth::check(), ...), but because my auth cookie is acceptable for client site too, unneeded data might be fetched. My route:

Route::group(['prefix' => 'admin', 'as' => 'api.admin.', 'middleware' => 'auth:api'], function () {
    Route::resource('users', ...);
});

If user is not authorized, he wouldn't get data because of middleware. At the same time, authorized used (who has non-expired cookie) wouldn't get unneded data while being on client site.
Thank you!

Upvotes: 0

Views: 29

Answers (1)

Namoshek
Namoshek

Reputation: 6544

I think your approach is fine. The route name is something internal and the user cannot tinker with it. You could improve it by using \Route::is('api.admin.*') though. It would then work for all of your admin API routes.

Upvotes: 1

Related Questions