Light-weight role-based permissions system for Laravel 6+ built in Auth system.

Overview

Kodeine/Laravel-ACL

Laravel Source Build Status License Total Downloads

Laravel ACL adds role based permissions to built in Auth System of Laravel 8.0+. ACL middleware protects routes and even crud controller methods.

Table of Contents

Requirements

  • Version 2.x of this package requires PHP 7.2+ and Laravel 6.0+
  • Version 1.x requires PHP 5.6+ and Laravel 5.0+

Getting Started

Install the package using composer

composer require kodeine/laravel-acl

If you need to support Laravel 5.x, make sure to install version 1.x

composer require kodeine/laravel-acl "^1.0"
  1. If you are using Laravel before version 5.4, manually register the service provider in your config/app.php file
'providers' => [
    'Illuminate\Foundation\Providers\ArtisanServiceProvider',
    'Illuminate\Auth\AuthServiceProvider',
    ...
    'Kodeine\Acl\AclServiceProvider',
],
  1. Publish the package configuartion files and add your own models to the list of ACL models"
$ php artisan vendor:publish --provider="Kodeine\Acl\AclServiceProvider"

Use your own models. Once you publish, it publishes the configuration file where you can define your own models which should extend to Acl models.

  1. Add the middleware to your app/Http/Kernel.php.
protected $routeMiddleware = [
    ....
    'acl' => 'Kodeine\Acl\Middleware\HasPermission',
];
  1. Add the HasRole trait to your User model.
use Kodeine\Acl\Traits\HasRole;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
    use Authenticatable, CanResetPassword, HasRole;
}
  1. Run the migrations to generate your roles and permissions tables

Please note that if you are upgrading to 6.0 from a previous version, the default column type for the id on the users table has changed. On certain databases foreign keys can only be defined with matching column types. As such, you will need to change the id column on your users table to bigInteger in to user this package.

php artisan migrate

Documentation

Follow along the Wiki to find out more.

Roadmap

Here's the TODO list for the next release.

  • Refactoring the source code.
  • Correct all issues.
  • Adding cache to final user permissions.

Change Logs

September 14 2019

  • Updated the readme to reflect new major release

September 13, 2019

  • Added support for Laravel 6

September 22, 2016*

  • Added unit tests

September 20, 2016*

  • Added support for Laravel 5.3

September 19, 2016

  • Added cache support to Roles and Permissions.

June 14, 2015

March 28, 2015

  • Added Role Scope to get all users having a specific role. e.g User::role('admin')->get(); will list all users having admin role.

March 7, 2015

  • is() and can() methods now support comma for AND and pipe as OR operator. Or pass an operator as a second param. more information
  • You can bind multiple permissions together so they inherit ones permission. more information

Contribution Guidelines

Support follows PSR-2 PHP coding standards, and semantic versioning.

Please report any issue you find in the issues page. Pull requests are welcome.

