PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 27, 2022

[FIXED] set default page for Forbidden (#403) when cant access in YII2

 February 27, 2022     yii, yii2, yii2-advanced-app, yii2-basic-app     No comments   

Issue

this is my behavior function in ShippingController :

 public function behaviors()
        {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::className(),
                'rules' => [
                    // deny all POST requests
//                        [
//                        'actions' => ['index', 'create'],
//                        'allow' => TRUE,
//                    ],
                        [
                        'actions' => ['index', 'create', 'init'],
                        'allow' => true,
                        'roles' => ['user2','user3'],
                        'denyCallback' => function()
                            {

                     redirect to address/index if user 2 cant access redirect to address/create if user3 cant access
                            //redirect here
                            }
                    ],
                // everything else is denied
                ],
            ],
        ];

        }

how to handle this problem !? i want redirect page to address/index if role :user2 cant access and redirect to address/create if role : user3 cant access


Solution

I assume you are using the RBAC system in yii. Check what config files for:

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

or 'yii\rbac\PhpManager'.

Here is what worked for me:

'actions' => ['index', 'create', 'init'],
'allow' => false,
'roles' => ['user2','user3'],
'denyCallback' => function()
     {
        $user = Yii::$app->user;
        if ($user->can('user2')) {
           return Yii::$app->getResponse()->redirect(['/address/index']);
        } else {
           return Yii::$app->getResponse()->redirect(['/address/create']);
        }
     }

The 'allow' option of the rule should be set to false in order for denyCallback to be called. You can see that at "yiisoft/yii2/filters/AccessControl.php" line 120.



Answered By - Jannes Botis
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing