GithubHelp home page GithubHelp logo

josephsilber / bouncer Goto Github PK

View Code? Open in Web Editor NEW
3.4K 88.0 328.0 2.95 MB

Laravel Eloquent roles and abilities.

License: MIT License

PHP 100.00%
laravel authorization eloquent php security permissions auth roles acl multitenancy

bouncer's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bouncer's Issues

How can we help Bouncer get to 1.0?

Hello!

Do you have a checklist of features or ideas that need to be hashed out before you're comfortable tagging a 1.0 release that anyone might be able to help with?

I want to start contributing to OSS and Bouncer might be a good place to start.

Abilities vs Permissions

I understand that the term ability sounds better and its more friendly than permission, but I find it confusing.
The terms mean different things, for example, a user may have the ability to delete a post, but not the permission. Users can delete posts, but not all of them have permission to do it. I think it's clear that the ability to do something does not implies the permission to do it.

I see there is already a fork of this repo that fixes but I wanted to point it out, maybe we can have this merged.
Thanks.

Idea.

What if this package support a function to remove all the roles for a givin user?

FatalErrorException after upgrading to Laravel 5.2.19

After upgrading to Laravel 5.2.19 Bouncer start returning FatalErrorException while trying to run methods Bouncer::denies('something') or Bouncer::allows('something').

Class name must be a valid object or a string
Symfony\Component\Debug\Exception\FatalErrorException
…/­vendor/­silber/­bouncer/­src/­Clipboard.php116

Probably problem comes from changes in Laravel file src/Illuminate/Auth/Access/Gate.php
laravel/framework@416cbab

Policies usage

Is your package supporting Laravel Policies in any way?
Because I've already got a policies with some complex logic like checks for the groups membership subscriptions state and it's type and etc or it suppose that application should grant an abilities for the user on groups joining\leaving and so on?

Clipboard closure arguments in v0.1.3

@can('user-edit', $user)
    <a href="#" class="edit">Edit user</a>
@endcan

Argument 3 passed to Silber\Bouncer\Clipboard::Silber\Bouncer{closure}() must be of the type array, object given.

Started to throw this exception since v0.1.3.

How should wildcards work?

I'm currently working on allowing wildcard abilities. Here's how it works:

Bouncer::allow($user)->to('*');

Bouncer::allows('*'); // true
Bouncer::allows('ban-users'); // true

You can also allow all actions on a model:

Bouncer::allow($user)->to('*', $post);

Bouncer::allows('delete', $post); // true
Bouncer::allows('*', $post); // true

Bouncer::allows('ban-users'); // false
Bouncer::allows('*'); // false

You can also allow a specific action on all models:

Bouncer::allow($user)->to('create', '*');

Bouncer::allows('create', User::class); // true
Bouncer::allows('create', Post::class); // true

Bouncer::allows('edit', Post::class); // false
Bouncer::allows('create'); // false

So far so good. What I'm not sure about is the following:

Bouncer::allow($user)->to('*');

Bouncer::allows('view-dashboard'); // true

Bouncer::allows('delete', $user); // false

As you can see, a wildcard ability does not allow model abilities. To also allow model abilities you need two wildcards:

Bouncer::allow($user)->to('*', '*');

Bouncer::allows('view-dashboard'); // true
Bouncer::allows('delete', $user); // true

All of this is already implemented. Now onto the question:

Which one of these two makes more sense?

  1. A single wildcard only allows simple abilities. Model abilities requires double wildcards.
  2. There's no point in ever only allowing a user all simple abilities. Make a single wildcard allow everything.

Option 1 is the way it works now.

Thoughts?

Seeding error in AppServiceProvider

Doing the following in AppServiceProvider.php (boot method):

Bouncer::seeder(function () {
Bouncer::allow('admin')->to(['ban-users', 'delete-posts']);
Bouncer::allow('editor')->to('delete-posts');
});

Gives;

Non-static method Silber\Bouncer\Bouncer::seeder() should not be called statically

Unsure what I am missing.

Problem when using Bouncer::cache()

I've followed the instructions outlined in the readme doc and everything is working properly with Bouncer except the caching functionality.

As soon as I added the following to my AppServiceProvider.php's boot() function

Bouncer::cache()

I got the following error

  [Illuminate\Contracts\Container\BindingResolutionException]
  Target [Illuminate\Contracts\Cache\Store] is not instantiable.

