Ads 4 You

Yii2 RBAC GROUPS Assignment for user based on groups

Email Id : phpmk888@gmail.com

Yii2 Role Base Access controll With Groups



Implementing a role based access (RBAC) control is a very easy process and you can even load your roles from the database if you want. Step1: Creating necessary tables in the database [ You can also apply migrations with console command yii migrate instead of step 1 ] The first step is to create necessary tables in the database.Below is the sql you need to run in the database.

 


-- --------------------------------------------------------

--
-- Table structure for table `auth_assignment`
--

CREATE TABLE `auth_assignment` (
  `item_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `user_id` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `auth_item`
--

CREATE TABLE `auth_item` (
  `name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `type` smallint(6) NOT NULL,
  `description` text COLLATE utf8_unicode_ci,
  `rule_name` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL,
  `data` blob,
  `created_at` int(11) DEFAULT NULL,
  `updated_at` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `auth_item_child`
--

CREATE TABLE `auth_item_child` (
  `parent` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `child` varchar(64) COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `auth_rule`
--

CREATE TABLE `auth_rule` (
  `name` varchar(64) COLLATE utf8_unicode_ci NOT NULL,
  `data` blob,
  `created_at` int(11) DEFAULT NULL,
  `updated_at` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

-- --------------------------------------------------------

--
-- Table structure for table `role_master`
--

CREATE TABLE `role_master` (
  `id` int(11) NOT NULL,
  `company_id` int(11) NOT NULL,
  `role_name` varchar(50) NOT NULL,
  `created_by` int(11) NOT NULL,
  `created_at` int(11) NOT NULL,
  `is_super_company` tinyint(4) NOT NULL DEFAULT '0' COMMENT '0:No,1:Yes'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `auth_assignment`
--
ALTER TABLE `auth_assignment`
  ADD PRIMARY KEY (`item_name`,`user_id`);

--
-- Indexes for table `auth_item`
--
ALTER TABLE `auth_item`
  ADD PRIMARY KEY (`name`),
  ADD KEY `rule_name` (`rule_name`),
  ADD KEY `idx-auth_item-type` (`type`);

--
-- Indexes for table `auth_item_child`
--
ALTER TABLE `auth_item_child`
  ADD PRIMARY KEY (`parent`,`child`),
  ADD KEY `child` (`child`);

--
-- Indexes for table `auth_rule`
--
ALTER TABLE `auth_rule`
  ADD PRIMARY KEY (`name`);

--
-- Indexes for table `role_master`
--
ALTER TABLE `role_master`
  ADD PRIMARY KEY (`id`),
  ADD KEY `company_id` (`company_id`),
  ADD KEY `created_by` (`created_by`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `role_master`
--
ALTER TABLE `role_master`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- Constraints for dumped tables
--

--
-- Constraints for table `auth_assignment`
--
ALTER TABLE `auth_assignment`
  ADD CONSTRAINT `auth_assignment_ibfk_1` FOREIGN KEY (`item_name`) REFERENCES `auth_item` (`name`) ON DELETE CASCADE ON UPDATE CASCADE;

--
-- Constraints for table `auth_item`
--
ALTER TABLE `auth_item`
  ADD CONSTRAINT `auth_item_ibfk_1` FOREIGN KEY (`rule_name`) REFERENCES `auth_rule` (`name`) ON DELETE SET NULL ON UPDATE CASCADE;

--
-- Constraints for table `auth_item_child`
--
ALTER TABLE `auth_item_child`
  ADD CONSTRAINT `auth_item_child_ibfk_1` FOREIGN KEY (`parent`) REFERENCES `auth_item` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `auth_item_child_ibfk_2` FOREIGN KEY (`child`) REFERENCES `auth_item` (`name`) ON DELETE CASCADE ON UPDATE CASCADE;




Step2: Setting up the config file Now you can set up the config file to use the authmanager as DbManager. This is done by adding the following lines to the components section of your config file

 


'components' => [
        'authManager' => [
            'class' => 'yii\rbac\DbManager',
            'defaultRoles' => ['guest'],
        ],
    ],




Step3: Creating Components for groups and Rules access permistion.

Create below components 1. CommonFunction.php



 

user->identity)) {
            //IF IS SUPER COMPANY AND IS ADMIN THEN RETURN ALL ACCESS
            if (Yii::$app->user->identity->is_admin && Yii::$app->user->identity->userCompany->is_super_company == 1) {
                $access = 1;
            } else {
                //IF IS NOT SUPER COMPANY THEN CHECK SPECIFIC PERMISSION VIES ACCESS
                if (Yii::$app->user->canRole("$permission")) {
                    $access = 1;
                }
            }
        }
        return $access;
    }

}

?>





2.User.php for override getAcess RBAC Function. ** UPDATED ** So, I have a solution, that uses custom checkAccess functions to check for proper permissions on the group or global areas.



 


_access[$permissionName])) {
            return $this->_access[$permissionName];
        }
        if (($accessChecker = $this->getAccessChecker()) === null) {
            return false;
        }
        $identity = $this->getIdentity();
        $access = $accessChecker->checkAccess($identity->role_id, $permissionName, $params);
        if ($allowCaching && empty($params)) {
            $this->_access[$permissionName] = $access;
        }

        return $access;
    }

}

?>



Step4: Adding and assigning roles in Controller behaviors function.



 


 [
                'class' => AccessControl::className(),
                'only' => ['index', 'create', 'delete', 'update', 'view'],
                'rules' => [
                    [
                        'actions' => ['index', 'create', 'delete', 'update', 'view'],
                        'allow' => true,
                        'roles' => [(CommonFunction::RolesAndPermissions()) ? '@' : '*'],
                    ],
                    [
                        'actions' => ['index', 'create', 'delete', 'update', 'view'],
                        'allow' => true,
                        'roles' => [(CommonFunction::RolesAndPermissions('user')) ? '@' : '*'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST', 'GET'],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'state-list' => ['POST', 'GET'],
                ],
            ],
        ];
    }
}
?>



Step5: Adding and Checking Access in Navigatin Menu.

 

user->identity->userCompany->is_super_company == 1) { 
    Yii::$app->urlManager->createAbsoluteUrl(['company/company']) 
 } 
*/
 ?>
urlManager->createAbsoluteUrl(['admin/city']) 
 } 
*/
 ?>





Yii2 rbac roles group, Yii2 RBAC group assignment tutorial 2018. Yii2 RBAC Multiple Assignments for Each User Based on Groups

My DB is set up like

1. Users (role_id, ect)
2. auth_assignment (user_id) here user_id is consider role_id
3. auth_item (name,type) is module name and type=2

For this example I have added a group field into the user table and have defined two groups, user (2) and admin (1).

Comments

Post a Comment