yii2 RBAC用于用户组的基本模板角色

时间:2016-11-04 03:47:59

标签: yii2

我只想知道如何使用DbManager为yii2中的一组用户分配角色,因为我已经看过很多教程,但大多数教程都是面向高级模板而我正在使用基本模板。 他们提到像普通,后端这样的文件夹,我在基本模板中找不到 你能给我一个我可以遵循的教程或指导吗?

感谢

1 个答案:

答案 0 :(得分:0)

请看这个页面:http://www.yiiframework.com/doc-2.0/guide-security-authorization.html

这将帮助您为RBAC添加DbManager。首先,您需要创建不同的角色,然后您需要为不同的角色添加权限。

然后,当您创建用户时,您需要为该用户分配一个角色,他们将拥有这些权限。

以下是文档中用于创建角色和权限的代码段。

<?php
namespace app\commands;

use Yii;
use yii\console\Controller;

class RbacController extends Controller
{
    public function actionInit()
    {
        $auth = Yii::$app->authManager;

        // add "createPost" permission
        $createPost = $auth->createPermission('createPost');
        $createPost->description = 'Create a post';
        $auth->add($createPost);

        // add "updatePost" permission
        $updatePost = $auth->createPermission('updatePost');
        $updatePost->description = 'Update post';
        $auth->add($updatePost);

        // add "author" role and give this role the "createPost" permission
        $author = $auth->createRole('author');
        $auth->add($author);
        $auth->addChild($author, $createPost);

        // add "admin" role and give this role the "updatePost" permission
        // as well as the permissions of the "author" role
        $admin = $auth->createRole('admin');
        $auth->add($admin);
        $auth->addChild($admin, $updatePost);
        $auth->addChild($admin, $author);

        // Assign roles to users. 1 and 2 are IDs returned by IdentityInterface::getId()
        // usually implemented in your User model.
        $auth->assign($author, 2);
        $auth->assign($admin, 1);
    }
}

此RbacController.php文件将放在项目基础中的commands文件夹中。您可以通过致电php yii rbac/init

在终端上运行它

然后,您实际上需要检查用户是否具有某些权限。因此,当经过身份验证的用户执行操作时,您可以调用类似

的内容
if (\Yii::$app->user->can('createPost')) {
    // create post
}

其中基于can方法的字符串是您要检查的权限。

相关问题