SaroBeatbox
SaroBeatbox

Reputation: 63

ACL in Laravel 7 , how do it?

I am looking to implement an ACL system in a project with Laravel 7. I currently have the following structure.

Authentication (Laravel standard login) using user name from the users table.

When logging in, a JWT Token is generated and saved in the user's session.

There is an html page (20 specifically each of a type of equipment, cars, motorcycles, boats) that contains a table with data from a JSON and inserted in the table through Datatables.js.

In this table there are 2 operations (Edit, Delete Record)

I would like only certain profiles to do the editing, certain profiles to do the deletion. I thought of the following.

depending on the user's permission, the "Edit" button would be disabled (where would it be done? in CarsController inside the construct method?)

However, inactivating the button does not prevent a malicious user from performing an operation via post, delete by passing the id as a parameter in the request, for this I thought of using JWT to control the routes of exclusion, editing.

what do you think ? I am open to new suggestions.

Upvotes: 1

Views: 393

Answers (1)

PKeidel
PKeidel

Reputation: 2589

If you implemented JWT correctly this is pretty easy. Laravel does support a pollicies concept out of the box: https://laravel.com/docs/7.x/authorization#policy-methods

Basically it's a class per model with a function per action (like create, view, update, delete, ...whatever you need) and looks like this:

class PostPolicy {
    /**
     * Determine if the given post can be updated by the user.
     *
     * @param  \App\User  $user
     * @param  \App\Post  $post
     * @return bool
     */
    public function update(User $user, Post $post) {
        return $user->id === $post->user_id;
    }
}

This Policy restricts access to the Post Model. The first argument of the function is the user that is sending the request.

In your blade template you would check for the access rights and show/hide the button:

@can('update', $post)
  <button>...</button>
@endcan

And to let laravel know what policy belongs to which model you have to create a mapping in AuthServiceProvider:

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];
...

Just follow this guide https://laravel.com/docs/7.x/authorization#creating-policies

If your JWT does not work with laravel then I would recommend using laravels sanctum or passport.

Upvotes: 0

Related Questions