问题描述
我想创建一个应用程序,只有管理员可以执行所有 crud 操作,而其他用户只能创建和更新帖子.我确实找到了基于 rbac 的教程,但仅适用于高级模板,但我使用的是基本模板.我也遵循了 yii2 指南,但我并没有像执行 ./yii rbac/init 控制台命令那样很好地理解它.我该怎么做?
i want to create an application where only admin can perform all the crud operations but other users can only create and update posts. I did find tutorials based on rbac but only for advanced template but i am using the basic template. I also followed the yii2 guide but i did not understood it very well like executing ./yii rbac/init console command. How do i do it?
推荐答案
首先在您的模型文件夹中创建一个名为 PermissionHelpers 的 Helper 类:
first of all create a Helper Class called PermissionHelpers in your model folder:
namespace app\models;
use Yii;
class PermissionHelpers {
public static function requireAdmin() {
if(Yii::$app->user->identity->role == 100)
{
return true;
}
else return false;
}
}
然后更新您的控制器:
// at top with your other use
use yii\filters\AccessControl;
use app\models\PermissionHelpers;
// first function inside the class
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['privateaction1', 'privateaction2'],
'rules' => [
[
'actions' => ['privateaction1', 'privateaction2'],
'allow' => true,
'roles' => ['@'],
'matchCallback' => function($rule, $action) {
return PermissionHelpers::requireAdmin();
}
],
],
],
}
现在你需要在数据库中更新你自己的角色 = 100,你就准备好了.
And now you need to update yourself in the DB with role = 100, and you're set.
我自己使用的是高级模板,因此命名空间等可能会有一些小的变化.但应该很容易弄清楚.祝你好运!
I'm using Advanced template myself, so there might be small changes to the namespaces and such. But it should be fairly easy to figure out. Good luck!
这篇关于用于基本 yii2 模板的 RBAC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!