A
A
anlamas2017-10-03 10:19:19
Software design
anlamas, 2017-10-03 10:19:19

What is the best way to restrict access by roles? At the route and/or controller level?

Hello. I work with Laravel. I am using laravel-permission . (for information)
Advise how best to restrict access?
Now I restrict access in routes through middleware. BUT! More often you have to divide an entity into a group of routes, for example, for a simple CRUD.

Route::group(['middleware' => ['auth', 'role:author']], function () {
    ...
    Route::post('/posts/store', ['uses' => '[email protected]', 'as' => 'posts.store']);
    Route::post('/posts/{post}/update', ['uses' => '[email protected]', 'as' => 'posts.update']);
    // другие роуты только для author
    ...
}
Route::group(['middleware' => ['auth', 'role:editor']], function () {
    ...
    Route::post('/posts/{post}/update', ['uses' => '[email protected]', 'as' => 'posts.update']);
    // другие роуты только для editor
    ...
}
// Можно ведь и в контроллере(DI)

public function __construct()
{
    $this->middleware('auth');
    $this->middleware('author');
    $this->middleware('editor')->only('update');
}
// а в роуте писать
Route::resource('posts', 'PostController');

Yes, I know what is possible for each individual
Route::get('profile', '[email protected]')->middleware('auth');

For me, the controllers are more flexible. So, write your advice, how best, general practices)
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nepster-web, 2017-10-03
@anlamas

It all depends on your tasks and architecture.
laravel-permission provides you with various tools for flexible permission management: the documentation has examples for blade, for model, for controller and for millver.
In this matter, you need to rely on your architecture and on the task. For example, there are situations when it is not advisable to check access in the millver, since for complex logic it is necessary to obtain data for verification (and whether the user can edit this record at this particular time from this IP).
Also, a very big nuance depends on your architecture, for example, I use DDD and access rights are checked in UseCase in the application layer, and there is not one check, but several (whether the user can edit records at all, and then can edit a specific one).
The answer to the question will be something like this:
Using laravel-permission, you can restrict access by roles in the controller, but you need to take into account your architectural approach, SOLID principles, etc.
I’ll add from myself, most likely you have RAD development, so you don’t have to bother and check where it’s more convenient.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question