I have 3 roles with Rbac in my Yii2 based application (SuperAdmin, Admin, User). How I can allocate profile to these users.
I want to have some fields for SuperAdmin profiles and another fields for Admin profile, ...
Assigning a role to a user in Yii2 rbac is best achieved initially by writing a migration script and running that. My script looks like this
<?php
use yii\db\Schema;
use yii\db\Migration;
use yii\base\InvalidConfigException;
use yii\rbac\DbManager;
use app\models\User;
class m141210_101111_user_authorize extends Migration
{
/**
* @throws yii\base\InvalidConfigException
* @return DbManager
*
* Get the applications Authorization manager and make sure it's a valid
*/
protected function getAuthManager()
{
$authManager = Yii::$app->getAuthManager();
if (!$authManager instanceof DbManager) {
throw new InvalidConfigException('You should configure "authManager" component to use database before executing this migration.');
}
return $authManager;
}
public function up()
{
$authManager = $this->getAuthManager();
$this->db = $authManager->db;
$authManager = Yii::$app->getAuthManager();
if (!$authManager instanceof DbManager) {
throw new InvalidConfigException('You should configure "authManager" component in console.php to use database before executing this migration.');
}
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$admin = $authManager->createRole('admin');
$admin->description = 'Administrator - can do anything';
$authManager->add($admin);
$manager=$authManager->createRole('manager');
$manager->description = 'Manager level access';
$authManager->add($manager);
$user=$authManager->createRole('end-user');
$user->description = 'Normal user';
$authManager->add($user);
// let user admin have admin rights.
if (!User::findOne(['username' => 'admin']))
echo ('No user named "admin" was found to assign admin rights to!');
$authManager->assign($admin, User::findOne(['username' => 'admin'])->id);
}
public function down()
{
echo "m141210_101111_user_authorize cannot be reverted.\n";
return false;
}
}
The critical line being
$authManager->assign($admin, User::findOne(['username' => 'admin'])->id);
Once your application grows a bit you'll have to build an admin interface that allows you to assign roles to users. ( I'm building that bit at the moment! )