PHP code example of claudejanz / yii2-context-access-filter
1. Go to this page and download the library: Download claudejanz/yii2-context-access-filter library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
claudejanz / yii2-context-access-filter example snippets
class RbacController extends Controller {
public function actionIndex() {
$auth = Yii::$app->authManager;
$auth->removeAll();
// 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 the rule
$rule = new \claudejanz\contextAccessFilter\rules\OwnRule();
$auth->add($rule);
// add "update" permission
$update = $auth->createPermission('update');
$update->description = 'update';
$auth->add($update);
// add the "updateOwn" permission and associate the rule with it.
$updateOwn = $auth->createPermission('updateOwn');
$updateOwn->description = 'update own';
$updateOwn->ruleName = $rule->name;
$auth->add($updateOwn);
// make "updateOwn" child from "update"
$auth->addChild($update,$updateOwn);
// add "delete" permission
$delete = $auth->createPermission('delete');
$delete->description = 'delete';
$auth->add($delete);
// add the "deleteOwn" permission and associate the rule with it.
$deleteOwn = $auth->createPermission('deleteOwn');
$deleteOwn->description = 'delete own';
$deleteOwn->ruleName = $rule->name;
$auth->add($deleteOwn);
// make "deleteOwn" child from "delete"
$auth->addChild($delete,$deleteOwn);
// add "reader" role and give this role the "view" permission
$reader = $auth->createRole('reader');
$auth->add($reader);
$auth->addChild($reader, $view);
// add "moderator" role and give this role the "create" permission
// as well as the permissions of the "updateOwn" and "deleteOwn" role
// and the permissions of the "reader" role
$moderator = $auth->createRole('moderator');
$auth->add($moderator);
$auth->addChild($moderator, $create);
$auth->addChild($moderator, $updateOwn);
$auth->addChild($moderator, $deleteOwn);
$auth->addChild($moderator, $reader);
// add "admin" role and give this role the "update" and "delete" permission
// as well as the permissions of the "moderator" role
$admin = $auth->createRole('admin');
$auth->add($admin);
$auth->addChild($admin, $update);
$auth->addChild($admin, $delete);
$auth->addChild($admin, $moderator);
// Assign roles to users. 1, 2 and 3 are IDs returned by IdentityInterface::getId()
// usually implemented in your User model.
$auth->assign($admin, 1);
$auth->assign($moderator, 2);
$auth->assign($normal, 3);
}
}