Note: I also set the package up to use Facades and added a

use Bouncer;

to the top of my AppServiceProvider.php file

and I have already setup my caching using the redis driver and from everything I can tell, its working correctly.

Any help would be appreciated!

error

After i installed the package i get:

Non-static method Silber\Bouncer\Bouncer::cache() should not be called statically, assuming $this from incompatible context

i followed the readme.

Can someone help me

Primary Keys and Unique Keys

Hi again, a database schema question this time.

I see in the migration file that a UNIQUE index is added to the relational tables user_roles, user_abilities and role_abilities.

I think this UNIQUE index is not needed because the tables already have a composite primary key.

Let me explain a bit more by showing the migration result for user_roles:

PRIMARY KEY    (role_id, user_id)
UNIQUE         (role_id, user_id)
FOREIGN KEY    (role_id)
FOREIGN KEY    (user_id)

As you can see the PRIMARY KEY already makes role_id and user_id combination unique, so there is no need to do it again with a UNIQUE key.

Don't assume table names

Is it possible to move relationship table names to a config file?
This can prevent name collisions and also allow to maintain the same naming conventions used for database tables in an app.

Documentation part 3

In the docs it says;

  1. Add the bouncer's trait to your user model:
    use Silber\Bouncer\Database\HasRolesAndAbilities;

class User extends Model
{
use HasRolesAndAbilities;
}

Clarifying;

I would like to suggest that this needs clarification.
If I understand correctly then "use HasRolesAndAbilities;" goes to app/User.php.

app/User.php looks totally different from that example - Take a look: https://github.com/laravel/laravel/blob/master/app/User.php

Entity type / Model type

Having the ability to easily specify an entity type and a entity id is awesome!

Bouncer::allow($user)->to('edit', Post::class);
Bouncer::allow($user)->to('edit', $post);

The entity class name is saved as a string in the entity_type column. This is simple and straightforward but what do you thing about moving this column to its own table?

Pros:

  • Database normalization.
  • Easy to change the entity class name without touching the abilities table.

Cons:

  • Additional table relationship to manage.

Confused

I noticed that you added the ability to edit a single item ("post" in your examples) but I am not sure how I would use it.

Using a typical "forum" example, I have 3 forums : general, specific, about. I want General-Admins to be able to edit/delete anything in General or Specifc. But I also have Specific-Admins and About-Admins.

Using the ability to edit single items, I can allow "self" to edit their own posts but how could I use the system to allow General-Admins, Specific Admins and About-Admins to have the ability to moderate any items under their forums(With General-Admins getting access to two forums)?

With the "model" permissions I could just create 3 rules (i.e. Bouncer::allow('General-Admin')->to('mod-general-forum');) for those roles...but I was just wondering how/if that would work with item specific ablities like Bouncer::allow($user)->to('edit', $general-forum-post); ? Can't seem to wrap my head around a way to do that using Bouncer. (Great product btw)

Blade templates

Do you have directives to use in blade templates? or it isn't necessary
For example:

@role('admin')
    <p>I'm an admin</p>
@endrole
@permission('create-user')
    <p>I can create users.</p>
@endpermission
@ability('admin,owner', 'create-user,edit-user')
    <p>Edit data</p>
@endability

Deny abilities

There should be an option to deny an ability to a user. That way, a user that belongs to a Role with X permissions, could have a specific permission(s) denied from that X without the need to fork the Role.

Best regards,
António Fernandes

Get role's abilities list

Hi there, i found that package usefull, but there is anyway to get role's abilities list?

For example :

foreach($roles as $role) {
     $role->name; // outputs Admin
     $role->getAbilities(); // outputs all admin permissions
}

Can't retract abilities or view abilities

Hello again,

I just started a fresh project with laravel 5.2, using the latest version of Bouncer. I noticed that when I try to retract an ability directly from a user, it always returns false, and the user DOES have the ability.

Here's a test I did on artisan tinker:

