thomas
thomas

Reputation: 2318

Yii2: set action in controller

My app has several actions but when a user has a certain role, I only want to allow one. I can't find a way to set the action in the controller. I want something like this:

public function beforeAction($action) 
{
    if($action->id != 'range') 
    {
       # run another action with custom params
    }
    else return 1;
}

A redirect would lead to a million CORS issues so I'd like to avoid it. How can I accomplish this?
Thanks!

Upvotes: 1

Views: 793

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133400

In controller you can use Access Control Filter (ACF)

assuming that you want in you site controller allow only role admin the access to actionViewforadmin

use yii\web\Controller;
use yii\filters\AccessControl;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['login', 'logout', 'signup', 'viewforadmin'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['login', 'signup'],
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['logout'],
                        'roles' => ['@'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['viewforadmin'],
                        'roles' => ['admin'],
                    ],                   
                ],
            ],
        ];
    }
    // ...
}

you can take a look at this brief guide

http://www.yiiframework.com/doc-2.0/guide-security-authorization.html or this reference http://www.yiiframework.com/doc-2.0/yii-base-actionfilter.html

Upvotes: 0

Bizley
Bizley

Reputation: 18021

One of the ways to do it is to override createAction() method in the controller.

public function createAction($id)
{
    if (/* condition for one action limit */) {
        $id = 'allowedAction';
    }
    return parent::createAction($id);
}

If condition is met any called action within this controller is returned as the result of actionAllowedAction() method.

Upvotes: 2

Related Questions