Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RBAC in Yii2 with PhpManager

Tags:

yii2

rbac

How can I implement RBAC in Yii 2.0 without any database. I will have just 2 roles , i.e. admin and author . my RbacController is

<?php
namespace app\commands;

use Yii;
use yii\console\Controller;

class RbacController extends Controller
{
    public function actionInit()
    {
        $auth =  \Yii::$app->authManager;

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

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

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

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

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

I am getting an error

  `PHP Fatal error: Call to a member function createPermission() 
on a non-object in var/www/commands/RbacController.php on line 14
    PHP Fatal Error 'yii\base\ErrorException' with message 'Call to a member
 function createPermission() on a non-object' in /var/www/commands/RbacController.php:14 

while executing yii rbac/init . I am using basic template with PhpManager . I have added 'authManager' => [ 'class' => 'yii\rbac\PhpManager', ], in web.php .I am using basic template.

like image 824
user7282 Avatar asked Dec 11 '22 02:12

user7282


1 Answers

i Know this is a bit old, but I want to publish the solution.. at least what worked for me.

I have added 'authManager' => [ 'class' => 'yii\rbac\PhpManager', ], in web.php

There is the mistake, since you a re running the command via console, you need to add that same line in the components section of console.php (in the same directory as web.php).

I hope this helps others who have a similar problem :D

like image 91
David Cadavid Avatar answered Feb 03 '23 09:02

David Cadavid