Code Monkey home page Code Monkey logo

rbac's Introduction

Laravel RBAC

Simple RBAC/ACL for Laravel 8 and more with caching permissions and permission groups for better convenience.

Installation

Install this package with composer using the following command:

composer require yaroslavmolchan/rbac

or you can add to your composer.json for Laravel 8.0

"require": {
    ...
    "yaroslavmolchan/rbac": "^2.0"
}

or if you use Laravel 5.5 use:

"require": {
    ...
    "yaroslavmolchan/rbac": "^1.0"
}

then run composer update.

Add Service Provider to providers array in config/app.php file.

'providers' => [
    ...
    /*
     * Package Service Providers...
     */
    YaroslavMolchan\Rbac\RbacServiceProvider::class,
    ...
],

Publish migration files

$ php artisan vendor:publish --provider="YaroslavMolchan\Rbac\RbacServiceProvider" --tag=migrations

And then run migrations

$ php artisan migrate

Add middleware to your app/Http/Kernel.php file.

protected $routeMiddleware = [
    ...
    'role' => \YaroslavMolchan\Rbac\Middleware\CheckRole::class,
    'permission' => \YaroslavMolchan\Rbac\Middleware\CheckPermission::class
];

Add Rbac trait to your User model

use \YaroslavMolchan\Rbac\Traits\Rbac;

class User extends Authenticatable
{
    use Rbac;
    ...
	    
}

Usage

Roles

Creating roles

use \YaroslavMolchan\Rbac\Models\Role;

$adminRole = Role::create([
    'name' => 'Administrator',
    'slug' => 'admin'
]);

$managerRole = Role::create([
    'name' => 'Manager',
    'slug' => 'manager'
]);

Attaching And Detaching Roles

You can simple attach role to user:

use App\User;

$user = User::find(1);
$user->attachRole($adminRole);
//or you can insert only id
$user->attachRole($adminRole->id);

And the same if you want to detach role:

use App\User;

$user = User::find(1);
$user->detachRole($adminRole);
//or you can insert only id
$user->detachRole($adminRole->id);

Checking for roles

You can simple check if user has role:

use App\User;

$user = User::find(1);
if ($user->hasRole('admin')) {
    
}

Permissions

Creating permissions

use \YaroslavMolchan\Rbac\Models\Permission;

$createPermission = Permission::create([
    'name' => 'Create product',
    'slug' => 'product.create'
]);

$removePermission = Permission::create([
    'name' => 'Delete product',
    'slug' => 'product.remove'
]);

Attaching And Detaching permissions

You can attach permission to role very simple:

use \YaroslavMolchan\Rbac\Models\Role;

$adminRole = Role::find(1);
$adminRole->attachPermission($createPermission);
//or you can insert only id
$adminRole->attachPermission($createPermission->id);

And the same to detach permission:

use \YaroslavMolchan\Rbac\Models\Role;

$adminRole = Role::find(1);
$adminRole->detachPermission($createPermission);
//or you can insert only id
$adminRole->detachPermission($createPermission->id);

If you want attach or detach array of permissions you can do it:

use \YaroslavMolchan\Rbac\Models\Role;

$adminRole = Role::find(1);
$adminRole->attachPermissions([$createPermission, $removePermission]);
//or you can insert only id
$adminRole->detachPermission([$createPermission->id, $removePermission->id]);
use \YaroslavMolchan\Rbac\Models\Role;

$adminRole = Role::find(1);
$adminRole->detachPermissions([$createPermission, $removePermission]);
//or you can insert only id
$adminRole->detachPermissions([$createPermission->id, $removePermission->id]);

Checking for permissions

You can simple check if user has permission:

use App\User;

$user = User::find(1);
if ($user->canDo('product.create')) {
    
}

