Search code examples
phplaravellaravel-passport

Laravel Passport


I am currently looking at building SaaS construction management tool. What I was wondering is if I used laravel passport for the api token how can I assign roles to users For example:

SuperAdmin: Can create projects | Can create new users and assign roles to user.

Admin: Can view projects.

Because I would like to be able to hide elements on my front end based upon a users permissions.

For example if I did a traditional laravel app I could use entrust and use blade directives @role('admin') to show elements based on a users permission type.


Solution

  • You can use Policies and Gates: https://laravel.com/docs/5.4/authorization

    Then it becomes as simple as

    $user = Auth::guard('api');
    if ($user->can('create', Post::class)) {
        // Do something
    }
    

    To hide/show stuff in the frontend, when you get the user, you get their permissions as well

    $user = Auth::guard('api');
    $user->isAdmin = $user->can('create', Post::class); //returns true or false
    

    In your frontend you show/hide stuff with that. E.g: using angular

    <li ng-if="vm.user.isAdmin">Admin</li>