├── .devcontainer ├── Dockerfile ├── devcontainer.bash └── devcontainer.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── config └── rbac.php ├── resources └── views │ └── .gitkeep ├── src ├── Actions │ ├── StorePermission.php │ └── SyncDefinedRole.php ├── Commands │ ├── AbilityMakeCommand.php │ ├── DefinedRoleMakeCommand.php │ └── RbacResetCommand.php ├── Contracts │ └── DefinedRole.php ├── DefinedRole.php ├── DiscoverAbilities.php ├── Exceptions │ └── RbacException.php ├── Facades │ └── Rbac.php ├── Jobs │ ├── FlushPermissionCache.php │ ├── ResetPermissions.php │ └── SyncDefinedRoles.php ├── Rbac.php └── RbacServiceProvider.php └── stubs ├── ability.stub └── defined-role.stub /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | # Base image is from Microsoft 2 | FROM mcr.microsoft.com/vscode/devcontainers/base:ubuntu-22.04 3 | 4 | # Avoid interactive prompts (e.g. tzdata) during installation 5 | ENV DEBIAN_FRONTEND=noninteractive 6 | 7 | RUN mkdir -p /var/www/html 8 | 9 | # Install 8.3 from Ondrej’s PPA 10 | RUN apt-get update && apt-get install -y \ 11 | software-properties-common \ 12 | && add-apt-repository ppa:ondrej/php -y \ 13 | && apt-get update && apt-get install -y sqlite3 \ 14 | && apt-get install -y php8.3-cli php8.3-dev \ 15 | php8.3-pgsql php8.3-sqlite3 php8.3-gd \ 16 | php8.3-curl \ 17 | php8.3-imap php8.3-mysql php8.3-mbstring \ 18 | php8.3-xml php8.3-zip php8.3-bcmath php8.3-soap \ 19 | php8.3-intl php8.3-readline \ 20 | php8.3-ldap \ 21 | php8.3-msgpack php8.3-igbinary php8.3-redis php8.3-swoole \ 22 | php8.3-memcached php8.3-pcov php8.3-imagick php8.3-xdebug \ 23 | && apt-get clean && rm -rf /var/lib/apt/lists/* 24 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.bash: -------------------------------------------------------------------------------- 1 | alias art='php artisan --ansi' 2 | alias tinker='art tinker' 3 | alias format='php vendor/bin/pint' 4 | alias analyze='php vendor/bin/phpstan analyse' 5 | alias test='php vendor/bin/paratest --coverage-html coverage' 6 | alias stf='php vendor/bin/phpunit --filter' 7 | 8 | # commit AI 9 | function commit() { 10 | commitMessage="$*" 11 | 12 | git add . 13 | 14 | if [ "$commitMessage" = "" ]; then 15 | aicommits 16 | return 17 | fi 18 | 19 | eval "git commit -a -m '${commitMessage}'" 20 | } 21 | 22 | # function gfind 23 | function gfind() { 24 | local excludeVendor="--exclude-dir=vendor" # Default to excluding the vendor directory 25 | local searchString="" 26 | local searchPath="./" 27 | 28 | # Process all arguments 29 | for arg in "$@"; do 30 | if [[ "$arg" == "-w" || "$arg" == "--with-vendor" ]]; then 31 | excludeVendor="" # Remove the exclude directive to include vendor 32 | elif [[ -z "$searchString" && "$arg" != -* ]]; then 33 | searchString="$arg" # Set the search string if it's not a flag and is the first non-flag argument 34 | fi 35 | done 36 | 37 | # Check if a search string was provided 38 | if [[ -z "$searchString" ]]; then 39 | echo -e "${RED}Error: Missing required search string.${NC}" 40 | echo -e "${YELLOW}Usage: ${NC}gfind searchString [-w|--with-vendor]" 41 | return 1 42 | fi 43 | 44 | # Execute grep command 45 | grep --include=\*.php $excludeVendor -rnw $searchPath -e "$searchString" 46 | } -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Laravel RBAC", 3 | "build": { 4 | "dockerfile": "Dockerfile", 5 | "context": "." 6 | }, 7 | "features": {}, 8 | "customizations": { 9 | "vscode": { 10 | "extensions": [ 11 | "bmewburn.vscode-intelephense-client", 12 | "calebporzio.better-phpunit", 13 | "laravel.vscode-laravel", 14 | "mikestead.dotenv", 15 | "ms-azuretools.vscode-docker", 16 | "php.intelephense" 17 | ], 18 | "settings": { 19 | "intelephense.environment.phpVersion": "8.3" 20 | } 21 | } 22 | }, 23 | "remoteUser": "vscode", 24 | "postCreateCommand": "", 25 | "forwardPorts": [], 26 | "portsAttributes": {} 27 | } 28 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `binary-cats/rbac` will be documented in this file. 4 | 5 | ## v1.5 - 2025-05-09 6 | 7 | ### What's Changed 8 | 9 | * Simplify the package by @cyrillkalita in https://github.com/binary-cats/laravel-rbac/pull/16 10 | 11 | * Add Laravel 8.3 and necessary dependencies to Dockerfile 12 | 13 | * Refactor actions for syncing permissions 14 | 15 | * Update composer.json and sync actions for roles and permissions 16 | 17 | * Remove spatie/laravel-collection-macros dependency 18 | 19 | * Refresh tests to rely on the model resolution instead of Artisan command 20 | 21 | * Refresh command to display the progress with components 22 | 23 | 24 | **Full Changelog**: https://github.com/binary-cats/laravel-rbac/compare/1.4.0...1.5.0 25 | 26 | ## v1.4 - 2025-03-22 27 | 28 | ### What's Changed 29 | 30 | * Add option to publish stub files by @briavers in https://github.com/binary-cats/laravel-rbac/pull/15 31 | 32 | ### New Contributors 33 | 34 | * @briavers made their first contribution in https://github.com/binary-cats/laravel-rbac/pull/15 35 | 36 | **Full Changelog**: https://github.com/binary-cats/laravel-rbac/compare/1.3...1.4.0 37 | 38 | ## 1.3 - 2025-03-03 39 | 40 | ### What's Changed 41 | 42 | * Update Laravel and Laravel Collection Macros versions by @cyrillkalita in https://github.com/binary-cats/laravel-rbac/pull/14 43 | * Adjust testing matrix to include Laravel 12 44 | 45 | **Full Changelog**: https://github.com/binary-cats/laravel-rbac/compare/1.2.0...1.3 46 | 47 | ## 1.2 | Add Laravel 12 dependency - 2025-02-19 48 | 49 | - Upgrade dependencies to allow for Laravel 12 50 | - Update text matrix 51 | 52 | ## 1.1.3 | Update dependabot - 2025-01-27 53 | 54 | ### What's Changed 55 | 56 | * Bump dependabot/fetch-metadata from 2.0.0 to 2.1.0 by @dependabot in https://github.com/binary-cats/laravel-rbac/pull/9 57 | * Bump dependabot/fetch-metadata from 2.1.0 to 2.2.0 by @dependabot in https://github.com/binary-cats/laravel-rbac/pull/10 58 | * Bump dependabot/fetch-metadata from 2.2.0 to 2.3.0 by @dependabot in https://github.com/binary-cats/laravel-rbac/pull/12 59 | 60 | **Full Changelog**: https://github.com/binary-cats/laravel-rbac/compare/1.1.2...1.1.3 61 | 62 | ## 1.1.2 | Update dependabot - 2024-04-15 63 | 64 | Update dependabot dependencies 65 | 66 | ## 1.1.1 - 2024-03-22 67 | 68 | ### What's Changed 69 | 70 | * Update namespace within role stub by @cyrillkalita in https://github.com/binary-cats/laravel-rbac/pull/7 71 | 72 | **Full Changelog**: https://github.com/binary-cats/laravel-rbac/compare/1.1.0...1.1.1 73 | 74 | ## 1.1.0 - 2024-03-20 75 | 76 | ### What's Changed 77 | 78 | * Update the namespace and add interactive facade by @cyrillkalita in https://github.com/binary-cats/rbac/pull/5 79 | * Adjust package namespace 80 | * Add integration help 81 | 82 | **Full Changelog**: https://github.com/binary-cats/rbac/compare/1.0.1...1.1.0 83 | 84 | ## 1.0.1 - 2024-03-20 85 | 86 | ### What's Changed 87 | 88 | * Update namespaces in DiscoverAbilities and RbacException files by @cyrillkalita in https://github.com/binary-cats/rbac/pull/4 89 | 90 | **Full Changelog**: https://github.com/binary-cats/rbac/compare/1.0.0...1.0.1 91 | 92 | ## v1.0 - 2024-03-19 93 | 94 | - Initial Release 95 | 96 | ## 1.0.0 - 2024-03-18 97 | 98 | - Initial version 99 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Binary Cats 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [](https://supportukrainenow.org) 2 | 3 | ![](https://banners.beyondco.de/Laravel%20RBAC.png?theme=light&packageManager=composer+require&packageName=binary-cats%2Flaravel-rbac&pattern=architect&style=style_1&description=Manage+your+spatie%2Flaravel-permission+lists+with+well-defined+roles&md=1&showWatermark=1&fontSize=100px&images=lock-closed) 4 | 5 | # Laravel RBAC 6 | 7 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/binary-cats/laravel-rbac.svg?style=flat-square)](https://packagist.org/packages/binary-cats/laravel-rbac) 8 | [![run-tests](https://img.shields.io/github/actions/workflow/status/binary-cats/laravel-rbac/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/binary-cats/laravel-rbac/actions/workflows/run-tests.yml) 9 | [![GitHub Code Style Action Status](https://github.styleci.io/repos/773171043/shield?branch=main)](https://github.com/binary-cats/laravel-rbac/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) 10 | 11 | Enhance your Laravel with opinionated extension for [spatie/laravel-permissions](https://spatie.be/docs/laravel-permission/v6/introduction). 12 | Before your permission list grows and maintenance becomes an issue, this package offers simple way of defining roles and their permissions. 13 | 14 | ## Installation 15 | 16 | You can install the package via composer: 17 | 18 | ```bash 19 | composer require binary-cats/laravel-rbac 20 | ``` 21 | 22 | You can publish the config file with: 23 | 24 | ```bash 25 | php artisan vendor:publish --tag="rbac-config" 26 | ``` 27 | 28 | This is the contents of the published config file: 29 | 30 | ```php 31 | return [ 32 | /* 33 | |-------------------------------------------------------------------------- 34 | | Role base access reset control 35 | |-------------------------------------------------------------------------- 36 | | 37 | | When running rbac:reset those commands will be executed in sequence 38 | | 39 | */ 40 | 41 | 'jobs' => [ 42 | \BinaryCats\LaravelRbac\Jobs\FlushPermissionCache::class, 43 | \BinaryCats\LaravelRbac\Jobs\ResetPermissions::class, 44 | \BinaryCats\LaravelRbac\Jobs\SyncDefinedRoles::class, 45 | ], 46 | 47 | /* 48 | |-------------------------------------------------------------------------- 49 | | Role base access ability set 50 | |-------------------------------------------------------------------------- 51 | | 52 | | Place your ability files in this folder, and they will be auto discovered 53 | | 54 | */ 55 | 'path' => app()->path('Abilities'), 56 | 57 | /* 58 | |-------------------------------------------------------------------------- 59 | | Defined Roles 60 | |-------------------------------------------------------------------------- 61 | | 62 | | Defined roles are immutable by users 63 | | 64 | */ 65 | 66 | 'roles' => [ 67 | 68 | ], 69 | ]; 70 | ``` 71 | 72 | You can publish the stub files with: 73 | 74 | ```bash 75 | php artisan vendor:publish --tag="rbac-stubs" 76 | ``` 77 | 78 | ## Usage 79 | 80 | ```bash 81 | php artisan rbac:reset 82 | ``` 83 | 84 | In a simple setup we usually have two basic parts of an RBAC: a permission and a role. 85 | Permissions are usually grouped by functional or business logic domain and a Role encapsulates them for a specific guard. 86 | 87 | 1. [Create Abilities](#abilities) 88 | 2. [Define Roles](#defined-roles) 89 | 3. [Connect the dots](#connect-the-dots) 90 | 91 | ### Abilities 92 | 93 | To avoid collision with `spatie/laravel-permission` we are going to use `BackedEnum` Ability enums to hold out enumerated permissions: 94 | You can read more on using `enums` as permissions at the [official docs](https://spatie.be/docs/laravel-permission/v6/basic-usage/enums). 95 | 96 | To create an Ability: 97 | 98 | ```bash 99 | php artisan make:ability PostAbility 100 | ``` 101 | 102 | This will generate a `PostAbility` in `App\Abilities`: 103 | 104 | ```php 105 | namespace App\Abilities; 106 | 107 | enum PostAbility: string 108 | { 109 | case ViewPost = 'view post'; 110 | case CreatePost = 'create post'; 111 | case UpdatePost = 'update post'; 112 | case DeletePost = 'delete post'; 113 | } 114 | ``` 115 | Default stub contains fairly standard CRUD enumeration, generated using the name of the ability. Feel free to publish the stubs and adjsut as needed. 116 | 117 | 118 | ### Defined Roles 119 | 120 | As the name suggests, a `DefinedRole` offers a mechanism to simplify the definition of all permissions needed for a given role. 121 | To create an `EditorRole` run: 122 | 123 | ```bash 124 | php artisan make:role EditorRole 125 | ``` 126 | 127 | This will generate an `EditorRole` within `App\Roles`: 128 | 129 | ```php 130 | use BinaryCats\LaravelRbac\DefinedRole; 131 | 132 | class EditorRole extends DefinedRole 133 | { 134 | /** @var array|string[] */ 135 | protected array $guards = [ 136 | 'web' 137 | ]; 138 | 139 | /** 140 | * List of enumerated permissions for the `web` guard 141 | * 142 | * @return array 143 | */ 144 | public function web(): array 145 | { 146 | return []; 147 | } 148 | } 149 | ``` 150 | 151 | This class contains a (now testable!) configuration definition for the role and its `web` guard. Pretty neat! 152 | We can now adjust it like so: 153 | 154 | ```php 155 | namespace App\Roles; 156 | 157 | use App\Abilities\PostAbility; 158 | use BinaryCats\LaravelRbac\DefinedRole; 159 | 160 | class EditorRole extends DefinedRole 161 | { 162 | /** @var array|string[] */ 163 | protected array $guards = [ 164 | 'web' 165 | ]; 166 | 167 | /** 168 | * List of enumerated permissions for the `web` guard 169 | * 170 | * @return array 171 | */ 172 | public function web(): array 173 | { 174 | return [ 175 | PostAbility::CreatePost, 176 | PostAbility::UpdatePost, 177 | PostAbility::ViewPost, 178 | ]; 179 | } 180 | } 181 | ``` 182 | Now you are confident a specific role has specific permissions! 183 | 184 | ### Connect the dots 185 | 186 | Now that we have the abilities and roles, simply register role with `rbac.php` config: 187 | 188 | ```php 189 | 'roles' => [ 190 | \App\Roles\EditorRole::class, 191 | ... 192 | ], 193 | ``` 194 | 195 | When you run `rbac:reset` next time, your RBAC will be reset automatically. 196 | 197 | ## Integration 198 | 199 | I suggest adding the script to `post-autoload-dump` of your `composer.json` to make sure the RBAC is reset on every composer dump: 200 | 201 | ```json 202 | "post-autoload-dump": [ 203 | "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump", 204 | "@php artisan rbac:reset" 205 | ], 206 | ``` 207 | 208 | ## Testing 209 | 210 | ```bash 211 | composer test 212 | ``` 213 | 214 | ## Changelog 215 | 216 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 217 | 218 | ## Contributing 219 | 220 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 221 | 222 | ## Security 223 | 224 | If you discover any security related issues, please email cyrill.kalita@gmail.com instead of using issue tracker. 225 | 226 | ## Postcardware 227 | 228 | You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. 229 | 230 | ## Credits 231 | 232 | - [Cyrill N Kalita](https://github.com/cyrillkalita) 233 | - [All Contributors](../../contributors) 234 | 235 | ## License 236 | 237 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 238 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "binary-cats/laravel-rbac", 3 | "description": "Laravel 11 enum-backed RBAC extension of spatie/laravel-permission", 4 | "keywords": [ 5 | "binary-cats", 6 | "enum", 7 | "laravel", 8 | "rbac" 9 | ], 10 | "homepage": "https://github.com/binary-cats/laravel-rbac", 11 | "license": "MIT", 12 | "authors": [ 13 | { 14 | "name": "Cyrill N Kalita", 15 | "email": "cyrill.kalita@gmail.com", 16 | "role": "Developer" 17 | } 18 | ], 19 | "require": { 20 | "php": "^8.2", 21 | "illuminate/contracts": "^11.0|^12.0", 22 | "lorisleiva/laravel-actions": "^2.8", 23 | "spatie/laravel-package-tools": "^1.16", 24 | "spatie/laravel-permission": "^6.4" 25 | }, 26 | "require-dev": { 27 | "laravel/pint": "^1.14", 28 | "nunomaduro/collision": "^8.1", 29 | "orchestra/testbench": "^9.0|^10.0" 30 | }, 31 | "autoload": { 32 | "psr-4": { 33 | "BinaryCats\\LaravelRbac\\": "src/" 34 | } 35 | }, 36 | "autoload-dev": { 37 | "psr-4": { 38 | "BinaryCats\\LaravelRbac\\Tests\\": "tests/", 39 | "Workbench\\App\\": "workbench/app/", 40 | "Workbench\\Database\\Factories\\": "workbench/database/factories/", 41 | "Workbench\\Database\\Seeders\\": "workbench/database/seeders/" 42 | } 43 | }, 44 | "suggest": { 45 | "binary-cats/laravel-mailgun-webhooks": "Handle Mailgun webhooks in your Laravel application", 46 | "binary-cats/laravel-sku": "Generate SKUs for Eloquent models" 47 | }, 48 | "scripts": { 49 | "test": "vendor/bin/phpunit", 50 | "post-autoload-dump": [ 51 | "@clear", 52 | "@prepare" 53 | ], 54 | "clear": "@php vendor/bin/testbench package:purge-skeleton --ansi", 55 | "prepare": "@php vendor/bin/testbench package:discover --ansi", 56 | "build": "@php vendor/bin/testbench workbench:build --ansi", 57 | "serve": [ 58 | "Composer\\Config::disableProcessTimeout", 59 | "@build", 60 | "@php vendor/bin/testbench serve" 61 | ], 62 | "lint": [ 63 | "@php vendor/bin/pint", 64 | "@php vendor/bin/phpstan analyse" 65 | ] 66 | }, 67 | "config": { 68 | "sort-packages": true 69 | }, 70 | "extra": { 71 | "laravel": { 72 | "providers": [ 73 | "BinaryCats\\LaravelRbac\\RbacServiceProvider" 74 | ], 75 | "aliases": { 76 | "Rbac": "BinaryCats\\LaravelRbac\\Facades\\Rbac" 77 | } 78 | }, 79 | "branch-alias": { 80 | "dev-master": "1.x-dev" 81 | } 82 | }, 83 | "minimum-stability": "dev", 84 | "prefer-stable": true 85 | } -------------------------------------------------------------------------------- /config/rbac.php: -------------------------------------------------------------------------------- 1 | [ 15 | \BinaryCats\LaravelRbac\Jobs\FlushPermissionCache::class, 16 | \BinaryCats\LaravelRbac\Jobs\ResetPermissions::class, 17 | \BinaryCats\LaravelRbac\Jobs\SyncDefinedRoles::class, 18 | ], 19 | 20 | /* 21 | |-------------------------------------------------------------------------- 22 | | Role base access ability set 23 | |-------------------------------------------------------------------------- 24 | | 25 | | Place your ability files in this folder, and they will be auto discovered 26 | | 27 | */ 28 | 'path' => app()->path('Abilities'), 29 | 30 | /* 31 | |-------------------------------------------------------------------------- 32 | | Defined Roles 33 | |-------------------------------------------------------------------------- 34 | | 35 | | Defined roles are immutable by users 36 | | 37 | */ 38 | 39 | 'roles' => [ 40 | 41 | ], 42 | ]; 43 | -------------------------------------------------------------------------------- /resources/views/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/binary-cats/laravel-rbac/4d485daa55f3a1f889e779a1afd0e581e0e4b60f/resources/views/.gitkeep -------------------------------------------------------------------------------- /src/Actions/StorePermission.php: -------------------------------------------------------------------------------- 1 | value; 23 | } 24 | 25 | $this->permission::findOrCreate($permission, $guard); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Actions/SyncDefinedRole.php: -------------------------------------------------------------------------------- 1 | map(fn ($permission) => match (true) { 23 | $permission instanceof BackedEnum => $permission->value, 24 | default => (string) $permission 25 | }); 26 | 27 | $this->role::findOrCreate($name, $guard) 28 | ->syncPermissions($permissions); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/Commands/AbilityMakeCommand.php: -------------------------------------------------------------------------------- 1 | classBasename() 58 | ->replaceLast($this->type, ''); 59 | 60 | $stub = Str::of($stub) 61 | ->replace('{{ Subject }}', $subject) 62 | ->replace('{{ subject }}', $subject->lower()) 63 | ->toString(); 64 | 65 | return parent::replaceClass($stub, $name); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/Commands/DefinedRoleMakeCommand.php: -------------------------------------------------------------------------------- 1 | databaseReady()) { 31 | $this->error('DB is not ready. Please run migrations.'); 32 | 33 | return self::INVALID; 34 | } 35 | 36 | $this->jobs()->each(function (string $job) { 37 | $this->components->task( 38 | $job, 39 | fn () => $this->laravel->make($job)->dispatchSync() 40 | ); 41 | }); 42 | 43 | return self::SUCCESS; 44 | } 45 | 46 | /** 47 | * Create the jobs. 48 | */ 49 | protected function jobs(): Collection 50 | { 51 | $value = config('rbac.jobs'); 52 | 53 | return collect($value); 54 | } 55 | 56 | /** 57 | * True if the Database is prepared. 58 | */ 59 | protected function databaseReady(): bool 60 | { 61 | $tables = config('permission.table_names', []); 62 | 63 | return collect($tables) 64 | ->map(fn (string $table) => Schema::hasTable($table)) 65 | ->reject() 66 | ->isEmpty(); 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/Contracts/DefinedRole.php: -------------------------------------------------------------------------------- 1 | name) { 27 | return $this->name; 28 | } 29 | 30 | $reflection = new ReflectionClass($this); 31 | 32 | return Str::of($reflection->getName()) 33 | ->classBasename() 34 | ->replaceLast('Role', '') 35 | ->snake() 36 | ->headline(); 37 | } 38 | 39 | public function handle(): void 40 | { 41 | foreach ($this->guards() as $guard) { 42 | SyncDefinedRole::run($this->name(), $guard, $this->{$guard}()); 43 | } 44 | } 45 | 46 | /** 47 | * @return array|string[] 48 | */ 49 | protected function guards(): array 50 | { 51 | return $this->guards; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/DiscoverAbilities.php: -------------------------------------------------------------------------------- 1 | 29 | */ 30 | public static function within(string $abilitiesPath, string $basePath): Collection 31 | { 32 | $abilities = collect(static::getAbilities( 33 | Finder::create()->files()->in($abilitiesPath), 34 | $basePath 35 | )); 36 | 37 | \throw_if( 38 | $abilities->pluck('value')->duplicates()->isNotEmpty(), 39 | RbacException::rbacContainsDuplicateAbilities($abilities) 40 | ); 41 | 42 | return $abilities; 43 | } 44 | 45 | protected static function getAbilities($abilities, $basePath) 46 | { 47 | $enums = []; 48 | 49 | foreach ($abilities as $ability) { 50 | try { 51 | $ability = new ReflectionClass( 52 | static::classFromFile($ability, $basePath) 53 | ); 54 | } catch (ReflectionException $e) { 55 | continue; 56 | } 57 | 58 | if (!$ability->isEnum()) { 59 | continue; 60 | } 61 | 62 | foreach ($ability->name::cases() as $permission) { 63 | $enums[] = $permission; 64 | } 65 | } 66 | 67 | return $enums; 68 | } 69 | 70 | /** 71 | * Extract the class name from the given file path. 72 | * 73 | * @param \SplFileInfo $file 74 | * @param string $basePath 75 | * 76 | * @return string 77 | */ 78 | protected static function classFromFile(SplFileInfo $file, $basePath) 79 | { 80 | if (static::$guessClassNamesUsingCallback) { 81 | return call_user_func(static::$guessClassNamesUsingCallback, $file, $basePath); 82 | } 83 | 84 | $class = trim(Str::replaceFirst($basePath, '', $file->getRealPath()), DIRECTORY_SEPARATOR); 85 | 86 | return str_replace( 87 | [DIRECTORY_SEPARATOR, ucfirst(basename(app()->path())).'\\'], 88 | ['\\', app()->getNamespace()], 89 | ucfirst(Str::replaceLast('.php', '', $class)) 90 | ); 91 | } 92 | 93 | /** 94 | * Specify a callback to be used to guess class names. 95 | * 96 | * @param callable(SplFileInfo, string): string $callback 97 | * 98 | * @return void 99 | */ 100 | public static function guessClassNamesUsing(callable $callback) 101 | { 102 | static::$guessClassNamesUsingCallback = $callback; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/Exceptions/RbacException.php: -------------------------------------------------------------------------------- 1 | groupBy('value') 21 | ->filter(fn ($element) => $element->count() > 1) 22 | ->collapse() 23 | ->map( 24 | fn (BackedEnum $enum) => Str::of(get_class($enum)) 25 | ->classBasename() 26 | ->append(':', $enum->value) 27 | ); 28 | 29 | $message = __('The following RBAC abilities are duplicated [:duplicates]', [ 30 | 'duplicates' => $duplicates->implode(', '), 31 | ]); 32 | 33 | return new static($message); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/Facades/Rbac.php: -------------------------------------------------------------------------------- 1 | forgetCachedPermissions(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Jobs/ResetPermissions.php: -------------------------------------------------------------------------------- 1 | guard = $guard ?? config('auth.defaults.guard'); 29 | } 30 | 31 | /** 32 | * @return void 33 | */ 34 | public function handle(): void 35 | { 36 | $this->permissions() 37 | ->each(fn (BackedEnum $ability) => StorePermission::run($ability, $this->guard)); 38 | } 39 | 40 | /** 41 | * @return \Illuminate\Support\Collection 42 | */ 43 | protected function permissions(): Collection 44 | { 45 | return Rbac::abilities(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/Jobs/SyncDefinedRoles.php: -------------------------------------------------------------------------------- 1 | definedRoles() 25 | ->map(fn (DefinedRole $role) => $role->handle()); 26 | } 27 | 28 | /** 29 | * @return \Illuminate\Support\Collection 30 | */ 31 | protected function definedRoles(): Collection 32 | { 33 | $value = config('rbac.roles'); 34 | 35 | return collect($value) 36 | ->map(fn (string $role) => app($role)); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Rbac.php: -------------------------------------------------------------------------------- 1 | abilitiesPath = $abilitiesPath; 25 | $this->basePath = $basePath; 26 | } 27 | 28 | /** 29 | * Return the list of all abilities in the application. 30 | */ 31 | public function abilities(): Collection 32 | { 33 | if (null === $this->abilities) { 34 | $this->abilities = $this->discoverAbilities(); 35 | } 36 | 37 | return $this->abilities; 38 | } 39 | 40 | /** 41 | * Discover Abilities in path. 42 | */ 43 | protected function discoverAbilities(): Collection 44 | { 45 | return DiscoverAbilities::within( 46 | abilitiesPath: $this->abilitiesPath, 47 | basePath: $this->basePath 48 | ); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/RbacServiceProvider.php: -------------------------------------------------------------------------------- 1 | name('rbac') 18 | ->hasConfigFile() 19 | ->hasCommands([ 20 | AbilityMakeCommand::class, 21 | DefinedRoleMakeCommand::class, 22 | RbacResetCommand::class, 23 | ]); 24 | } 25 | 26 | public function packageBooted() 27 | { 28 | parent::packageBooted(); 29 | 30 | $this->publishes([ 31 | __DIR__.'/../stubs/ability.stub' => base_path('stubs/ability.stub'), 32 | __DIR__.'/../stubs/defined-role.stub' => base_path('stubs/defined-role.stub'), 33 | ], ['rbac-stubs', 'stubs']); 34 | } 35 | 36 | /** 37 | * @return void 38 | */ 39 | public function packageRegistered() 40 | { 41 | $this->app->bind(Rbac::class, function (Application $app) { 42 | return new Rbac( 43 | abilitiesPath: $app['config']->get('rbac.path'), 44 | basePath: $app->basePath() 45 | ); 46 | }); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /stubs/ability.stub: -------------------------------------------------------------------------------- 1 |