{"id":15064560,"url":"https://github.com/efficiently/authority-controller","last_synced_at":"2025-04-06T20:13:26.356Z","repository":{"id":56975472,"uuid":"13156792","full_name":"efficiently/authority-controller","owner":"efficiently","description":"Authorization PHP package for Laravel 4, 5.0, 5.1, 5.2 and 5.3","archived":false,"fork":false,"pushed_at":"2017-08-30T19:51:35.000Z","size":347,"stargazers_count":155,"open_issues_count":5,"forks_count":17,"subscribers_count":17,"default_branch":"master","last_synced_at":"2025-03-30T19:07:40.765Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://laravel.io/forum/02-03-2014-authority-controller-authorization-library-cancan-port","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/efficiently.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-09-27T17:36:40.000Z","updated_at":"2024-07-18T18:11:08.000Z","dependencies_parsed_at":"2022-08-21T11:50:33.326Z","dependency_job_id":null,"html_url":"https://github.com/efficiently/authority-controller","commit_stats":null,"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/efficiently%2Fauthority-controller","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/efficiently%2Fauthority-controller/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/efficiently%2Fauthority-controller/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/efficiently%2Fauthority-controller/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/efficiently","download_url":"https://codeload.github.com/efficiently/authority-controller/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247543595,"owners_count":20955865,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-09-25T00:20:32.782Z","updated_at":"2025-04-06T20:13:26.324Z","avatar_url":"https://github.com/efficiently.png","language":"PHP","readme":"AuthorityController [![Build Status](https://travis-ci.org/efficiently/authority-controller.png?branch=master)](http://travis-ci.org/efficiently/authority-controller)\n===================\n\nAuthorityController is an PHP authorization library for [Laravel 5.3](http://laravel.com) which restricts what resources a given user is allowed to access.\n\nAll permissions are defined in a single location:\n\n    config/authority-controller.php\n\nand not duplicated across controllers, routes, views, and database queries.\n\nFor [**Laravel 5.2**](http://laravel.com/docs/5.2) supports see [AuthorityController 2.2 branch](https://github.com/efficiently/authority-controller/tree/2.2)\n\nFor [Laravel 5.0 or 5.1](http://laravel.com/docs/5.1) supports see [AuthorityController 2.1 branch](https://github.com/efficiently/authority-controller/tree/2.1)\n\nFor [Laravel 4.1 or 4.2](http://laravel.com/docs/4.2) supports see [AuthorityController 1.2 branch](https://github.com/efficiently/authority-controller/tree/1.2)\n\n#### Demo application\n\nYou can see in action this package with this Laravel 5.3 [**demo application**](https://github.com/efficiently/laravel_authority-controller_app#readme).\n\n#### Origins and Inspirations\n\nIt's an extension of the [`authority-laravel`](https://github.com/authority-php/authority-laravel) package.\n\nAnd a port of the best [Ruby](https://ruby-lang.org) authorization library: [CanCan](https://github.com/ryanb/cancan).\n\n[Authority](https://github.com/authority-php/authority) ports some features of CanCan and this package ports [_almost_](https://github.com/efficiently/authority-controller/blob/master/README.md#missing-features) all the other features.\n\nInstallation\n---------------------------\n\n#### With [Composer](https://getcomposer.org/)\n\n1. Add `authority-controller` package to your `composer.json` file to require AuthorityController:\n\n ```bash\n composer require efficiently/authority-controller:dev-master\n ```\n\n2. Add the service provider to `config/app.php`:\n\n ```php\n     Efficiently\\AuthorityController\\AuthorityControllerServiceProvider::class,\n ```\n\n3. Add the aliases (facades) to your Laravel app config file:\n\n ```php\n     'Params'    =\u003e Efficiently\\AuthorityController\\Facades\\Params::class,\n     'Authority' =\u003e Efficiently\\AuthorityController\\Facades\\Authority::class,\n ```\n\n4. This will allow you to access the Authority class through the static interface you are used to with Laravel components.\n\n ```php\n Authority::can('update', SomeModel::class);\n ```\n\nConfiguration\n-------------\n##### Create Roles and Permissions Tables\n\nWe have provided a basic table structure to get you started in creating your roles and permissions.\n\nPublish them to your migrations directory or copy them directly.\n\n```bash\nphp artisan vendor:publish --provider=\"Efficiently\\AuthorityController\\AuthorityControllerServiceProvider\" --tag=\"migrations\"\n```\n\nRun the migrations\n\n```bash\nphp artisan migrate\n```\n\nThis will create the following tables\n\n- roles\n- role_user\n- permissions\n\nTo utilize these tables, you can add the following methods to your `User` model. You will also need to create Role and Permission Model stubs (replacing `App\\Authority\\` with you own namespace)..\n\n```php\n    //app/User.php\n    public function roles()\n    {\n        return $this-\u003ebelongsToMany(Authority\\Role::class)-\u003ewithTimestamps();\n    }\n\n    public function permissions()\n    {\n        return $this-\u003ehasMany(Authority\\Permission::class);\n    }\n\n    public function hasRole($key)\n    {\n        $hasRole = false;\n        foreach ($this-\u003eroles as $role) {\n            if ($role-\u003ename === $key) {\n                $hasRole = true;\n                break;\n            }\n        }\n\n        return $hasRole;\n    }\n```\n\n```php\n    //app/Authority/Role.php\n    \u003c?php\n\n    namespace App\\Authority;\n\n    use Illuminate\\Database\\Eloquent\\Model;\n\n    class Role extends Model {}\n```\n\n```php\n    //app/Authority/Permission.php\n    \u003c?php\n\n    namespace App\\Authority;\n\n    use Illuminate\\Database\\Eloquent\\Model;\n\n    class Permission extends Model {}\n```\n\n##### Init resource filters and controller methods\nIn your `app/Http/Controllers/Controller.php` file, add the `ControllerAdditions` trait and disable the use of the `AuthorizesRequests` trait:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Foundation\\Bus\\DispatchesJobs;\nuse Illuminate\\Routing\\Controller as BaseController;\nuse Illuminate\\Foundation\\Validation\\ValidatesRequests;\nuse Illuminate\\Foundation\\Auth\\Access\\AuthorizesRequests;\nuse Efficiently\\AuthorityController\\ControllerAdditions as AuthorityControllerAdditions;\n\nclass Controller extends BaseController\n{\n    // use AuthorizesRequests;\n    use DispatchesJobs, ValidatesRequests;\n    use AuthorityControllerAdditions;\n    //code...\n}\n```\n\n**NB:** If you really need the default Laravel Authorization system, you can use the `AuthorizesRequests` trait, if you alias its `authorize` and `authorizeResource` methods, like this:\n\n```php\n\u003c?php\n//code...\nclass Controller extends BaseController\n{\n    use DispatchesJobs, ValidatesRequests;\n    use AuthorizesRequests, AuthorityControllerAdditions {\n        AuthorityControllerAdditions::authorize insteadof AuthorizesRequests;\n        AuthorizesRequests::authorize as illuminateAuthorize;\n        AuthorizesRequests::authorizeResource as illuminateAuthorizeResource;\n    }\n    //code...\n}\n```\n\nGetting Started\n---------------\nAuthorityController expects that `auth()-\u003euser()` return the current authenticated user. Now, by default Laravel 5 handles [this](https://laravel.com/docs/5.3/authentication#retrieving-the-authenticated-user).\n\n##### Defining Authority rules\n\nUser permissions are defined in an AuthorityController configuration file.\n\nYou can publish the AuthorityController default configuration file with the command below:\n\n```bash\nphp artisan vendor:publish --provider=\"Efficiently\\AuthorityController\\AuthorityControllerServiceProvider\" --tag=\"config\"\n```\n\nThis will place a copy of the configuration file at `config/authority-controller.php`. The config file includes an `initialize` function, which is a great place to setup your rules and aliases.\n\n```php\n//config/authority-controller.php\n\u003c?php\n\n$serializer = new SuperClosure\\Serializer;\nreturn [\n    'initialize' =\u003e $serializer-\u003eserialize(function ($authority) {\n        $user = auth()-\u003eguest() ? new App\\User : $authority-\u003egetCurrentUser();\n\n        // Action aliases. For example:\n        $authority-\u003eaddAlias('moderate', ['read', 'update', 'delete']);\n\n        // Define abilities for the passed in user here. For example:\n        if ($user-\u003ehasRole('admin')) {\n            $authority-\u003eallow('manage', 'all');\n        } else {\n            $authority-\u003eallow('read', 'all');\n        }\n    })\n];\n```\n\nSee [Defining Authority rules](https://github.com/efficiently/authority-controller/wiki/Defining-Authority-rules) for details.\n\n##### Check Authority rules \u0026 Authorization\n\nThe current user's permissions can then be checked using the `Authority::can()` and `Authority::cannot()` methods in the view and controller.\n\n```\n@if (Authority::can('update', $article))\n    {{ link_to_route(\"articles.edit\", \"Edit\", $article-\u003eid) }}\n@endif\n```\n\nSee [Checking Authority rules](https://github.com/efficiently/authority-controller/wiki/Checking-Authority-rules) for more information\n\nThe `authorize()` method in the controller will throw an exception if the user is not able to perform the given action.\n\n```php\npublic function show($id)\n{\n    $this-\u003earticle = App\\Article::find($id);\n    $this-\u003eauthorize('read', $this-\u003earticle);\n}\n```\n\nSetting this for every action can be tedious, therefore the `loadAndAuthorizeResource()` method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for every action.\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nclass ArticlesController extends Controller\n{\n\n    public function __construct()\n    {\n        $this-\u003eloadAndAuthorizeResource();\n    }\n\n    public function show($id)\n    {\n        // $this-\u003earticle is already loaded and authorized\n    }\n}\n```\n\nSee [Authorizing Controller Actions](https://github.com/efficiently/authority-controller/wiki/authorizing-controller-actions) for more information.\n\n##### Exception Handling\n\nThe `Efficiently\\AuthorityController\\Exceptions\\AccessDenied` exception is thrown when calling `authorize()` in the controller and the user is not able to perform the given action. A message can optionally be provided.\n\n```php\nAuthority::authorize('read', 'App\\Product', 'Unable to read this product.');\n```\n\nYou can catch the exception and modify its behavior in the `render()` method of the `app/Exceptions/Handler.php` file. For example here we set the error message to a flash and redirect to the home page.\n\n```php\n//app/Exceptions/Handler.php\n\n   /**\n    * Render an exception into an HTTP response.\n    *\n    * @param  \\Illuminate\\Http\\Request  $request\n    * @param  \\Exception  $e\n    * @return \\Illuminate\\Http\\Response\n    */\n    public function render($request, Exception $e)\n    {\n        //code...\n        if ($e instanceof \\Efficiently\\AuthorityController\\Exceptions\\AccessDenied) {\n            $msg = $e-\u003egetMessage();\n            \\Log::error('Access denied! '.$msg);\n\n            return redirect('/home')-\u003ewith('flash_alert', $msg);\n        }\n\n        return parent::render($request, $e);\n    }\n\n    //code...\n```\n\nSee [Exception Handling](https://github.com/efficiently/authority-controller/wiki/Exception-Handling) for more information.\n\nDocumentations\n--------------\n##### Wiki Docs\n\n* [Defining Authority rules](https://github.com/efficiently/authority-controller/wiki/Defining-Authority-rules)\n* [Checking Authority rules](https://github.com/efficiently/authority-controller/wiki/Checking-Authority-rules)\n* [Authorizing Controller Actions](https://github.com/efficiently/authority-controller/wiki/Authorizing-Controller-Actions)\n* [Exception Handling](https://github.com/efficiently/authority-controller/wiki/Exception-Handling)\n* [See more](https://github.com/efficiently/authority-controller/wiki)\n\n##### Authority Docs\n\nAuthority [introduction](https://github.com/authority-php/authority/blob/2.2.2/readme.md#introduction).\n\nAuthority-Laravel [general usage](https://github.com/authority-php/authority-laravel/blob/2.4.3/README.md#general-usage).\n\n##### CanCan Wiki Docs\n\nBecause AuthorityController is a CanCan port, you can also read the Wiki docs of CanCan [here](https://github.com/ryanb/cancan/wiki).\n\nController additions\n--------------------\nYour controllers have now a `$params` property:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Controllers;\n\nclass ProductsController extends Controller\n{\n    //code...\n\n    public function update($id)\n    {\n        $this-\u003eparams['id'] == $id;//-\u003e true\n        $this-\u003eparams['product'];//-\u003e [\"name\" =\u003e \"Best movie\"]\n        $this-\u003eparams['controller'];//-\u003e 'products'\n        $this-\u003eparams['action'];//-\u003e 'update'\n        //code...\n    }\n\n    //code...\n}\n```\n\nChangelog\n---------\n#### 2.3.0-dev\n* Laravel 5.3 support!\n\n#### 2.2.0\n* Laravel 5.2 support!\n\n#### 2.1.1\n* Update installation instructions for Laravel \u003e= 5.1.11\n\n#### 2.1.0\n* Laravel 5.1 support!\n\n#### 2.0.1\n*  Replace the deprecated package [`illuminate/html`](https://github.com/illuminate/html) package by the [`laravelcollective/html`](https://github.com/LaravelCollective/html) package\n* Autoloading migrations class is useless, see issue [#30](https://github.com/efficiently/authority-controller/issues/30) \u003csmall\u003e(reported by @Fnatte)\u003c/small\u003e\n* Autoloading class from `tests` directory are now only available in Composer's dev mode to avoid conflicts\n\n#### 2.0.0\n* Laravel 5.0 support!\n* Use your Laravel Aliases to resolve your models namespace name.\n* Or auto guessing them, e.g. `User` =\u003e `App\\User`\n* Add a new config option `controllerClass` which is by default `Illuminate\\Routing\\Controller`\n* Support Route Model Binding in the Parameters class.\n  See: http://laravel.com/docs/5.0/routing#route-model-binding and issue [#21](https://github.com/efficiently/authority-controller/issues/21)\n* Use [authority-laravel](https://github.com/authority-php/authority-laravel) package instead of [authority-l4](https://github.com/machuga/authority-l4).\n* Upgrade Notes \u003csmall\u003e(if you used previously this package with Laravel 4)\u003c/small\u003e:\n  * Move your `authory-controller` config file from `app/config/packages/efficiently/authority-controller/config.php` to `config/authority-controller.php`\n  * Publish the `authory-controller` migrations files \u003csmall\u003e(see the section [Create Roles and Permissions Tables](https://github.com/efficiently/authority-controller/blob/2.0/README.md#create-roles-and-permissions-tables) of this README)\u003c/small\u003e\n\n#### 1.2.4\n* Add `BaseController::flushAuthorityEvents()` static method.\n  Useful for functional tests with Codeception (see issue [#14](https://github.com/efficiently/authority-controller/issues/14) and [this Wiki page](https://github.com/efficiently/authority-controller/wiki/Testing-Authority-rules#functional-tests-with-codeception) for more explanations).\n* Fix User::hasRoles() method to avoid duplicate roles.\n\n#### 1.2.3\n* Follow [PSR-2](http://www.php-fig.org) coding style\n\n#### 1.2.2\n* Run tests with Laravel 4.2\n\n#### 1.2.1\n* Fix `composer.json` file.\n\n#### 1.2.0\n* Security fix: conditional callback was never evaluated when an actual instance object was present.\n* Non backwards compatible: Deny rules override prior rules and Allow rules don't override prior rules but instead are logically or'ed (fix [#5](https://github.com/efficiently/authority-controller/issues/5)).\n  Match more CanCan default behavior unlike `authority-php\\authority` package.\n  Read the Wiki doc for more information: [Authority-Precedence](https://github.com/efficiently/authority-controller/wiki/Authority-Precedence).\n* Support PHP 5.4, 5.5, 5.6 and HipHop Virtual Machine (hhvm).\n* Update [`Parameters`](https://github.com/efficiently/authority-controller/blob/18c2ad7788385da4e0309708772ea40cc8be0f53/src/Efficiently/AuthorityController/Parameters.php#L46) class to allow custom routes with `id` and `parent_id` routes's parameters (fix [#6](https://github.com/efficiently/authority-controller/issues/6)).\n\n#### 1.1.3\n* Upgrade Authority-L4 package to fix Laravel 4.1 support.\n\n#### 1.1.2\n* Tweak the mock system who simulates Eloquent's constructor method.\n\n#### 1.1.1\n* Less intrusive parameters injection in the controllers\n    * Check if the current resolved controller responds to paramsBeforeFilter method. Otherwise the application crash.\n    * Use the Controller alias of the current Laravel application instead of a hardcoded class name.\n\n#### 1.1.0\n* First beta release for Laravel **4.1** compatibility.\n* Non backwards compatible with Laravel **4.0**.\n\n#### 1.0.0\n* First stable release, only compatible with Laravel **4.0**.\n* For Laravel **4.1** supports, see [AuthorityController 1.1 branch](https://github.com/efficiently/authority-controller/tree/1.1).\n* Fix AccessDenied class, the exception message didn't fallback to the default message if it was empty.\n\n#### 0.10.0\n* Non backwards compatible: `Params::get('controller')` behaviour is now like Rails. It returns controller name in snake_case and in plural.\n\n#### 0.9.0\n* First beta release\n\nMissing features\n----------------\n1. In `ControllerResource` class, the [`#load_collection`](https://github.com/ryanb/cancan/blob/1.6.10/lib/cancan/controller_resource.rb#L80) method, who uses in the `User` model [`#accessible_by`](https://github.com/ryanb/cancan/blob/1.6.10/lib/cancan/model_additions.rb#L22) method. Looks complicated.\n  Instead, use specific query scopes with `collectionScope` option to filtering your data in your collection (e.g. `index`) controller actions.\n  Because you'll allowing/denying access by roles or check user's authorizations on each record of the collection.\n2. In `Ability` class, the [`#attributes_for`](https://github.com/ryanb/cancan/blob/1.6.10/lib/cancan/ability.rb#L221) method.\n  Looks useless with `Authority` because rules conditions are only possible by `Closure` not by associative array. And CanCan handles `#attribute_for` only for `Hash` (associative array) conditions.\n3. `#skip_*` methods in `ControllerAdditions`.\n4. For `allow()` and `deny()` methods of `Authority`, the third argument isn't an optional hash (associative array) of conditions but an anonymous function (Closure):\n\n```php\n$authority-\u003eallow('update', 'App\\Product', function ($self, $product) {\n    return $product-\u003eavailable === true;\n});\n```\n\nGood to know\n------------\n#### Compatibility\nIt's **only** compatible with **PHP \u003e= 5.6** and **Laravel \u003e= 5.3** framework.\n\n#### Differences between CanCan and AuthorityController\nSee Wiki page [Differences between CanCan and AuthorityController](https://github.com/efficiently/authority-controller/wiki/Differences-between-CanCan-and-AuthorityController)\n\n#### Philosophy\nIt's following the D.R.W.J.P.I. principle:\n\n\u003e Don't Reinvent the Wheel, Just Port It !\n\u003e -- \u003ccite\u003e(c) 2013 A.D.\u003c/cite\u003e\n\nQuestions or Problems?\n----------------------\nIf you have any issues with AuthorityController, please add an [issue on GitHub](https://github.com/efficiently/authority-controller/issues) or fork the project and send a pull request.\n\nTo get the tests running you should install PHPUnit and run `phpunit tests`.\n\n\nSpecial Thanks\n--------------\nAuthorityController was _heavily_ inspired by [CanCan](https://github.com/ryanb/cancan) and uses [Authority-Laravel](https://github.com/authority-php/authority-laravel).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fefficiently%2Fauthority-controller","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fefficiently%2Fauthority-controller","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fefficiently%2Fauthority-controller/lists"}