Yii2는 RBAC를 사용합니다.

WBOY
풀어 주다: 2016-08-08 09:24:22
원래의
996명이 탐색했습니다.

1. /basic/config/console.php 및 /basic/config/web.php에서 구성 요소를 구성합니다. console.php의 코드만 여기에 게시됩니다.

<?php

Yii::setAlias(&#39;@tests&#39;, dirname(__DIR__) . &#39;/tests&#39;);

$params = require(__DIR__ . &#39;/params.php&#39;);
$db = require(__DIR__ . &#39;/db.php&#39;);

return [
    &#39;id&#39; => 'basic-console',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log', 'gii'],
    'controllerNamespace' => 'app\commands',
    'modules' => [
        'gii' => 'yii\gii\Module',
    ],
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
        'log' => [
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'db' => $db,'authManager' => [
    				'class' => 'yii\rbac\DbManager',
    				'itemTable' => 'web_auth_item',
    				'assignmentTable' => 'web_auth_assignment',
    				'itemChildTable' => 'web_auth_item_child',
        			'ruleTable'=>'web_auth_rule'
    		],
    ],
    'params' => $params,
];
로그인 후 복사
콘솔이 있는 경우 .php에 구성이 없으면 다음 오류가 보고됩니다.

You should configure "authManager" component to use database before executing this migration.
로그인 후 복사

2. 명령줄을 엽니다.

3.cd 명령을 전환합니다. /php/basic 디렉토리

4. 다음 명령을 입력합니다: yii migration --migrationPath=@yii/rbac/migrations/

5. 권한 생성:

    public function createPermission($item)
    {
        $auth = Yii::$app->authManager;

        $createPost = $auth->createPermission($item);
        $createPost->description = '创建了 ' . $item . ' 许可';
        $auth->add($createPost);
    }
로그인 후 복사

6. 역할 생성:

public function createRole($item)
    {
        $auth = Yii::$app->authManager;

        $role = $auth->createRole($item);
        $role->description = '创建了 ' . $item . ' 角色';
        $auth->add($role);
    }
로그인 후 복사

7.역할 할당 권한

 static public function createEmpowerment($items)
    {
        $auth = Yii::$app->authManager;

        $parent = $auth->createRole($items['name']);
        $child = $auth->createPermission($items['description']);

        $auth->addChild($parent, $child);
    }
로그인 후 복사

8. 역할 할당 사용자:

 static public function assign($item)
    {
        $auth = Yii::$app->authManager;
        $reader = $auth->createRole($item['name']);
        $auth->assign($reader, $item['description']);
    }
로그인 후 복사

9. 권한 확인:

 public function beforeAction($action)
    {
        $action = Yii::$app->controller->action->id;
        if(\Yii::$app->user->can($action)){
            return true;
        }else{
            throw new \yii\web\UnauthorizedHttpException('对不起,您现在还没获此操作的权限');
        }
    }
로그인 후 복사

10. 컨트롤러에서 권한 확인

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\web\AccessControl::className(),
                'only' => ['login', 'logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['login', 'signup'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    // ...
로그인 후 복사

컨트롤러에서 확인 사용자 지정

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\web\AccessControl::className(),
                'only' => ['special-callback'],
                'rules' => [
                    [
                        'actions' => ['special-callback'],
                        'allow' => true,
                        'matchCallback' => function ($rule, $action) {
                            return date('d-m') === '31-10';
                        }
                    ],
로그인 후 복사

   // ...
    // Match callback called! 此页面可以访问只有每个10月31日
    public function actionSpecialCallback()
    {
        return $this->render('happy-halloween');
    }
로그인 후 복사

위 내용은 콘텐츠의 측면을 포함하여 Yii2에서 RBAC의 사용을 소개합니다. PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!