开发者

CakePHP Login Redirect

I have the following code in my login method:

    if(!(empty($this->data)) && $this->Auth->user())
    {

        if($this->referer(array('controller' => 'users', 'action' => 'login')))
        {
            $this->redirect(array('controller' => 'home', 'action' => 'index'));
        }
        else
        {
            $this->redirect($this->Auth->redirect($this->referer()));
        }
    }
}

This basically redirects the user to their previous page when they successfully login using a login form in the site header BUT if they login directly from the login page it will send them to the home pa开发者_开发知识库ge as they previous page would be the login form.

The problem however is that if a user visits a page that requires authentication then they will be redirected to the login page and then login but because they have now visited the login page they will be redirected to the home page and NOT their previous page that they were trying to access.

How do I fix this problem?

Thanks


If I remember correctly (not confirmed on 1.3), you can set the default redirect to home and check whether the redirect path is set by the Auth component.

Something like this in your login action

$auth_redirect = $this->Session->read("Auth.redirect");
if(isset($auth_redirect) && $auth_redirect != "") {
    $this->redirect($auth_redirect);
} else { 
    $this->redirect('/home/index')
}

And something like this in your app_controler

$this->Auth->loginRedirect = array('controller' => 'home', 'action' => 'index');


There are two or three options, one which is much better in my opinion

Option 1 - embed in form (preferred)

  1. When they are redirected to the login page, embed the previous page URL into the login URL as a GET parameter
  2. Take that get parameter and add it as a hidden input value in the login form
  3. In your login code above, check for presence of this value and redirect to it if it exists.

Option 2 - remember in session

  1. Before they are redirected to the login page, store the previous page URL in the session
  2. After login, check for the presence of a previous page value, redirect if it exists, and delete it from session.

Option 3 - display login page at URL instead of redirecting to login page.

  1. Instead of displaying the unauthorized page or redirecting, keep them at the desired URL, but display the login form.
  2. Then your code above will work as desired.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