Coder Social home page Coder Social logo

laravel-rbac's Introduction

Laravel RBAC

Super simple RBAC/ACL implementation for Laravel 5.

Installation

Require this package with composer (Packagist) using the following command

composer require phpzen/laravel-rbac

or modify your composer.json

"require": {
    ...
    "phpzen/laravel-rbac": "^0.2"
}

then run composer update.

After installation register the ServiceProvider to the providers array in config/app.php

PHPZen\LaravelRbac\RbacServiceProvider::class,

Publish migration files

$ php artisan vendor:publish --provider="PHPZen\LaravelRbac\RbacServiceProvider" --force

Run migrations

$ php artisan migrate

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

protected $routeMiddleware = [
    ...
    'rbac' => '\PHPZen\LaravelRbac\Middleware\Rbac::class'
];

Add Rbac trait to your User model

use PHPZen\LaravelRbac\Traits\Rbac;
	
class User extends Authenticatable
{
    use Rbac;
    ...
	    
}

Usage

Roles

Create role

$adminRole = new Role;
$adminRole->name = 'Administrator';
$adminRole->slug = 'administrator';
$adminRole->description = 'System Administrator';
$adminRole->save();

$editorRole = new Role;
$editorRole->name = 'Editor';
$editorRole->slug = 'editor';
$editorRole->description = 'Editor';
$editorRole->save();

Assign role to user

$user = User::find(1);
$user->roles()->attach($adminRole->id);

you can also assign multiple roles at once

$user->roles()->attach([$adminRole->id, $editorRole->id]);

Revoke role from user

$user->roles()->detach($adminRole->id);

you can also revoke multiple roles at once

$user->roles()->detach([$adminRole->id, $editorRole->id]);

Sync roles

$user->roles()->sync([$editorRole->id]);

Any role already assigned to user will be revoked if you don't pass its id to sync method.

Permissions

Create permission

$createUser = new Permission;
$createUser->name = 'Create user';
$createUser->slug = 'user.create';
$createUser->description = 'Permission to create user';
$createUser->save();

$updateUser = new Permission;
$updateUser->name = 'Update user';
$updateUser->slug = 'user.update';
$updateUser->description = 'Permission to update user';
$updateUser->save();

Assign permission to role

$adminRole = Role::find(1);
$adminRole->permissions()->attach($createUser->id);

you can also assign multiple permissions at once

$adminRole->permissions()->attach([$createUser->id, $updateUser->id]);

Revoke permission from role

$adminRole->permissions()->detach($createUser->id);

you can also revoke multiple permissions at once

$adminRole->permissions()->detach([$createUser->id, $updateUser->id]);

Sync permissions

$adminRole->permissions()->sync([$updateUser->id]);

Any permission already assigned to role will be revoked if you don't pass its id to sync method.

Check user roles/permissions

Roles and permissions can be checked on User instance using hasRole and canDo methods.

$isAdmin = Auth::user()->hasRole('administrator'); // pass role slug as parameter
$isAdminOrEditor = Auth::user()->hasRole('administrator|editor'); // using OR operator
$canUpdateUser = Auth::user()->canDo('update.user'); // pass permission slug as parameter
$canUpdateOrCreateUser = Auth::user()->canDo('update.user|create.user'); // using OR operator

Protect routes

Laravel RBAC provides middleware to protect single route and route groups. Middleware expects 2 comma separated params:

  • is or can as first param - what to check (role/permission)
  • role/permission slug as second param
Route::get('/backend', [
    'uses' => 'BackendController@index',
    'middleware' => ['auth', 'rbac:is,administrator']
]);
Route::get('/backend', [
    'uses' => 'BackendController@index',
    'middleware' => ['auth', 'rbac:is,administrator|editor']
]);
Route::get('/dashboard', [
    'uses' => 'DashboardController@index',
    'middleware' => ['auth', 'rbac:can,view.dashboard']
]);
Route::get('/dashboard', [
    'uses' => 'DashboardController@index',
    'middleware' => ['auth', 'rbac:can,view.dashboard|view.statistics']
]);

Blade directive

Laravel RBAC provides two Blade directives to check if user has role/permission assigned.

Check for role

@ifUserIs('administrator')
    // show admin content here
@else
    // sorry
@endif

@ifUserIs('administrator|editor')
    // show editor content here
@else
    // sorry
@endif

Check for permission

@ifUserCan('delete.user')
    // show delete button
@endif

@ifUserCan('delete.user|manage.user')
    // show delete button
@endif

License

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

laravel-rbac's People

Contributors

msbytes avatar phpzen avatar tal512 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

Watchers

 avatar  avatar  avatar  avatar  avatar

laravel-rbac's Issues

How to use OR in blade

hi, how to use or in blade? for example if user is administrator or user is manager ?

@ifUserIs('administrator') or ifUserIs('manager')

Call to undefined method Illuminate\Database\Query\Builder::permissions()

