2016-11-04 75 views
0

我只想知道如何使用DbManager将角色分配给yii2中的一组用户,因为我看过很多教程,但其中大多数都是面向提升模板和我正在使用基本模板。 他们提到常见的后端文件夹,我在基本模板中找不到 您可以给我一个教程或一些我可以遵循的指导吗?yii2用于用户组的基本模板角色的RBAC

感谢

+0

您可以通过以下链接访问:www.youtube.com/watch?v=eFOIUeU-Y74 – CrashBurn

回答

0

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

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

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

以下是创建角色和权限的文档片段。

<?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文件将进入您的项目的基础中的命令文件夹。您可以通过拨打php yii rbac/init通过终端运行它。

然后,您实际上需要检查用户是否具有某些权限。所以,当某个用户正在执行的操作,你可以调用像

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

其中bassed到罐方法的字符串是,你是想查询的权限。