ป้ายกำกับ: ติดตั้ง

YII2 : RBAC สมาชิก กลุ่มและสิทธิYII2 : RBAC สมาชิก กลุ่มและสิทธิ

yii2 มีระบบจัดการสิทธิต่าง ๆ เรียกว่า Role Based Access Control (RBAC) โดยสามารถกำหนดสิทธิได้โดยใช้ กลุ่ม (role) และกำหนดสิทธิให้รายคนได้ เพื่อที่จะควบคุมให้แต่ละคนสามารถเข้าไปใช้เมนูต่าง ๆ ได้ตามความเหมาะสม เราคงไม่ต้องการให้ใครก็ได้ แต่มาเปลี่ยนข้อมูล ตั้งค่าของระบบใหม่ หรือลบงานของคนอื่นออกไปโดยไม่มีเหตุอันควร เริ่มจากการกำหนด role โดย

  1. เพิ่ม component authManager ในไฟล์ common/config/main.php

    PHP

    'components' => [
    ... 'authManager' => [ 'class' => 'yii\rbac\DbManager', ],
    ... ],
    
  2. สร้างตาราง auth ก่อนโดย command

    PHP

    yii migrate –migrationPath=@yii/rbac/migrations/
    

    ตอบ yes รอจนเห็น Migrated up successfully. จะเป็นการสร้างตาราง auth_assignment, auth_item, auth_item_child และ auth_rule
    ถ้าเห็น Exception ‘yii\base\InvalidConfigException’ with message ‘The configuration for the “user” component must contain a “class” element.’ ให้ไป comment config ทีระบุ user components ออกไปก่อน แลัวลองใหม่

  3. สร้างไฟล์ใหม่ /backend/controllers/RbacController.php

    PHP

    <?php
    namespace backend\controllers; use Yii;
    use yii\helpers\Html;
    use yii\web\Controller; /** * Site controller */
    class RbacController extends Controller
    { private $auth = &#x5B;]; public function init () { parent::init () ; $this->auth = Yii::$app->authManager; } public function actionIndex () { return '<h1>RBAC Snippets</h1>' . '<ul>' . '<li>' . html::a ('Create Role', 'createparentsrole', &#x5B;'target' => 't1']) . '</li>' . '<li>' . html::a ('Set Child Role', 'childrole', &#x5B;'target' => 't2']) . '</li>' . '<li>' . html::a ('Assign To User', 'assignrole', &#x5B;'target' => 't3']) . '</li>' . '</ul>'; } public function actionAssignrole () { $administratorsRole = $this->auth->getRole ('administrators') ; if (is_null ($this->auth->getAssignment ('administrators', 1))) { $this->auth->assign ($administratorsRole, 1) ; } $staffsRole = $this->auth->getRole ('staffs') ; if (is_null ($this->auth->getAssignment ('staffs', 1))) { $this->auth->assign ($staffsRole, 1) ; } /* show all roles from table auth_assignment */ return '<h1>Assignments of user id = 1</h1>' . '<pre>' . print_r ($this->auth->getAssignments (1) , true) . '
    

    ลองเรียก link http://localhost/advanced/backend/web/rbac และดูความเปลี่ยนแปลงตามลำดับ

ดูเพิ่มเติม