CakePHP Auth Redirect to Previous Page

CakePHP has a lot of built in awesome-ness. But what do you do when you need to be awesomer?

CakePHP has a lot of built in awesome-ness. But what do you do when you need to be awesomer?

Here's one instance when awesome just isn't going to cut it.

CakePHP has the Auth component all set up so that in your app_controller.php you can specify the URL for

$this->Auth->loginRedirect 

I thought that when a user logged in, if there was a referer, they would be redirected to it. If not, they would be redirected to whichever URL you specified in the loginRedirect.

What has stumped me for a long time is that the login doesn't work as I expected it to. It seemed almost randomly that I would be redirected to the page I came from.

This evening I looked into it a bit more and it all became clear. The referring page is only set automatically if the user tries to access a page that you have specified in your controller as requiring authentication - logical assumption, however that's not the only time it needs to be set.

For my application, I have a comments form which I only want to be available if the user is logged in - so the page itself is public but the form is not. When you click on the "Leave a Comment" link, the login form appears and the desired action is that you would log in, then be redirected to the article.

So a big thanks for the functionality CakePHP has out of the box, but this is what I had to do to make it work the way I want...

The referer (when set) is actually written to the Auth.redirect session. So in your controller method, you need to manually write the url to that session.

$this->Session->write('Auth.redirect', $this->here);

Now when a user visits the page they see it as they should, but when they need to log in to comment, it takes them back to that page.

Awesomer.