Redirect user to previous page after auth (yii2)

2019-06-21 03:56发布

I have the main controller from which the others are inherited. Code is something like this

public function init()
{
    $this->on('beforeAction', function ($event) {
        ...

        if (Yii::$app->getUser()->isGuest) {
            $request = Yii::$app->getRequest();
            // dont remember login page or ajax-request
            if (!($request->getIsAjax() || strpos($request->getUrl(), 'login') !== false))                  {
               Yii::$app->getUser()->setReturnUrl($request->getUrl());
              }
           }
        }
        ...
    });
}

It works perfectly for all pages, except the page with captcha. All the pages with captcha are redirected to something like this - /captcha/?v=xxxxxxxxxxxxxx

If the object is logged Yii::$app->getRequest() then I see that for pages with captcha it is used twice. For the first time the object is corect, and the second time I see the object with captcha. How can I solve this problem with yii? Is there a chance not to track the request for captcha?

标签: yii2
2条回答
虎瘦雄心在
2楼-- · 2019-06-21 04:31

The default (generated) controller uses something like this:

public function actions()
{
    return [
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
        ],
    ];
}

Does your controller contain something like this?

This means that there is an action "captcha" that is used for displaying captchas (it returns the image). When you have a page displaying a captcha the image is called after the page you want to return to. Therefore that latest page visited is the one with the captcha.

I think you have to filter out this action.

Another possibility could be to use the default $controller->goBack() method. I think this handles registering of the returnUrl by default.

Reference: Class yii\web\Controller

查看更多
老娘就宠你
3楼-- · 2019-06-21 04:52

Guid security authorization

Use Access Control Filter(ACF) in your controller.

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

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['login', 'logout', 'signup'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['login', 'signup'],
                        'roles' => ['?'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['logout'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    // ...
}
查看更多
登录 后发表回答