D
D
Dmitry2017-01-24 23:42:23
Yii
Dmitry, 2017-01-24 23:42:23

How to implement middleware-like logic in Yii2?

We implement the API for the client, authorization by token, that is, the parameter in GET (or in headers) comes with the token parameter , which is used to identify the user and provide data to platform resources.
There is a common controller from which all the others are inherited ( AuthController , ProductController , OrdersController and others). I would like to describe in this controller the logic for checking the presence of a token (ideally, describe your method, maybe specify this method as a callback somewhere, for example) and, if it exists, launch a request for further execution, otherwise return a JSON object with the necessary me data. These actions must be carried out with each request, that is, as is the case withMiddleware , for example in Laravel .
The beforeAction method in the controller solves the problem halfway - I can return false and then the execution is simply interrupted, but I need to give at least some information to the client, for example, a message in JSON format about the absence of a token and, possibly, some more data.
Implementing a Component object and including it in the bootstrap section of the application's config is similar to beforeAction .
If I return something other than false or an exception, then the response is accepted as true and execution continues.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
DieZz, 2017-01-25
@another_dream

Используйте поведения (behaviors). Например в Yii из коробки есть такая штука:

public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['authenticator'] = [
        'class' => HttpBearerAuth::className(),
    ];
    
    return $behaviors;
}

Если хотите свою логику для проверки токена, то создайте класс который будет имлпементировать интерфейс yii\filters\auth\AuthInterface у указывайте его в поведении. В случае ошибки авторизации бросайте UnauthorizedHttpException

D
Dmitry, 2017-01-25
@another_dream

There was an idea to override the runAction method :

public function runAction($id, $params = [])
    {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        // Если условие истино, то выкидываю ошибку
        if (mt_rand(0,1) === 0) {
            return [
                   'status' => false,
                   'errors' => 'Ошибка'
            ];
        } else {
        // Иначе продолжаем выполнение
            parent::runAction($id, $params);
        }
    }

Works as required, what are the pitfalls? Is this decision rational/reasonable?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question