Comments
  • Question not and issue.

    Question not and issue.

    This is more a question then a issue.

    When implementing the acl. How would you go about managing this. If I make a admin page that manages the permissions. How would the database know witch permissions have been implemented into the routes file, and for that matter in the code?

    Also if I make use of Roles in routes, then how are these roles translated into actual permission sets in the database?

    In my mind if I implement either a role or a user permission in the routes file or anywhere else, this should some how be available to me in the interface, so that it is not necessary to implement the roles "by memory". Would this some how be possible?

    question 
    opened by addgod 21
  • Call to undefined method Illuminate\View\Compilers\BladeCompiler::directive()

    Call to undefined method Illuminate\View\Compilers\BladeCompiler::directive()

    This error appeared after doing composer update today, currently running Laravel 5.0.33.

    I managed to find the block of code at fault, lines 64 to 81 in AclServiceProvider.php, as copied below. Commenting it out temporarily fixed the problem but I'm unsure about a permanent solution (not even sure why this has suddenly appeared).

            // role
            Blade::directive('role', function($expression) {
                return "<?php if (Auth::check() && Auth::user()->is{$expression}): ?>";
            });
    
            Blade::directive('endrole', function() {
                return "<?php endif; ?>";
            });
    
            // permission
            Blade::directive('permission', function($expression) {
                return "<?php if (Auth::check() && Auth::user()->can{$expression}): ?>";
            });
    
            Blade::directive('endpermission', function() {
                return "<?php endif; ?>";
            });
    
    opened by jshah4517 16
  • Assing specific permissions to roles

    Assing specific permissions to roles

    Hi, is it possible to assign only specific permissions to roles?

    According to the wiki it's possible to do this by following line:

    $roleAdmin->assignPermission('user');
    

    But in my case I want my roles to only have something like this:

    $roleUser->assignPermission('view.user');
    $roleModerator->assignPermission(['view.user', 'update.user']);
    $roleAdmin->assignPermission('user');
    

    So is this possible with the code above or is it a feature that has to be implemented?

    Regards, Stefan

    opened by Mythos 14
  • Protecting Routes (using different roles)

    Protecting Routes (using different roles)

    I have a question guys, maybe you could help me. My question is how can I protect the routes if I have two different kinds of roles? For example I have an administrator and a supervisor. How can I Implement it in my routes.php?

    Privileges for all roles in User route: administrator: ALL supervisor: READ, UPDATE, CREATE (NO DELETE)

    I have this in my administrator Route::group([ 'prefix' => 'api', 'middleware' => ['jwt.auth', 'acl'], 'is' => 'administrator' ], function () { Route::post('user/create', 'UserController@store'); Route::get('user', 'UserController@index'); Route::get('user/{user}', 'UserController@show'); Route::put('user/{user}', 'UserController@update'); Route::delete('user/{user}', 'UserController@destroy'); } );

    Do I need to create another route for a supervisor and just remove the delete route? Like this? Route::group([ 'prefix' => 'api', 'middleware' => ['jwt.auth', 'acl'], 'is' => 'supervisor' ], function () { Route::post('user/create', 'UserController@store'); Route::get('user', 'UserController@index'); Route::get('user/{user}', 'UserController@show'); Route::put('user/{user}', 'UserController@update'); } );

    I do hope you could give me some tips and suggestions with regards to my problem. Thanks.

    opened by tritontek 13
  • About get user permissions

    About get user permissions

    In Wiki i found the following rules about user permissions

    1. getPermissions : Get permissions assigned to a user, all user permissions along with its role permissions.
    2. user permissions override role ones.

    But I dont get them as result. Please refer this image

    http://snag.gy/Eyc6Y.jpg

    Please check.

    bug: solved 
    opened by nglelinh 11
  • Support for Laravel 5.3

    Support for Laravel 5.3

    solves #149

    Changes

    • Renamed HasRole::is() to HasRole::hasRole() due to conflicts with new method Model::is() in Eloquent
    • Corrected all Blade directives to handle change in $expression parameter passing (no more brackets included).
    • Using Collection::pluck instead of Collection::lists(), if the method exists.
    • Preserved compatibility with older Laravel versions.

    Testing:

    I updated the complete library, but only did functional testing on Laravel 5.3 with the hasRole trait, because that's the only one we use for now. For the other changes I only did an automated syntax and a thorough visual check.

    I am quite confident that nothing broke, but if someone can test the other Traits and/or on prior Laravel versions, that would be appreciated.

    opened by peetersdiet 10
  • Laravel 5.0 and 5.1 compatibility issue with lists()

    Laravel 5.0 and 5.1 compatibility issue with lists()

    I'm currently working with Laravel v.5.0, and I have an error in the HasRole.php since this https://github.com/kodeine/laravel-acl/commit/8e5bcd4e0befdf9de6e5de498a613510e4873168 update.

    FatalErrorException in HasRole.php line 35: Call to a member function all() on array

    The lists() method still returns an array in v.5.0 whilst it no longer returns an array in v.5.1.

    Could you make it compatible?

    bug bug: solved 
    opened by wowzzangga 10
  • NTFS / Permission inheritance

    NTFS / Permission inheritance

    Greetings and thanks for your work on this package.

    I just spent the last couple hours trying to figure out why the permissions inheritance was not working as per your example in the wiki. Alas, it was the 'ntfs' setting in the config file.

    I suggested an edit on the Wiki page to inform the reader that the example will not work as expected if the default value of true is left unchanged.

    Do you believe it is a more common desire to have the default behavior of "more permissive wins"? I would think not, but I have not implemented many ACL systems, so perhaps this is my ignorance.

    opened by danyellnoe 10
  • [Possible bug] Problem with multiple roles

    [Possible bug] Problem with multiple roles

    Problem

    I have just noticed something that doesn't look quite right to me, i have the following situation: An user has two roles: student and secretary both have a different kind of permission regarding users obtained via permission inheritance:

    $genericUser=Permission::create([
                'name' => 'users',
                'slug' => [
                    'create' => false,
                    'view' => true,
                    'update' => false,
                    'approve' => false,
                    'delete' => false,
                ],
                'description' => 'generic permission regarding users'
            ]);
            $secretaryUser = Permission::create([
                'name' => 'users.secretary',
                'slug' => [
                    'create' => true,
                    'edit' => true,
                    'approve' => true,
                    'delete' => true,
                ],
                'inherit_id' => $genericUser->getKey(),
                'description' => 'secretary permission regarding users'
            ]);
    

    Since the user has both roles, it has both the permission users and users.secretary. The problem is that when i call can('edit.users') it returns false, if i call $user->getPermissions() i get the permissions of the last role assigned to the user (if i assign the generic first, i get the permissions of the secretary and vice versa).

    Where the issue is

    I think that depends on the fact that the method 'can' in 'HasPermission' trait calls the method 'getPermissions' which uses an array_replace_recursive, which replaces the permission set with the latest extracted from the database and not the higher in clearance

    Proposal

    When the user has more roles, each one with a different permission regarding the same thing, they should be merged granting the highest level of clearence, for example

    User has role1 and role2
    role1 has permission1:
    'name' => 'generic'
     'slug' => [
                    'create' => true,
                    'edit' => false,
                ],
    role2 has permission2:
    'name' => 'generic'
     'slug' => [
                    'create' => false,
                    'edit' => true,
                ],
    

    Calling getPermissions() on him should return

    "users"=>array:2[
    "create"=>"true"
    "edit"=>"true"
    ]
    

    Workaround

    array_replace_recursive overwrites everything previously existing, even if this means loosing some clearence, to avoid that we need to check for every key that it's value is higher than the one we currently have, i can't find any fancy function in PHP to do this:

    foreach($this->roles as $role){
      foreach($role->getPermissions() as $slug=>$array){
        if(array_key_exists($slug,$permissions){
          foreach($array as $clearence=>$value){
           !$value?:$permissions[$slug][$clearance]=true;
         }
       }else{
          $permissions = array_merge($permissions,array($slug => $array));
       }
     }
    }
    

    It's quite an ugly piece of code and i'm sorry for that, maybe you can come up with something better. Sorry for my horrible english

    opened by MarcoROG 10
  • Create Permissions

    Create Permissions

    Hello,

    When I want to create a new permission with the example in the wiki, I'm getting this error: ErrorException in helpers.php line 686: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array.

    Is this my mistake or an issue in the code?

    Thanks!

    Example: $permission = new Permission(); $permUser = $permission->create([ 'name' => 'user', 'slug' => [ 'create' => true, 'view' => true, 'update' => true, 'delete' => true, 'view.phone' => true ], 'description' => 'manage user permissions' ]);

    opened by mbalcaen 10
  • Add tags to the cache to easily purge ACL cache

    Add tags to the cache to easily purge ACL cache

    In order to purge only ACL cached entries, use the tags() method on the Cache facade. This way it is possible to purge only the ACL entries.

    This functionality can be helpful when editing ACLs using an interface.

    opened by screencomuser 9
  • Added:  Different guard support

    Added: Different guard support

    This fixes handling of a different guard other than application default.

    Fixes: #135.

    • Guard parameter on config file to get default;
      /**
       * Guard
       * Set the guard for user validations.
       */
      'guard' => config('auth.defaults.guard'),
    
    • Added guard on HasPermission handle;
       $this->guard = config('acl.guard');
    
    • Added $guard = $this->guard on hasRole, hasPermission and protectMethods;

    • Changed $request->user() to $request->user($guard) on hasRole, hasPermission and protectMethods;

    • Changed Blade directives to Blade::if method and guard added;

       // role
       Blade::if('role', function ($expression) {
            return Auth::guard(config('acl.guard'))->check() && Auth::guard(config('acl.guard'))->user()->hasRole($expression);
       });
    
       // permission
       Blade::if('permission', function ($expression) {
            return Auth::guard(config('acl.guard'))->check() && Auth::guard(config('acl.guard'))->user()->hasPermission($expression);
       });
    
    opened by CodeIgor 2
  • No way to invalidate cache manually

    No way to invalidate cache manually

    By default this package has set cache time for 1 minute. If I update permissions for a role, this will be effective in next cache interval. But there's should be an option to manually invalidate the cache.

    opened by apuatcfbd 2
  • Different structure of data returned for JSON ($role->toJSON()) after cache expire

    Different structure of data returned for JSON ($role->toJSON()) after cache expire

    I'm talking about JSON output/print When cache is active, it return like the following for $role->getPermissions()

    {
         role_name: {
             update: true
         },
         ...
    }
    

    but after the cache time exceeds, 1st response returns whole result set like:

    [
    	{
    		"id":2,
    		"inherit_id":null,
    		"name":"role_name",
    		"slug":{
    			"update":true
    		},
    		"description":"Post can be edited",
    		"created_at":"2021-03-03T12:02:43.000000Z",
    		"updated_at":"2021-03-03T12:02:43.000000Z",
    		"pivot":{
    			...
    		}
    	},
    	...
    ]
    

    In config file I've 'cacheMinutes' => 1 & I get this type of data change every 1 minute. Hope this explanation will be enough to reproduce the issue.

    This makes working with this hard.

    opened by apuatcfbd 1
  • cache tags not available in version 2.0

    cache tags not available in version 2.0

    I tried to use the cache feature and would like to clear the existing permissions when ever role is updated. but couldn't find anything related to this in docs.

    I just dig into the code and found that cache tags were available in ver 1.0 but not in v 2.0. any plan to incorporate this feature to 2.0 branch?

    I'm using laravel 6 and laravel-acl 2.0.

    opened by Rafeethu 1
  • PublishMigrations

    PublishMigrations

    Sometimes standard migrations need to be tweaked a bit. For example, when the user's id is not numeric, but uuid, ulid. Then a different ID format is used. It is good to have all migrations in one database/migrations folder.

    Tested, everything works

    opened by mcandylab 0
Releases(2.0.7)
Owner
Kodeine
Kodeine
Manage authorization with granular role-based permissions in your Laravel Apps.

Governor For Laravel Manage authorization with granular role-based permissions in your Laravel apps. Goal Provide a simple method of managing ACL in a

GeneaLabs, LLC 149 Dec 23, 2022
Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system.

Laravel Auth is a Complete Build of Laravel 8 with Email Registration Verification, Social Authentication, User Roles and Permissions, User Profiles, and Admin restricted user management system. Built on Bootstrap 4.

Jeremy Kenedy 2.8k Dec 31, 2022
Multi Auth and admin auth in Laravel Project

Laravel Multi Auth For Complete Documentation, visit Here This package is just create admin side (multi auth), which is totaly isolated from your norm

Bitfumes 435 Dec 31, 2022
CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

CakeDC Auth Objects is a refactor of the existing Auth objects present in the CakeDC Users Plugin, to let anyone else use them in their projects.

Cake Development Corporation 24 Sep 23, 2022
A Native PHP MVC With Auth. If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo.

If you will build your own PHP project in MVC with router and Auth, you can clone this ready to use MVC pattern repo. Auth system is implemented. Works with bootstrap 5. Composer with autoload are implemented too for future composer require.

null 2 Jun 6, 2022
User role and Permission Management system with Paticie package

User role and Permission Management system with Paticie package Installation instruction Download or git clone https://github.com/KKOO727/User-role-ma

Ninja 2 Mar 4, 2022
Auth is a module for the Yii PHP framework that provides a web user interface for Yii's built-in authorization manager

Auth is a module for the Yii PHP framework that provides a web user interface for Yii's built-in authorization manager (CAuthManager). You can read more about Yii's authorization manager in the framework documentation under Authentication and Authorization.

Christoffer Niska 134 Oct 22, 2022
Tech-Admin is Laravel + Bootstrap Admin Panel With User Management And Access Control based on Roles and Permissions.

Tech-Admin | Laravel 8 + Bootstrap 4 Tech-Admin is Admin Panel With Preset of Roles, Permissions, ACL, User Management, Profile Management. Features M

TechTool India 39 Dec 23, 2022
A user, group, role and permission management for Codeigniter 4

CI4-Auth CI4-Auth is a user, group, role and permission management library for Codeigniter 4. CI4-Auth is based on the great Myth-Auth library for Cod

George Lewe 15 Dec 16, 2022
GUI manager for RBAC (Role Base Access Control) Yii2. Easy to manage authorization of user

RBAC Manager for Yii 2 GUI manager for RBAC (Role Base Access Control) Yii2. Easy to manage authorization of user ?? . Documentation Important: If you

MDMunir Software 1.2k Jan 7, 2023
PermissionsMakr is a Laravel package that will help any developer to easily manage the system's users permissions

PermissionsMakr is a Laravel package that will help any developer to easily manage the system's users permissions

Alvarium Digital 3 Nov 30, 2021
Hierarchical Rol-Permission Based Laravel Auth Package with Limitless Hierarchical Level of Organizations

AAuth for Laravel Hierarchical Rol-Permission Based Laravel Auth Package with Limitless Hierarchical Level of Organizations Features Organization Base

Aurora Web Software Team 23 Dec 27, 2022
Configurable Basic Auth based on Pimcore Documents

CORS Property Basic Auth This bundles allows to add basic auth based on Properties on Pimcore Documents. Simply use these properties password_enabled

CORS GmbH 1 Nov 12, 2021
A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready

A PHP boilerplate based on Slim Framework, for start projects with Eloquent ORM, Validation, Auth (JWT), Repositories and Transformers ready.

Damiano Petrungaro 58 Aug 10, 2022
How to create a simple auth system with login and signup functionalities in Code-igniter 4.

Codeigniter 4 Authentication Login and Registration Example Checkout the step-by-step tutorial on: Codeigniter 4 Authentication Login and Registration

Digamber Rawat 7 Jan 9, 2023
Handle roles and permissions in your Laravel application

Laratrust (Laravel Package) Version Compatibility Laravel Laratrust 8.x 6.x 7.x 6.x 6.x 6.x 5.6.x - 5.8.x 5.2 5.3.x - 5.5.x 5.1 5.0.x - 5.2.x 4.0. Ins

Santiago García 2k Dec 30, 2022
Roles & Permissions for Laravel 8 / 7 / 6 / 5

Defender Defender is an Access Control List (ACL) Solution for Laravel 5 / 6 / 7 (single auth). (Not compatible with multi-auth) With security and usa

Artesãos 437 Dec 22, 2022
Laravel Users (Roles & Permissions, Devices, Password Hashing, Password History).

LARAVEL USERS Roles & Permissions Devices Password Hashing Password History Documentation You can find the detailed documentation here in Laravel User

Pharaonic 8 Dec 14, 2022
Powerful package for handling roles and permissions in Laravel 5

Roles And Permissions For Laravel 5 Powerful package for handling roles and permissions in Laravel 5 (5.1 and also 5.0). Installation Composer Service

Roman Bičan 1.2k Dec 17, 2022