gpt4 book ai didi

php - 如何给用户添加角色?

转载 作者:IT王子 更新时间:2023-10-29 00:12:14 26 4
gpt4 key购买 nike

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

最佳答案

对于 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

示例访问规则:

<?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' );
}
}
?>

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

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

表格:

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;

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

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

关于php - 如何给用户添加角色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21308423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com