Dedikisme's Blog

Ngeblog biar dibilang eksis

Rbac Yii2 authManager

Lanjutan dari artikel Rbac Yii2 Framework => http://blog.dedikisme.com/blog/2014/05/09/rpbac-yii2-framework/

jika ingin lebih flexible dan ringkas, kode

apaajaController.php
1
2
3
4
5
$phpm = new PhpManager;
// buat "readPost" permission
$readPost =  $phpm->createPermission('readPost');
$readPost->description = 'read a post';
$phpm->add($createPost);

bisa diganti dengan

apaajaController.php
1
2
3
4
$phpm = Yii::$app->authManager;
$readPost =  $phpm->createPermission('readPost');
$readPost->description = 'read a post';
$phpm->add($createPost);

dan untuk mengecek akses user tinggal mengganti

apaajaController.php
1
$phpm->checkAccess('2', 'writePost')  // angka 2 adalah ID user

dengan

apaajaController.php
1
Yii::$app->user->can('writePost');

tapi dengan menambah config component ‘authManager’ pada config/main.php pada baris berikut

main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 'components' => [
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
         'authManager' => [
            'class' => 'yii\rbac\PhpManager',
        ],
    ],

sehingga jika ingin mengganti ke Rbac yang pake database tinggal ganti class nya jadi

main.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 'components' => [
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
         'authManager' => [
            'class' => 'yii\rbac\DbManager',
        ],
    ],

Thanks

Comments