Tuesday, February 28, 2017

Laravel 5.2 custom user permission check

I would like to do a permission check that will disallow users from accessing certain pages and buttons if they do not have permission. In my database, I have a table for users, permissions and then a permission_user table to assign permissions for each user.

Now, I have pages where a table is displayed with all a summary of the data and there are a set of buttons there (view, edit etc.) and some users can't do all of these so I want these buttons to be invisible/disabled. And I don't want them to access the restricted pages linked with these buttons if they type it in the URL (e.g. public/admin/edit/id).

Here are the currently available permissions

  PermissionID  PermissionName
        1            View
        2            Add
        3            Edit
        4            Delete

Now in my permissions_user table it is like this

   PermissionID   AccountID
        1             2

Here is a piece of my controller

public function showDetails($action, $id)
    {
        return view('pages.admin.form_details', ['action' => $action, 'id' => $id]);
    }

This example function will show the details page and return action (string which is either view or edit) and then the checking for display of the view or edit page is done in my blade. If possible, I want to do the checking all at once (Like how you check in every page if user is logged in or not through a middleware). I actually tried zizaco entrust, but I do not understand how to implement it and ended up removing it from my project.

I've been thinking of doing something like this in my show functions for each page controllers.

if($action == "edit)
//check if edit permission exists for the authenticated user. if not abort and show error page.

I think it's inefficient and repetitive to do this. Would there be a better solution? Or maybe a package that I could integrate easier?




via Friency Fernandez

Advertisement