{"id":14966351,"url":"https://github.com/yiisoft/rbac","last_synced_at":"2025-05-16T12:12:02.276Z","repository":{"id":32851909,"uuid":"140871085","full_name":"yiisoft/rbac","owner":"yiisoft","description":"Role based access control","archived":false,"fork":false,"pushed_at":"2025-04-04T12:28:29.000Z","size":424,"stargazers_count":69,"open_issues_count":11,"forks_count":23,"subscribers_count":23,"default_branch":"master","last_synced_at":"2025-04-27T17:40:23.316Z","etag":null,"topics":["access-control","hacktoberfest","rbac","yii3"],"latest_commit_sha":null,"homepage":"https://www.yiiframework.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/yiisoft.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":".github/CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":".github/SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"open_collective":"yiisoft","github":["yiisoft"]}},"created_at":"2018-07-13T16:43:41.000Z","updated_at":"2025-04-04T12:28:31.000Z","dependencies_parsed_at":"2023-12-25T17:27:08.083Z","dependency_job_id":"6599f331-e19b-4f97-8769-1cc457cfb52c","html_url":"https://github.com/yiisoft/rbac","commit_stats":{"total_commits":171,"total_committers":19,"mean_commits":9.0,"dds":0.5789473684210527,"last_synced_commit":"9cee78e4f5da53411a9a019a969b677dddc4594e"},"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Frbac","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Frbac/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Frbac/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/yiisoft%2Frbac/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/yiisoft","download_url":"https://codeload.github.com/yiisoft/rbac/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252831463,"owners_count":21810809,"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":["access-control","hacktoberfest","rbac","yii3"],"created_at":"2024-09-24T13:36:15.529Z","updated_at":"2025-05-16T12:12:02.256Z","avatar_url":"https://github.com/yiisoft.png","language":"PHP","funding_links":["https://opencollective.com/yiisoft","https://github.com/sponsors/yiisoft"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://github.com/yiisoft\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://yiisoft.github.io/docs/images/yii_logo.svg\" height=\"100px\" alt=\"Yii\"\u003e\n    \u003c/a\u003e\n    \u003ch1 align=\"center\"\u003eYii Role-Based Access Control\u003c/h1\u003e\n    \u003cbr\u003e\n\u003c/p\u003e\n\n[![Latest Stable Version](https://poser.pugx.org/yiisoft/rbac/v)](https://packagist.org/packages/yiisoft/rbac)\n[![Total Downloads](https://poser.pugx.org/yiisoft/rbac/downloads)](https://packagist.org/packages/yiisoft/rbac)\n[![Build status](https://github.com/yiisoft/rbac/actions/workflows/build.yml/badge.svg)](https://github.com/yiisoft/rbac/actions/workflows/build.yml)\n[![codecov](https://codecov.io/gh/yiisoft/rbac/graph/badge.svg?token=95SVWYEXO1)](https://codecov.io/gh/yiisoft/rbac)\n[![Mutation testing badge](https://img.shields.io/endpoint?style=flat\u0026url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fyiisoft%2Frbac%2Fmaster)](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/rbac/master)\n[![static analysis](https://github.com/yiisoft/rbac/workflows/static%20analysis/badge.svg)](https://github.com/yiisoft/rbac/actions?query=workflow%3A%22static+analysis%22)\n[![type-coverage](https://shepherd.dev/github/yiisoft/rbac/coverage.svg)](https://shepherd.dev/github/yiisoft/rbac)\n\nThis package provides [RBAC](https://en.wikipedia.org/wiki/Role-based_access_control) (Role-Based Access Control)\nlibrary. It is used in [Yii Framework](https://yiiframework.com) but is usable separately as well.\n\n## Features\n\n- Flexible RBAC hierarchy with roles, permissions, and rules.\n- Role inheritance.\n- Data could be passed to rules when checking access.\n- Multiple storage adapters.\n- Separate storages could be used for user-role assignments and role hierarchy.\n- API to manage RBAC hierarchy.\n\n## Requirements\n\n- PHP 8.1 or higher.\n\n## Installation\n\nThe package could be installed with [Composer](https://getcomposer.org):\n\n```shell\ncomposer require yiisoft/rbac\n```\n\nOne of the following storages could be installed as well:\n\n- [PHP storage](https://github.com/yiisoft/rbac-php) - PHP file storage;\n- [DB storage](https://github.com/yiisoft/rbac-db) - database storage based on [Yii DB](https://github.com/yiisoft/db);\n- [Cycle DB storage](https://github.com/yiisoft/rbac-cycle-db) - database storage based on\n  [Cycle DBAL](https://github.com/cycle/database).\n\nAlso, there is a rule factory implementation - [Rules Container](https://github.com/yiisoft/rbac-rules-container) (based\non [Yii Factory](https://github.com/yiisoft/factory)).\n\nAll these can be replaced with custom implementations.\n\n## General usage\n\n### Setting up manager\n\nFirst step when using RBAC is to configure an instance of `Manager`:\n\n```php\nuse Yiisoft\\Rbac\\AssignmentsStorageInterface;\nuse Yiisoft\\Rbac\\ItemsStorageInterface;\nuse Yiisoft\\Rbac\\RuleFactoryInterface;\n\n/**\n* @var ItemsStorageInterface $itemsStorage\n* @var AssignmentsStorageInterface $assignmentsStorage\n* @var RuleFactoryInterface $ruleFactory\n*/\n$manager = new Manager($itemsStorage, $assignmentsStorage, $ruleFactory);\n```\n\nIt requires the following dependencies:\n\n- Items storage (hierarchy itself).\n- Assignments storage where user IDs are mapped to roles.\n- Rule factory. Creates a rule instance by a given name.\n\nWhile storages are required, rule factory is optional and, when omitted, `SimpleRuleFactory` will be used. For more\nadvanced usage, such as resolving rules by aliases and passing arguments in rules constructor, install\n[Rules Container](https://github.com/yiisoft/rbac-rules-container) additionally or write your own implementation.\n\nA few tips for choosing storage backend:\n\n- Roles and permissions could usually be considered \"semi-static,\" as they only change when you update your application\n  code, so it may make sense to use PHP storage for it.\n- Assignments, on the other hand, could be considered \"dynamic.\" They change more often: when creating a new user,\n  or when updating a user role from within your application. So it may make sense to use database storage for assignments.\n\n### Managing RBAC hierarchy\n\nBefore being able to check for permissions, an RBAC hierarchy must be defined. Usually it is done via either console\ncommands or migrations. Hierarchy consists of permissions, roles, and rules:\n\n- Permissions are granules of access such as \"create a post\" or \"read a post.\"\n- A role is what is assigned to the user. The Role is granted one or more permissions. Typical roles are \"manager\" or\n  \"admin.\"\n- Rule is a PHP class that has given some data answers a single question \"given the data has the user the permission\n  asked for.\"\n\nTo create a permission, use the following code:\n\n```php\nuse Yiisoft\\Rbac\\ManagerInterface;\nuse Yiisoft\\Rbac\\Permission;\n\n/** @var ManagerInterface $manager */\n$manager-\u003eaddPermission(new Permission('createPost'));\n$manager-\u003eaddPermission(new Permission('readPost'));\n$manager-\u003eaddPermission(new Permission('deletePost'));\n```\n\nTo add some roles:\n\n```php\nuse Yiisoft\\Rbac\\ManagerInterface;\nuse Yiisoft\\Rbac\\Role;\n\n/** @var ManagerInterface $manager */\n$manager-\u003eaddRole(new Role('author'));\n$manager-\u003eaddRole(new Role('reader'));\n```\n\nNext, we need to attach permissions to roles:\n\n```php\nuse Yiisoft\\Rbac\\ManagerInterface;\n\n/** @var ManagerInterface $manager */\n$manager-\u003eaddChild('reader', 'readPost');\n$manager-\u003eaddChild('author', 'createPost');\n$manager-\u003eaddChild('author', 'deletePost');\n$manager-\u003eaddChild('author', 'reader');\n```\n\nHierarchy for the example above:\n\n```mermaid\nflowchart LR\n  createPost:::permission ---\u003e author:::role\n  readPost:::permission --\u003e reader:::role --\u003e author:::role\n  deletePost:::permission ---\u003e author:::role\n  classDef permission fill:#fc0,stroke:#000,color:#000\n  classDef role fill:#9c0,stroke:#000,color:#000\n```\n\nSometimes, basic permissions are not enough. In this case, rules are helpful. Rules are PHP classes that could be\nadded to permissions and roles:\n\n```php\nuse Yiisoft\\Rbac\\Item;\nuse Yiisoft\\Rbac\\RuleContext;\nuse Yiisoft\\Rbac\\RuleInterface;\n\nclass ActionRule implements RuleInterface\n{\n    public function execute(?string $userId, Item $item, RuleContext $context): bool;\n    {\n        return $context-\u003egetParameterValue('action') === 'home';\n    }\n}\n```\n\nWith rule added, the role or permission is considered only when rule's `execute()` method returns `true`.\n\nThe parameters are:\n\n- `$userId` is user id to check permission against;\n- `$item` is RBAC hierarchy item that rule is attached to;\n- `$context` is a rule context providing access to parameters.\n\nTo use rules with `Manager`, specify their names with added permissions or roles:\n\n```php\nuse Yiisoft\\Rbac\\ManagerInterface;\nuse Yiisoft\\Rbac\\Permission;\n\n/** @var ManagerInterface $manager */\n$manager-\u003eaddPermission( \n    (new Permission('viewList'))-\u003ewithRuleName(ActionRule::class),\n);\n\n// or\n\n$manager-\u003eaddRole(\n    (new Role('NewYearMaintainer'))-\u003ewithRuleName(NewYearOnlyRule::class)\n);\n```\n\nThe rule names `action_rule` and `new_year_only_rule` are resolved to `ActionRule` and `NewYearOnlyRule` class instances\naccordingly via rule factory.\n\nIf you need to aggregate multiple rules at once, use composite rule:\n\n```php\nuse Yiisoft\\Rbac\\CompositeRule;\n\n// Fresh and owned\n$compositeRule = new CompositeRule(CompositeRule::AND, [FreshRule::class, OwnedRule::class]);\n\n// Fresh or owned\n$compositeRule = new CompositeRule(CompositeRule::OR, [FreshRule::class, OwnedRule::class]);\n```\n\n### Assigning roles to users\n\nTo assign a certain role to a user with a given ID, use the following code:\n\n```php\nuse Yiisoft\\Rbac\\ManagerInterface;\n\n/** @var ManagerInterface $manager */\n$userId = 100;\n$manager-\u003eassign('author', $userId);\n```\n\nIt could be done in an admin panel, via console command, or it could be built into the application business logic\nitself.\n\n### Check for permission\n\nTo check for permission, obtain an instance of `Yiisoft\\Access\\AccessCheckerInterface` and use it:\n\n```php\nuse Psr\\Http\\Message\\ResponseInterface; \nuse Yiisoft\\Access\\AccessCheckerInterface;\n\npublic function actionCreate(AccessCheckerInterface $accessChecker): ResponseInterface\n{\n    $userId = getUserId();\n\n    if ($accessChecker-\u003euserHasPermission($userId, 'createPost')) {\n        // author has permission to create post\n    }\n}\n```\n\nSometimes you need to add guest-only permission, which is not assigned to any user ID. In this case, you can specify a\nrole which is assigned to guest user:\n\n```php\nuse Yiisoft\\Access\\AccessCheckerInterface;\nuse Yiisoft\\Rbac\\Permission;\nuse Yiisoft\\Rbac\\Role;\n\n/** \n * @var ManagerInterface $manager\n * @var AccessCheckerInterface $accessChecker \n */\n$manager-\u003esetGuestRoleName('guest');\n$manager-\u003eaddPermission(new Permission('signup'));\n$manager-\u003eaddRole(new Role('guest'));\n$manager-\u003eaddChild('guest', 'signup');\n\n$guestId = null;\nif ($accessChecker-\u003euserHasPermission($guestId, 'signup')) {\n    // Guest has \"signup\" permission.\n}\n```\n\nIf there is a rule involved, you may pass extra parameters:\n\n```php\nuse Yiisoft\\Rbac\\ManagerInterface;\n\n/** @var ManagerInterface $manager */\n$anotherUserId = 103;\nif (!$manager-\u003euserHasPermission($anotherUserId, 'viewList', ['action' =\u003e 'home'])) {\n    echo 'reader hasn\\'t \"index\" permission';\n}\n```\n\n## Documentation\n\n- [Internals](docs/internals.md)\n\nIf you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for that.\nYou may also check out other [Yii Community Resources](https://www.yiiframework.com/community).\n\n## License\n\nThe Yii Role-Based Access Control is free software. It is released under the terms of the BSD License.\nPlease see [`LICENSE`](./LICENSE.md) for more information.\n\nMaintained by [Yii Software](https://www.yiiframework.com/).\n\n## Support the project\n\n[![Open Collective](https://img.shields.io/badge/Open%20Collective-sponsor-7eadf1?logo=open%20collective\u0026logoColor=7eadf1\u0026labelColor=555555)](https://opencollective.com/yiisoft)\n\n## Follow updates\n\n[![Official website](https://img.shields.io/badge/Powered_by-Yii_Framework-green.svg?style=flat)](https://www.yiiframework.com/)\n[![Twitter](https://img.shields.io/badge/twitter-follow-1DA1F2?logo=twitter\u0026logoColor=1DA1F2\u0026labelColor=555555?style=flat)](https://twitter.com/yiiframework)\n[![Telegram](https://img.shields.io/badge/telegram-join-1DA1F2?style=flat\u0026logo=telegram)](https://t.me/yii3en)\n[![Facebook](https://img.shields.io/badge/facebook-join-1DA1F2?style=flat\u0026logo=facebook\u0026logoColor=ffffff)](https://www.facebook.com/groups/yiitalk)\n[![Slack](https://img.shields.io/badge/slack-join-1DA1F2?style=flat\u0026logo=slack)](https://yiiframework.com/go/slack)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyiisoft%2Frbac","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fyiisoft%2Frbac","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fyiisoft%2Frbac/lists"}