我在基于Yii2的应用程序(SuperAdmin,Admin,User)中有3个Rbac角色。我如何为这些用户分配个人资料。
我想为SuperAdmin配置文件添加一些字段,为管理员配置文件设置另一个字段,...
答案 0 :(得分:0)
最初通过编写迁移脚本并运行该角色,最好在Yii2 rbac中为用户分配角色。我的脚本看起来像这样
<?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;
}
}
关键线
$authManager->assign($admin, User::findOne(['username' => 'admin'])->id);
一旦您的应用程序增长了一点,您就必须构建一个管理界面,允许您为用户分配角色。 (我现在正在建造这一点!)