Skip to content

Instantly share code, notes, and snippets.

@machour
Last active Sep 17, 2021
Embed
What would you like to do?
[yii2] How to migrate from PHP Rbac to DB Rbac
<?php
namespace console\controllers;
/**
* I needed to migrate from files-based RBAC to db-based RBAC, here's how I've done it
*
* - Before executing the migration, rename your old `authManager` component to `authManagerPhp`
* - Add the new `authManager` component as follow:
* 'authManager' => [
* 'class' => \yii\rbac\DbManager::class,
* // 'cache' => 'cache',
* ],
* - Update rules mapping in $rulesMapping
* - Run ./yii migrate-rbac/to-db
* - Uncomment the `cache` property in the freshly created authManager
* - Test your app
*
*
* If anything goes wrong, run `./yii migrate/down 4 --migration-path=vendor/yiisoft/yii2/rbac/migrations`
* to drop Rbac db migrations before trying again
*/
class MigrateRbacController extends yii\console\Controller
{
public function actionToDb()
{
$this->run('migrate/up', ['migrationPath' => '@vendor/yiisoft/yii2/rbac/migrations']);
/** @var \yii\rbac\ManagerInterface $oldAuth */
$oldAuth = Yii::$app->authManagerPhp;
$newAuth = Yii::$app->authManager;
$rulesMapping = [
// Example:
// 'news-update' => \common\rbac\rules\AuthorRule::class,
// 'leasing-view' => \common\rbac\rules\BrandUserRule::class,
];
// 1 - migrate all rules
foreach ($oldAuth->getRules() as $rule) {
$newRule = new $rulesTranslation[$rule->name]();
$newAuth->add($newRule);
}
// 2 - migrate all permissions
foreach ($oldAuth->getPermissions() as $permission) {
$newPermission = $newAuth->createPermission($permission->name);
$newPermission->description = $permission->description;
$newPermission->data = $permission->data;
$newPermission->ruleName = $permission->ruleName;
$newPermission->createdAt = $permission->createdAt;
$newPermission->updatedAt = $permission->updatedAt;
$newAuth->add($newPermission);
}
// 2-1 - and their children
foreach ($oldAuth->getPermissions() as $permission) {
foreach ($oldAuth->getChildren($permission->name) as $child) {
$newAuth->addChild($newPermission, $child);
}
}
// 3 - migrate all roles & permissions => role, assignations => role
foreach ($oldAuth->getRoles() as $role) {
$newRole = $newAuth->createRole($role->name);
$newRole->description = $role->description;
$newRole->data = $role->data;
$newRole->ruleName = $role->ruleName;
$newRole->createdAt = $role->createdAt;
$newRole->updatedAt = $role->updatedAt;
$newAuth->add($newRole);
foreach ($oldAuth->getPermissionsByRole($role->name) as $permission) {
$newAuth->addChild($newRole, $permission);
}
foreach ($oldAuth->getUserIdsByRole($role->name) as $userId) {
$newAuth->assign($newRole, $userId);
}
}
// 3.1 - and children roles
foreach ($oldAuth->getRoles() as $role) {
foreach ($oldAuth->getChildRoles($role->name) as $child) {
if ($newRole->name !== $child->name) {
$newAuth->addChild($newRole, $child);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment