Behaviors for specific user

Hi!

I wonder if there is a simple way to add users to rule. I have a new partner and I only want to show some of the information available.

I have the classic predefined 2 users in User.php like:

private static $users = [
        '100' => [
            'id' => '100',
            'username' => 'admin',
            'password' => 'xxx',
            'authKey' => 'test100key',
            'accessToken' => '100-token',
        ],
        '101' => [
            'id' => '101',
            'username' => 'sarah',
            'password' => 'xxx',
            'authKey' => 'test101key',
            'accessToken' => '101-token',
        ],
    ];

And in my SiteController for now I have like this:

public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'except' => ['statistics', 'login', 'logout', 'spam', ...],
                'rules' => [
                    ['allow' => true, 'roles' => ['@']],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

I want the user sarah only view school and contact tables. I only know that I have to modify something in SchoolController and ContactController.

Yii’s example code for User Management is extremely basic. If you require different rights and access for different users you can of course implement anything you want. But most likely you find find everything you need and more in “Usuario” here …

2 Likes

https://forum.yiiframework.com/t/how-to-ask-a-question-that-will-land-you-a-help

In simple form you can try to expand your code like this (not tested):

// [...]
'rules' => [
    [
        'allow' => false, 
        'matchCallback' => function() {
            return Yii::$app->user->username != 'admin';
        }
    ],
    ['allow' => true, 'roles' => ['@']],
],

https://www.yiiframework.com/doc/guide/2.0/en/security-authorization#access-control-filter

ACF performs the authorization check by examining the access rules one by one from top to bottom until it finds a rule that matches the current execution context. The allow value of the matching rule will then be used to judge if the user is authorized or not. If none of the rules matches, it means the user is NOT authorized, and ACF will stop further action execution.

1 Like