Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii returnUrl function

Hello guys I have this code in main.php config file:

'components' => array(
    '[.........]',
    'user'=>array(
        // enable cookie-based authentication
        'allowAutoLogin'=>true,
        'autoRenewCookie' => true,
        'returnUrl' => 'http://stackoverflow.com',
    )
);

My problem is that id doesn't redirects user to http://stackoverflow.com after login, can you please help me?

UserController.php :

public function actionLogin()
{
    if (!Yii::app()->user->isGuest){
        $this->redirect('/user/index');
        return;
    }

    $model=new LoginForm;

    // if it is ajax validation request
    if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
    {
        echo CActiveForm::validate($model);
        Yii::app()->end();
    }

    // collect user input data
    if(isset($_POST['LoginForm']))
    {
        $model->attributes=$_POST['LoginForm'];
        // validate user input and redirect to the previous page if valid
        if($model->validate() && $model->login())
            $this->redirect(Yii::app()->user->returnUrl);
    }
    // display the login form
    $this->render('login',array('model'=>$model));
}
like image 394
Irakli Avatar asked Mar 10 '12 14:03

Irakli


2 Answers

I have found a solution for my problem. I added this lines of code in login.php so after user login it will redirect on previous page:

if (Yii::app()->request->urlReferrer != 'http://www.example.com/user/login' && 
    Yii::app()->request->urlReferrer != 'http://www.example.com/user/register')
{
    Yii::app()->user->setReturnUrl(Yii::app()->request->urlReferrer);
}
like image 130
Irakli Avatar answered Oct 14 '22 23:10

Irakli


Try this in order to keep track of the last visited valid url:

Add to you configuration:

'preload' => array(
    // preloading 'loginReturnUrlTracker' component to track the current return url that users should be redirected to after login
    'loginReturnUrlTracker'
),
'components' => array(
    'loginReturnUrlTracker' => array(
        'class' => 'application.components.LoginReturnUrlTracker',
    ),
    ...
),

Put this file in components/LoginReturnUrlTracker.php:

<?php

class LoginReturnUrlTracker extends CApplicationComponent
{

    public function init()
    {
        parent::init();

        $action = Yii::app()->getUrlManager()->parseUrl(Yii::app()->getRequest());

        // Certain actions should not be returned to after login
        if ($action == "site/error") {
            return true;
        }
        if ($action == "site/logout") {
            return true;
        }
        if ($action == "site/login") {
            return true;
        }

        // Keep track of the most recently visited valid url
        Yii::app()->user->returnUrl = Yii::app()->request->url;

    }

}
like image 30
Motin Avatar answered Oct 14 '22 23:10

Motin