php 如何为用户添加角色?Yii2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21308423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:02:31  来源:igfitidea点击:

How to add role to user? Yii2

phpyii2

提问by Alexufo

We used Yii2 framework last alpha. Role for user already created but problem is how it assign to user. Documentation is absent.

我们在上一个 alpha 版本中使用了 Yii2 框架。用户的角色已经创建,但问题是如何分配给用户。文档不存在。

采纳答案by Martijn H.

For database version of RBAC use DbManager (quote frm: Alexufo):

对于 RBAC 的数据库版本,请使用 DbManager(引用:Alexufo):

use yii\rbac\DbManager;
$r=new DbManager;
$r->init();
$r->createRole("admin","Administrator");
$r->save();

$r->assign('1','admin');   //1 is user id 

Example Access rules:

示例访问规则:

<?php
namespace backend\controllers;

use yii;
use yii\web\AccessControl;
use yii\web\Controller;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        //'actions' => ['login', 'error'], // Define specific actions
                        'allow' => true, // Has access
                        'roles' => ['@'], // '@' All logged in users / or your access role e.g. 'admin', 'user'
                    ],
                    [
                        'allow' => false, // Do not have access
                        'roles'=>['?'], // Guests '?'
                    ],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render( 'index' );
    }
}
?>

Don't forget to add this to your configuration file (config/main.php):

不要忘记将其添加到您的配置文件 (config/main.php) 中:

'components' => [
    'authManager'=>array(
        'class' => 'yii\rbac\DbManager',
        'defaultRoles' => ['end-user'],
    ),
    ...
]

Tables:

表格:

drop table if exists `tbl_auth_assignment`;
drop table if exists `tbl_auth_item_child`;
drop table if exists `tbl_auth_item`;

create table `tbl_auth_item`
(
   `name`                 varchar(64) not null,
   `type`                 integer not null,
   `description`          text,
   `biz_rule`              text,
   `data`                 text,
   primary key (`name`),
   key `type` (`type`)
) engine InnoDB;

create table `tbl_auth_item_child`
(
   `parent`               varchar(64) not null,
   `child`                varchar(64) not null,
   primary key (`parent`,`child`),
   foreign key (`parent`) references `tbl_auth_item` (`name`) on delete cascade on update cascade,
   foreign key (`child`) references `tbl_auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

create table `tbl_auth_assignment`
(
   `item_name`            varchar(64) not null,
   `user_id`              varchar(64) not null,
   `biz_rule`              text,
   `data`                 text,
   primary key (`item_name`,`user_id`),
   foreign key (`item_name`) references `tbl_auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;

You can also find this information in the "yii/rbac" directory (including other SQL files). For functionality and more details:

您也可以在“yii/rbac”目录(包括其他 SQL 文件)中找到此信息。有关功能和更多详细信息:

https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md

https://github.com/yiisoft/yii2/blob/master/docs/guide/security-authorization.md

回答by Oleg Ozimok

$user_id = 1;

$auth = new DbManager;
$auth->init();
$role = $auth->createRole('editor');
$auth->add($role);

$auth->assign($role, $user_id);

========================================================================= if you want to select role instead creating then

================================================== ======================== 如果你想选择角色而不是创建然后

$auth = new DbManager;
$auth->init();
$role = $auth->getRole('admin');
$auth->assign($role, $user_id);

100% worked!

100%工作!

回答by Alexufo

Solved!

解决了!

================ create role ============

================ 创建角色 ============

use yii\rbac\PhpManager;
$r=new PhpManager;
$r->init();
$r->createRole("admin","Администратор"); 
$r->save();

=============== assign ==================

============== 赋值 ==================

$r->assign('1','admin');   //1 is user id

回答by Ivo Renkema

A really simple way to achieve an admin role is to add this to your controller:

实现管理员角色的一种非常简单的方法是将其添加到您的控制器中:

use yii;
/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'rules' => [
                [
                    'allow' => true,
                    'actions' => ['index'],
                    'roles' => ['@'],
                ],
                [
                    'allow' => !Yii::$app->user->isGuest && Yii::$app->user->identity->isAdmin(),
                    'actions' => ['view', 'create', 'update', 'delete'],
                ],
            ],
        ],
    ];
}

Then add to your Usermodel an isAdmin()which returns truefor your admin user(s) and falsefor everyone else. Personally, I use:

然后添加到您的User模型中,isAdmin()它会true为您的管理员用户和false其他所有人返回。就个人而言,我使用:

public function isAdmin() {
    return Self::ROLE_ADMIN === $this->role;
}

Admittedly, this is not "by the book". But it is simple, quick and effective.

诚然,这不是“书上说的”。但它简单、快速且有效。

回答by Kalpesh Desai

$user_id = \Yii::$app->user->id;

$auth = new DbManager;
$auth->init();
$role = $auth->createRole('editor');
$auth->add($role);

$auth->assign($role, $user_id);