Yii2 RBAC dengan menggunakan DBManager sudah disediakan oleh team Yii. Kita hanya perlu menggunakan console untuk menggunakan nya, sebelumnya anda bisa lihat terlebih dahulu di situs resmi Yii Access.

Untuk memulainya anda hanya perlu menambahkan component di file config anda , seperti code berikut ini menggunakan DbManager :

return [
    // ...
    'components' => [
        'authManager' => [
            'class' => 'yii\rbac\DbManager',
        ],
        // ...
    ],
];

Kemudian buka console anda ,untuk OS windows anda bisa ketik "cmd" kemudian masuk ke direktory project anda, misalkan " cd xampp\htdocs\myproject" kemudian ketik :

"yii migrate --migrationPath=@yii/rbac/migrations" di linux karena menggunakan bash maka menjadi "./yii migrate --migrationPath=@yii/rbac/migrations"

Setelah selesai maka akan menambah 4 table di database anda yaitu : auth_assignment,auth_item,auth_item_child dan auth_rule. mudah kan hehehe, blom selesai.

Sekarang kita akan coba pikirkan CRUD (crud, update dan delete) dan katakanlah kita punya role sbb:

  • Admin : bisa semuanya
  • Editor : bisa update plus Author
  • Author : bisa create plus Viewer
  • Viewer : hanya bisa view

Oke dengan ilustrasi diatas maka kita akan buat RbacController di folder "console", sbb:

 

<?php
namespace console\controllers;

use yii\console\Controller;
use Yii;


class RbacController extends Controller {

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

        // add "view" permission
        $view = $auth->createPermission('view');
        $view->description = 'View';
        $auth->add($view);

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

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

        // add "delete" permission
        $delete = $auth->createPermission('delete');
        $delete->description = 'Delete';
        $auth->add($delete);

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

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

        // 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, $delete);
        $auth->addChild($admin, $author);
        $auth->addChild($admin, $editor);
        $auth->addChild($admin, $viewer);

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

}

Masih di console anda,kita inisialisai sesuai dengan function init() dengan code sbb: "yii rbac/init", setelah init maka kita akan lihat userId dengan id =1 akan menjadi admin.

 

Oke sekarang kita akan tambahkan di class User role, kita buat property static dengan nama $roles :

anda bisa assign beberapa user di form user, contoh nya adalah update

class User extends ActiveRecord implements IdentityInterface {

public static $roles = [20 => 'admin', 30 => 'editor', 40 => 'viewer', '50' => 'author'];

 

di view form user, anda bisa tambahkan roleId sesuai dengan code diatas, contoh :

<?= $form->field($model, 'role')->dropDownList(common\models\User::$roles) ?>

 

Controller actionCreate / update :

 if ($model->load(Yii::$app->request->post()) && $model->save()) {
            // the following three lines were added:
            $auth = Yii::$app->authManager;
            $authorRole = $auth->getRole(User::$roles[$model->role]);
            $auth->assign($authorRole, $model->id);

            Yii::$app->session->setFlash('success', 'Well done! successfully to update data!  ');

untuk controller secara umum di behaviour:

public function behaviors()
    {
        return [
        'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index','view'],
                        'roles' => ['viewer']
                    ],
                    [
                        'allow' => true,
                        'actions' => ['create'],
                        'roles' => ['author']
                    ],
                    [
                        'allow' => true,
                        'actions' => ['update'],
                        'roles' => ['editor']
                    ],
                    [
                        'allow' => true,
                        'actions' => ['delete'],
                        'roles' => ['admin']
                    ],
                    [
                        'allow' => true,
                        'roles' => ['admin']
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

Selamat mencoba :)

 

Leave a Comment:


admin 5 years ago

pake ini : namespace backend\components; class Controller extends \yii\web\Controller { public function beforeAction($event) { .............. return parent::beforeAction($event); } } before action, bisa taruh database disitu :)

davidsuwandi 5 years ago

klo rolenya dinamis, trus permission add,delete,edit,view nya masing2 permodule/menu gmn? ada solusi?


digital_ocean