0
votes

I have a rest full API in Yii2. I have the user model, controller and created a new rest action called login.

How can I set the action login to be executed by the guest users?

class UserController extends \yii\rest\ActiveController{
    public function actions()    {
        $actions = parent::actions();

        $actions['login'] = [
            'class' => 'app\modules\user\actions\user\LoginUserAction',
            'modelClass' => $this->modelClass,
            'checkAccess' => [$this, 'checkAccess'],
        ];

        return $actions;
    }

    public function checkAccess($action, $model = null, $params = array())    {
        return true;
    }
}
1

1 Answers

1
votes

You can set the access control rules on the behaviors function of your controller, instead of on the checkAccess property on the action:

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['access'] = [
                'class' => AccessControl::className(),
                'except' => ['login'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['foo', 'foo2'],
                        'roles' => ['admin'],
                    ]
                ],
    ];

    return $behaviors;
}

In this example, the access control is applied to all actions except 'login'. I left the rules part so you can have an example of how you make customized rules.