after successful install this package i get the error:

My Test:

Route::get('rl', ['as' => 'rl', function () {
    $adminRole = new Role;
    $adminRole->name = 'Administrator';
    $adminRole->slug = 'administrator';
    $adminRole->description = 'System Administrator';
    $adminRole->save();

    $user = User::find(1);
    $user->roles()->attach($adminRole->id);
    $user->roles()->sync([$editorRole->id]);

    $createUser = new Permission;
    $createUser->name = 'Create user';
    $createUser->slug = 'user.create';
    $createUser->description = 'Permission to create user';
    $createUser->save();

    $adminRole = Role::find(1);
    $adminRole->permissions()->attach($createUser->id);

}]);

My laravel version is 5.2.

i resolve the problem by create Role model as:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    public function permissions()
    {
        return $this->hasMany('App\Permission');
    }
}

but i get this error now

Call to undefined method Illuminate\Database\Query\Builder::attach()

Permission model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Permission extends Model
{
    public function roles() {
        return $this->belongsToMany('App\Role');
    }
}

Compatible to Laravel 5.2?

Hi, is this compatible to Laravel 5.2? I am using laravel 5.2 and Dingo/Api package for Rest Api. Hoping that this package fit in to my existing package.

Change role permissions with array.

I'm trying to do a frontend role permission change, a bit stuck, im putting the values in to an array like this:

$allowed_permissions = []; 
        foreach($request->input('permissions') as $permission) {
        if ($permission == 1) {
            $allowed_permissions = $request->input('permissions');
        }

        }
       $role = Role::find($request->input('role_id'));
       $role->permissions()->sync($allowed_permissions);
        $role->save();

And that will then equal an array with either 1 if the permission is allowed, or 0 if the permission is not allowed like this:

 " 1 " => "1"
  " 2 " => "1"
  " 3 " => "1"
  " 4 " => "0"
  " 5 " => "1"
  " 6 " => "1"
  " 7 " => "0"
  " 8 " => "0" // 0 = deattach 1= attach
  " 9 " => "1"
  " 10 " => "1",

the problem is the sync dosen't syc. ($role->permissions()->sync($allowed_permissions)

how can i install on Laravel 5.3?

how can?

    - Installation request for phpzen/laravel-rbac ^0.2 -> satisfiable by phpzen/laravel-rbac[0.2].
    - Conclusion: don't install laravel/framework v5.3.2
    - Conclusion: don't install laravel/framework v5.3.1
    - phpzen/laravel-rbac 0.2 requires illuminate/support 5.2.* -> satisfiable by illuminate/support[v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7].

Invalid RBAC operator specified.

i get the error when i use RBAC like with this code:

Route::group(['middleware' => ['auth', 'rbac:is,administrator']], function () {

Error after installation

FatalThrowableError
Class 'rpc\Http\Controllers\Role' not found

How i'm install rbac :

  1. composer require phpzen/laravel-rbac
  2. add PHPZen\LaravelRbac\RbacServiceProvider::class, in app.php
  3. php artisan vendor:publish --provider="PHPZen\LaravelRbac\RbacServiceProvider" --force
  4. php artisan migrate
  5. add in Kernel.php 'rbac' => '\PHPZen\LaravelRbac\Middleware\Rbac::class'
  6. add Rbac in User.php
<?php

namespace rpc;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use PHPZen\LaravelRbac\Traits\Rbac;

class User extends Authenticatable
{
    use Notifiable, Rbac;

I got an error message

Thx , Yura Lons

Unable to install with Laravel 5.4.*

I'm trying to get this added to my Laravel 5.4 install using the following command:

composer require phpzen/laravel-rbac

The output of this command is:

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for phpzen/laravel-rbac 0.2 -> satisfiable by phpzen/laravel-rbac[0.2].
    - Conclusion: remove laravel/framework v5.4.15
    - Conclusion: don't install laravel/framework v5.4.15
    - phpzen/laravel-rbac 0.2 requires illuminate/support 5.2.* -> satisfiable by illuminate/support[v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.43, v5.2.45, v5.2.6, v5.2.7].
    - don't install illuminate/support v5.2.0|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.19|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.21|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.24|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.25|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.26|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.27|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.28|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.31|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.32|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.37|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.43|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.45|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.6|don't install laravel/framework v5.4.15
    - don't install illuminate/support v5.2.7|don't install laravel/framework v5.4.15
    - Installation request for laravel/framework (locked at v5.4.15, required as 5.4.*) -> satisfiable by laravel/framework[v5.4.15].


Installation failed, reverting ./composer.json to its original content.

Is anyone else having this error? What did you do to resolve?

Thanks,

ifUserNot

hi. can you develop your code to use @ifUserNot('customers') ???

for example i use this code for exclude customers roles

@ifUserIs('administrator|accountant_manager|sales_manager')

if i have @ifUserNot option, my code clear. Thanks

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.