Применение областей паспорта условно к методам ресурсов api - PullRequest
0 голосов
/ 27 мая 2020

Я использую токен личного доступа паспорта для защиты своего API. Вот некоторые из фрагментов кода.

// api.php
Route::apiResource('categories', 'CategoryController');

AuthServiceProvider. php

public function boot()
    {
        $this->registerPolicies();

        //scopes 
        Passport::tokensCan([
            'admin' => 'Perform every action',
            'user' => 'Perform only normal user actions',
        ]);

        // passport routes
        Passport::routes();
        //
    }

CategoryController. php

class CategoryController extends Controller
{
    function __construct()
    {
        $this->middleware('api:auth', ['scopes: admin']);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {   
        return CategoryResource::collection(Category::all()); 
    }
    ...

Как видите, я использовали административную область, доступную только администраторам. Но проблема в том, что модель категорий может редактироваться или обновляться только областью администратора и может быть доступна как администратору, так и пользователю. Что может быть лучшим подходом к решению этой проблемы?

1 Ответ

0 голосов
/ 04 июня 2020

Одно из решений, которое сработало для меня, - я использовал промежуточное ПО два раза с разными областями действия.

class CategoryController extends Controller
{
    function __construct()
    {
        $this->middleware('api:auth', ['scopes: admin'])->except(['index']);
        $this->middleware('api:auth', ['scopes: user'])->only(['index']);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {   
        return CategoryResource::collection(Category::all()); 
    }
    ...
...