All permissions for each role store in cache, and when you check for permission - it take information from cache, that`s why its works quickly.

Permission groups

Permission groups created for group some permissions in one main group, and then you can attach permission group to role and all permissions in this group attach to this role to. Its very useful thing.

Creating permission groups

use \YaroslavMolchan\Rbac\Models\PermissionGroup;

$productManagementPermissionGroup = PermissionGroup::create([
    'name' => 'Product management',
    'module' => 'main' // optional
]);

Attaching And Detaching Permissions to Permission group

You can add permission to group very simple:

use \YaroslavMolchan\Rbac\Models\Permission;

$createPermission = Permission::find(1);
$productManagementPermissionGroup->attachPermission($createPermission);
//or you can insert only id
$productManagementPermissionGroup->attachPermission($createPermission->id);

And the same to remove permission from group:

use \YaroslavMolchan\Rbac\Models\Permission;

$createPermission = Permission::find(1);
$productManagementPermissionGroup->detachPermission($createPermission);
//or you can insert only id
$productManagementPermissionGroup->detachPermission($createPermission->id);

Attaching And Detaching Permission groups to Role

You can attach permission group to role very simple:

use \YaroslavMolchan\Rbac\Models\Role;

$adminRole = Role::find(1);
$adminRole->attachGroup($productManagementPermissionGroup);

And the same to detach permission group:

use \YaroslavMolchan\Rbac\Models\Role;

$adminRole = Role::find(1);
$adminRole->detachGroup($productManagementPermissionGroup);

Protected routes

You can easily protect your routes with role and permission params:

Route::get('/admin', [
    'uses' => 'AdminController@index',
    'middleware' => 'role:admin'
]);

Route::get('/products/create', [
    'uses' => 'ProductsController@create',
    'middleware' => 'permission:product.create'
]);

Blade Extensions

You can check roles and permissions in Blade like this:

@ifUserIs('admin')
    // show content only for admin
@else
    // show content for other roles
@endif

@ifUserCan('product.create')
    // show product create content
@endif

License

Laravel RBAC is open-sourced software licensed under the MIT license

rbac's People

Contributors

baorv avatar harshloco avatar themy3 avatar

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rbac's Issues

check permission

hi, it's an excellent work, however i found a mistake beacuse when y tried to use smething like:

Route::get('/', [
        'uses'=>'UsersController@index',
        'middleware'=>'permission:users.user.index',
        'as'=>'users.user.index'
    ])->middleware('auth');

the code didn't fidn de permission, so i was looking for the problem. In the file namespace YaroslavMolchan\Rbac\Helpers\CacheHelper line 13 appear this if (false === \Cache::has($key)) { and i changed it for if (true === \Cache::has($key)) { whit this the code could find a permission related to the permission group and a permission related to a role both related to the same user.

@ifUserCan('product.create') - It doesn't work

try

@ifUserCan('product.create')
    // show product create content
@endif

but It doesn't work

Note: I added role 'admin' and role_user also added 'pruduct.create' in the permissions table

cannot find yaroslavmolchan/rbac ^2.0

As shown in the readme the installation instructions for Laravel 8.x, i tried to add the rbac^2.0 dependency and tried to run composer, but it couldn't find a suitable package. Here's the config and the output:

composer.json

{
    "name": "ssom/ssom",
    "type": "project",
    "description": "Simple Service Order Managent",
    "keywords": ["order management"],
    "license": "Beerware",
    "require": {
        "php": "^7.3|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.40",
        "laravel/tinker": "^2.5",
        "yaroslavmolchan/rbac": "^2.0"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/breeze": "^1.3",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

and the output:

$ composer update
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Root composer.json requires yaroslavmolchan/rbac ^2.0, found yaroslavmolchan/rbac[dev-master, 0.9.0, ..., 0.9.x-dev, 1.0.0, 1.0.1, 1.0.2, 1.0.3] but it does not match the constraint.

Is v2 available? If not yet, any hints when it will be?

Your package seems nice, thanks for sharing!

Proposal redirect

Currently when a permission is not related to a user the code redirect to /page welcome by default, for this i suggest add a variable in the config file to put the value than each project need in my case was the page /home.

Thanks for your atention.

Method Illuminate\Database\Query\Builder::permissions Array does not exist.

Hi guys,

Good work.
How ever, I come across this issue when I'm trying to implement this.
I am trying this on a fresh laravel installation with only change of Models having their own folder called Models.
Therefore, models are in App\Models.
I have updated this in the auth config file/section.
Logins, and registrations are working.

My issue comes up when I'm trying to check if a user has permission.

My code is

namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\User;

class RequestController extends Controller
{

    public function index(){
        $user = Auth::user();
        if ($user->canDo('product.create')) {

        }
    }
}


However, I come across the error

BadMethodCallException
Method Illuminate\Database\Query\Builder::permissionsArray does not exist.

Any help is greatly appreciated.

Migration Error

While following the steps of Readme.MD i found that when i run php artisian miragte it throws error:

[Illuminate\Database\QueryException]                                         
SQLSTATE[42000]: Syntax error or access violation: 1059 Identifier name 'pe  
rmission_permission_group_permission_id_permission_group_id_primary' is too  
 long (SQL: alter table `permission_permission_group` add primary key `perm  
ission_permission_group_permission_id_permission_group_id_primary`(`permiss  
ion_id`, `permission_group_id`))                                             
                                                                             

                                                                             
[PDOException]                                                               
SQLSTATE[42000]: Syntax error or access violation: 1059 Identifier name 'pe  
rmission_permission_group_permission_id_permission_group_id_primary' is too  
 long    

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.