All jobs

Add Role-Based Access Control (RBAC) to a Yii2 App

Yes. An agent configures authManager in a Yii2 app, defines roles and permissions in a console command, guards controllers with them and tests each role.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent picks up the Linear issue and reads how access works in the app today, which in a Yii2 basic app is barely at all. In a repository laid out like yiisoft/yii2-app-basic, controllers/SiteController.php attaches AccessControl to a single action: logout is allowed for the @ role, meaning any signed-in user, and a VerbFilter restricts it to POST. Neither config/web.php nor config/console.php defines an authManager component, so Yii::$app->user->can() has nothing to ask. config/__autocomplete.php, the IDE hint file, already declares authManager as yii\rbac\DbManager, which records an intention nobody wired up. Users come from the static array in models/User.php, with ids 100 for admin and 101 for demo.

The first decision is where roles are stored, and the agent makes it from what it read and says why. DbManager keeps roles in four tables created by yii migrate --migrationPath=@yii/rbac/migrations, and it needs the MySQL database that config/db.php names but that nothing in the app opens: no model is an ActiveRecord, and the Codeception suites run without one. PhpManager keeps the same data in PHP files under @app/rbac. With users in an array and no database in use, the agent configures yii\rbac\PhpManager in config/web.php, config/console.php and config/test.php, corrects the hint in config/__autocomplete.php, and notes that moving to DbManager later is a class name and one migration command.

Roles are defined in code that can be rerun. Next to commands/HelloController.php the agent adds commands/RbacController.php with an actionInit that calls removeAll(), creates the permissions the issue names, creates a member role and an admin role that inherits from it with addChild, and assigns admin to user 100 and member to user 101. Running php yii rbac/init writes rbac/items.php and rbac/assignments.php, which are committed so a fresh checkout has the same roles. When the issue asks for ownership checks, such as editing only your own record, the agent writes a class extending yii\rbac\Rule and attaches it to an updateOwn permission, which lands in rbac/rules.php.

Then it applies the roles where requests arrive. The controller the issue names gets an AccessControl behavior whose rules list roles by permission name, so a guest is sent to site/login and a signed-in user without the permission gets a 403. The navigation in views/layouts/_header.php hides the link behind Yii::$app->user->can(), in the style of the existing visible conditions on Login and Logout. Tests follow the suites already there. A functional Cest uses amLoggedInAs(100) and amLoggedInAs(101), the helper tests/Functional/LoginFormCest.php already demonstrates, to assert that admin sees the page, demo gets 403 and a guest is redirected. A unit test calls checkAccess for each id and permission, and one more runs rbac/init twice to show it is repeatable. The agent finishes with composer tests, composer static and composer cs, and leaves the generated files under rbac/ out of the PHPStan and coding-standard paths.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "A Linear issue labeled agent says: \"Add role-based access control. Add an admin area at /admin with a dashboard page that only the admin user can open; the demo user must get a 403 and a guest must be sent to the login page. Show the Admin link in the navigation only to users who can open it.\" Do this work in this Yii2 repository. Read composer.json, config/web.php, config/console.php, config/test.php, config/__autocomplete.php, config/db.php, models/User.php, controllers/SiteController.php, commands/HelloController.php, views/layouts/_header.php, codeception.yml and the tests directory first. Install PHP 8.2 or later and Composer if the sandbox lacks them and run composer install; do not commit the cookie validation key it writes into config/web.php. Choose between yii\\rbac\\PhpManager and DbManager from what the app already uses and explain the choice. Configure authManager in the web, console and test configs. Add a console command rbac/init that rebuilds permissions, a member role, an admin role that inherits from it, and the assignments for the two existing users, and commit the files it generates. Add an AdminController guarded by AccessControl with the permission as its role, and hide the navigation link behind Yii::$app->user->can(). Write functional tests for admin, demo and guest using amLoggedInAs, and unit tests for checkAccess and for running rbac/init twice. Run composer tests, composer static and composer cs. Open a pull request that links back to the issue, lists roles, permissions and assignments in a table, and quotes the three command outputs.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
  1. Get an API key. In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
  2. Send the request. POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
  3. Read what came back. Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

What comes back

The pull request links the Linear issue and adds commands/RbacController.php, controllers/AdminController.php with its view, the generated rbac/items.php and rbac/assignments.php, and the new test classes. It changes the three config files, config/__autocomplete.php and views/layouts/_header.php. The description opens with a table of roles, the permissions each holds, which role inherits from which and which user id has which role, followed by the reason for the storage choice and the output of the three Composer scripts.

A reviewer checks the table against the issue before reading code, because RBAC mistakes are usually mistakes of intent. Then they check that the controller's rule names a permission and not a role, so later roles can be granted the permission without editing the controller. They confirm the 403 and redirect cases are asserted in the Cest file and not only the allowed one, and that rbac/init starts with removeAll(), which makes it safe to rerun and destructive to manual assignments. With PhpManager, the web server writes to the files under rbac/ whenever an assignment changes at runtime, so the reviewer also decides whether those files stay in the repository once real users exist.

Run it on every Linear issue labelled agent

In the console, connect Linear under Settings → Connections and add an automation on the Project with a linear trigger on linear.issue.labeled and the label agent. Each issue that gains the label starts one run in the Project's repository with the issue after the saved prompt, and the run opens a pull request that links back. The trigger fires only when the person who added the label is in your Rush org, and changes made by an app integration never fire it.

Access rules tend to arrive as a stream of small issues: a new permission, a role for support staff, an ownership rule. Each becomes its own run and its own pull request with the roles table updated, and the automation's max_runs_per_hour caps how many start when a backlog is labelled at once.

The use case this job follows, with its automation and trigger: Turn a Linear label into a PR.

Why run it on Rush?

Access control is easy to write and easy to get subtly wrong, and the only convincing check is to sign in as each kind of user and try the door. In its Rush sandbox the agent installs PHP, generates the RBAC files with the real console command and runs the functional suite as admin, as demo and as a guest. The commands and their output are kept in the run's transcript, so the 403 the pull request claims is one a reviewer can find in the test output.

It also turns a labelled issue into a reviewed change with no laptop in the path. The run starts when the label lands, works in its own checkout, and leaves a pull request tied to the issue. Several labelled issues run side by side without sharing a working tree, which matters here because each one regenerates the same files under rbac/.

Frequently asked questions

PhpManager or DbManager: which should a real app use?

DbManager once users live in a database, since assignments then change at runtime and belong beside the user rows. PhpManager suits an app like this template, where users are a PHP array and nothing opens the database. The two share one interface, so the console command, the AccessControl rules and the tests stay the same when the component's class changes.

How do roles get assigned to new users?

Through Yii::$app->authManager->assign($role, $userId), called wherever users are created. The template has no signup, so rbac/init assigns roles to the two hardcoded ids. An app with registration would assign a default role in its signup code, or list one under defaultRoles in the component config.

Does it replace the existing AccessControl on logout?

No. The @ rule on logout already says what it should: any authenticated user may log out. The agent leaves SiteController as it is and adds permission-based rules only on the controllers the issue covers.

Can it add ownership rules, like editing only your own posts?

Yes. That is what yii\rbac\Rule is for: a class whose execute() compares the current user id with the record passed in params. The agent attaches it to an updateOwn permission, makes the general permission its child as the Yii guide's own example does, and writes tests for the owner, a non-owner and an admin.

More Yii jobs

The same job on other stacks

More jobs like this: Turn a Linear label into a PR

Keep reading