How to use Authority package for Laravel

127 views Asked by At

After some searching, I succesfully installed the Authority-l4 package to use for my Laravel project. The docs are clear but small (not much info/examples). This is what my config file looks like atm:

return array[

    'initialize' => function($authority) {
        $user = $authority->getCurrentUser();

        $authority->addAlias('manage', ['create', 'read', 'update', 'delete']);

        if($user->hasRole('admin')) {
            //Admin can manage all resources
            $authority->allow('manage', 'all');
        }

        // User can manage his own post
        Authority::allow('manage', 'User', function($self, $user){
            return $self->getCurrentUser()->id === $user->id;
        });

        // User can manage his own post
        Authority::allow('manage', 'Post', function($self, $post){
            return $self->getCurrentUser()->id === $post->id;
        });
    }

];

I have some questions about this:

  1. How to add a role to a user? hasRole() exists, why not setRole()?
  2. I noticed nothing gets saved into the database, isn't this better?
  3. How do I use my database with Authority? Could someone give me a head start, I've been strugling four hours now.
  4. In some articles they say that the class Role should be changed to have many permissions instead of a user having many permissions, isn't this better?

Probably I'm thinking way to difficult about this package, searching the internet doesn't help either. Any help is appreciated!

1

There are 1 answers

0
machuga On

I'm the author of Authority, and I maintain Authority-l4 though it was written primarily by Conar Welsh.

  1. Since roles, as defined in the package, are just an Eloquent relation so you can simply add them like any other relation in Eloquent.
  2. I have no idea what you're asking here, can you rephrase?
  3. Can you elaborate on the question beyond what's in the readme (the part just above General Usage)?
  4. Probably - either works. You don't need to use this structure to use Authority-l4. It's just an optional structure that you are 100% free to setup as you'd like. I personally don't use this at all and just use the Authority facade that it generates. Most of my permissions aren't stored in the DB though so that plays a factor.

The idea behind Authority is that it is implementation agnostic. It genuinely does not care where you store your data, you just need to tell authority what to do with your rules. Reading the section of the readme referenced above and the readme on the Authority core repo should be able to give you a general idea of how it expects information to be loaded - anything beyond that is up to your discretion.