>>> $user = App\User::find(1)
=> App\User {#718
>>> Bouncer::allow($user)->to('access_admin_cp')
=> true
>>> Bouncer::retract('access_admin_cp')->from($user)
=> false
>>> 

And, if I try to check the user's abilities, it doesn't return an array/collection of abilities, it returns a BelongsToMany relation:

>>> $user = App\User::find(1)
=> App\User {#718
>>> Bouncer::allow($user)->to('access_admin_cp')
=> true
>>> Bouncer::refreshFor($user)
=> Silber\Bouncer\Bouncer {#713}
>>> $user->abilities()
=> Illuminate\Database\Eloquent\Relations\BelongsToMany {#707}

Not sure if the refresh was necessary, but anyway...

What am I doing wrong here?

Regards!

Middleware

What do you think about middleware?

Something like this for roles:

Route::get('post.create', [
    'as' => 'post.create',
    'middleware' => 'role:admin,editor',
    'uses' => 'PostController@create',
]);

And one more for an ability:

Route::get('post.create', [
    'as' => 'post.create',
    'middleware' => 'ability:create-post',
    'uses' => 'PostController@create',
]);

Publishing migrations on dev-polymorphic

when I try to publish migrations on dev-polymorphic

 php artisan vendor:publish --provider="Silber\Bouncer\BouncerServiceProvider" --tag="migrations"
Nothing to publish for tag [migrations].

Change requests

I have a couple requests for your fantastic library.

  1. Make it work for sites that already have a users table and have the code check to see what the user table primary index name is. Our users table has a primary key of user_id which breaks Bouncer. The migrations don't work right and I had to modify the AssignRole.php Conductors file in the assignRole function to work with it. Would be nice if it was more universal.
  2. Right now you have functions for checking to see if a user is in a particular role. But I don't see an option for checking to see if a user has a particular ability. I can fetch all abilities and loop, but something like this would be nice:
$check = $user->can('ban-users');

Thanks so much!

Laravel 5.2

Good day, I am getting
QueryException in Connection.php line 669:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (ascend.user_roles, CONSTRAINT user_roles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into user_roles (role_id, user_id) values (4, admin))

on this test code

    $user = Auth::user();
    Bouncer::assign($user)->to('admin');

Seeding is using
Bouncer::seeder(function () {
// Owners can
Bouncer::allow('owner')->to([
'create-user',
'delete-user',
'promote-admin',
'promote-create-content',
'create-content',
'update-h5p'
]);
// Admins can
Bouncer::allow('admin')->to([
'create-user',
'delete-user',
'promote-create-content',
'update-h5p'
]);
// Content Creators Can
Bouncer::allow('content-creator')->to([
'create-content'
]);

Any suggestions?

getAbilities function not working

When using $user->getAbilities() method the following error is returned:

BadMethodCallException in Builder.php line 2117:
Call to undefined method Illuminate\Database\Query\Builder::getAbilities()

The database is properly seeded and the User has admin role.

The seeder:

Bouncer::seeder(function () {
    Bouncer::allow('admin')->to(['ban-users', 'update-post', 'delete-post']);
    Bouncer::allow('editor')->to(['delete-post', 'moderate-post', 'create-post']);
    Bouncer::allow('member')->to(['create-post']);
});
Bouncer::assign('admin')->to(User::findOrFail(1));

Add method in Role model

Hello,

Would it be possible to have a scope method added to the Role model to return a list of available roles? Something like this for example

    public function scopeOrderedList($query)
    {
        return $query->orderBy('name')->lists('name', 'id');
    }

For example, this would be useful when building select boxes for someone to choose a role from.

$roles = Role::orderedList()->toArray();

Then pass that into a view.

Thanks

Get user's roles list. Question

There is a way to get user's roles like $user->getAbilities(); but $user->getRoles(); and return all roles that user have?

Polymorphic

Hey,

Has the polymorphic branch been merged with master? I switched to polymorphic a while ago to test it after Joseph requested some people to try it.

App\User is hard coded

I've noticed that you don't seem to have a config file that would allow us to change the model we are using. I have all my models in App\Models, so I'm using App\Models\User as my User Model. That causes an error because Ability.php, Models.php, Role.php and BouncerServiceProvider.php all hard code the App\User;

Perhaps the User Model should be type-hinted ?

Problem with multiple databases

Hello!

Thank you for this awesome project, it makes handling roles and abilities a painless task.

Apparently Bouncer does not support multiple databases...

For my project I have my users table on a different database, and trust me, I have good reasons to do that.

The problem is: when I try to assign a role to a user, I get a QueryException, saying that the users table was not found.

I modified the migrations to set the foreign keys correctly, but I think it would be a bad practice to modify the vendor files and fix the relations in the classes...

Is there any way you could help me here?

Thank you!

this dont work with php artisan app:name

rename my application and install the package, run the migrations I am having the error App\User not found, fix this good series, for those who use app: name.

Thanks

How to approach customizing table names?

Hello!

I was browsing this repository and thinking about how I can integrate the package into a project I'm working on. A thought that came to mind is how to approach customizing table names. I need to namespace my tables (projectname__abilities) in my case.

I was wondering what your thoughts on this might be.

Thanks!

Migration Pitfalls

Dropping the user-table in the migration's down-function is risky. The users-table is included in a clean Laravel install, so most likely it should be left alone.

The keys you use inside the pivot-tables, aren't really keys at all. They're just ints. These should be indeces and foreign keys, referencing the foreign table.

On a nitpickety note, the convention in Laravel, I believe, is to use the table-names, singular, in alphabetical order, as names for pivot-tables. I.e. role_user, ability_role, ability_user.

I also found a typo, which seems to be significant. The HasRolesAndAbilities trait, has this:

public function abilities()
{
    return $this->belongsToMany(Ability::class, 'user_Abilities'); // this should be user_abilities
}

Thanks for this package :-)

[Symfony\Component\Debug\Exception\FatalErrorException] Class 'App\User' not found

Using laravel 5.1,
some classes in your Database namespace expect App\User to be present in my installation.

However, my app namespace is different and my models were put in to a folder called 'Models' under the app namespace.

I see that you're just using it as a reference to load the actual user model class. Wouldn't it be better to just use a string instead of a reference.

A lot of applications won't have it present in the App namespace and/or have it available at the top of that namespace.

Don't assume model App\User

Model App\User is hard-coded in various classes:

Silber\Bouncer\Database\Models
Silber\Bouncer\Database\Ability
Silber\Bouncer\Database\Role

It is possible to make it configurable?

ErrorException in Clipboard.php line 30: Missing argument 3 for Silber\Bouncer\Clipboard::Silber\Bouncer\{closure}()

Hi Joseph,

Still using Bouncer in my project, and found it very useful :)

I've just tried moving from 0.1.2 to 0.1.6 and come across an issue with the clipboard - it looks to be related to the changes for the Gate.

It appears when I do:

    $user->can('do-something');

It looks like the required $arguments var is lost in the Gate processing during an array merge since it is an empty array.

I think a simple fix is to make the closure signature:

  function ($user, $ability, $arguments = [], $additional = null) {
      ...
  }

I'll happily put together a pull request if you'd like.

Cheers,

Keoghan

Class not found when trying to add wildcards

Hi

I get an

Fatal error: Class '*' not found

error when I try to add add wildcard abilities.

This works:

Bouncer::allow('admin')->to('*');

This does not:

Bouncer::allow('admin')->to('*', '*');

I followed the examples as discussed here:
#56

Not sure if I'm missing something. This is a stock standard installation via composer on a Laravel 5.2 project.

Any help would be appreciated.

Thanks for an awesome package btw. :-)

Non-static method is() Execption

I have a basic Problem with checking if a user has a role:

If I do it in routes.php it works:

        $user = User::find(3);
        Bouncer::is($user)->a('admin');

If i do it in the CompanyController, I get this Error:

at HandleExceptions->handleError('8192', 'Non-static method Silber\Bouncer\Bouncer::is() should not be called statically, assuming $this from incompatible context', '/home/vagrant/Code/torebuild1/app/Http/Controllers/CompanyController.php', '112', array('id' => '3', 'user' => object(User))) in CompanyController.php line 112

Is there a Issue or am I doing something completely wrong?

Laravel 5.2 Trait 'App\HasRolesAndAbilities' not found

I've set up a new Laravel 5.2 and just installed bouncer, but when I want to do the migrations I get the error:

  [Symfony\Component\Debug\Exception\FatalErrorException]  
  Trait 'App\HasRolesAndAbilities' not found               

Probably I have to do something else in the User model, because the installation docu seems not to be updated to Laravel 5.2.. it says to change the usermodel to:

use Silber\Bouncer\Database\HasRolesAndAbilities;

class User extends Model
{
    use HasRolesAndAbilities;
}

but in Laravel 5.2 the user model extends the Authenticable class:

class User extends Authenticatable
{

I'm using "silber/bouncer": "^0.1.2"

Thanks for help.

Unsure if Issue... But confused...

So, I created the basic roles for myself... here I will use two...

Bouncer::allow('role1')->to('create', App\User::class);
Bouncer::allow('role1')->to('delete', App\User::class);

Bouncer::allow('role2')->to('create', App\User::class);

Ok... so easy enough?

I created two users...
$user1 = new User(); // Created and Saved
$user2 = new User(); // Created and Saved

$user1->assign('role1');
$user2->assign('role2');

// Again, super easy...

$user1->can('create', App\User::class); // FAILS...

no abilities for this user were set, however they were set through the roles... but through roles are not checked if the user has this ability, it only checks directly...

so even though user belongs to ROLE: role1, which has the 'create' and 'delete' roles, it fails to find it with ->can()... unless I specify that $user1->is('admin') which I really don't want to do...

Thoughts? maybe I am missing something...

Fatal error: Call to a member function intersect() on boolean

Im getting error when i
$user->is('admin')
Fatal error: Call to a member function intersect() on boolean

This Happens when i included it in
AppServiceProvider Boot Function

\Bouncer::cache();

I running it on homestead, is this normal or not?

Seeding with DatabaseSeeder

First thing is first: Great work, thank you.

I am trying to seed the database with my global seeder. Here is my setup:

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Model::unguard();

        $this->call(UsersTableSeeder::class);
        $this->call(WorksTableSeeder::class);
        $this->call(BouncerTableSeeder::class);

        Model::reguard();
    }
}

Here is `BouncerTableSeeder.php':

use Illuminate\Database\Seeder;
use Silber\Bouncer;

class BouncerTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Bouncer::seeder(function () {
            Bouncer::allow('admin')->to(['ban-users', 'delete-posts']);
            Bouncer::allow('editor')->to('delete-posts');
        });
    }
}

I am doing this because I am mostly using the following command in development.

php artisan migrate:refresh --seed

However it throws error:

[Symfony\Component\Debug\Exception\FatalErrorException]  
  Class 'Silber\Bouncer' not found 

If I use use Bouncer; it throws error:

[ErrorException]                                                  
  The use statement with non-compound name 'Bouncer' has no effect 

How should it be? Thanks.

CachedClipboard FileStore::sear undefined

I ran into this issue building my user-management system. I don't know if it's relevant, but $user in this particular context, is not necessarily the logged in user; it could be another user you're editing through the management GUI.

Here's what happens:

FatalErrorException in CachedClipboard.php line 96:
Call to undefined method Illuminate\Cache\FileStore::sear()

in CachedClipboard.php line 96
at FatalErrorException->__construct() in HandleExceptions.php line 133
at HandleExceptions->fatalExceptionFromError() in HandleExceptions.php line 118
at HandleExceptions->handleShutdown() in HandleExceptions.php line 0
at CachedClipboard->getRoles() in Clipboard.php line 80
at Clipboard->checkRole() in HasRolesAndAbilities.php line 112
at User->is() in ed94e7a189d21f20c12b5f8b14253ae1ea173343.php line 50
in PhpEngine.php line 42
at PhpEngine->evaluatePath() in CompilerEngine.php line 59
at CompilerEngine->get() in View.php line 147
at View->getContents() in View.php line 118
at View->renderContents() in View.php line 83
(...)

It happens when I call $user->is('someRole') from a view. Now, I may be using the is()-function wrong in this case, but it seems to work just fine if I don't use cache, that is, if I don't ever call Bouncer::cache().

I'm using file as cache-driver, obviously, Laravel 5.2 and latest Bouncer.

column name entity_id and entity _type use?

I see abilities have extra field called entity_id and entity_type

What is the purpose of that extra column?

my hint is it is a polymorphic relationship.

but what would use the entity?

can you explain it thanks

fatal error after update

I've done the update to Laravel 5.2 which was not easy. But now I get the following error:

PHP Fatal error:  Using $this when not in object context in /Users/emergingdzns/Cloud Drive/Sites/Symplur/signals/vendor/silber/bouncer/src/Database/Models.php on line 64

Fortunately I did this on a test branch though because we can't load the site at all now.

I'm not sure what could cause this conflict. Any ideas? Any particular code you'd like me to share?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.