2

I implemented security according to this tutorial:

http://book.cakephp.org/view/1543/Simple-Acl-controlled-Application

What I want it to do is if a user issues a request and isn't logged in, they are presented with the login page and then redirected back to their original request.

I think I need to add code in app_controller.php (the top level controller) to save the initial request as maybe a session variable, and then add a line at the end of this function in the users controller to redirect to the saved value:

function login() {
        if ($this->Session->read('Auth.User')) {
            $this->Session->setFlash('You are logged in!');
            // redirect to referrer here
        }
    }   

Am I on the right track here?

Teej
  • 12,764
  • 9
  • 72
  • 93
opike
  • 7,053
  • 14
  • 68
  • 95
  • 1
    I can't copy-paste you now the solution, but what you say is what you have to do: save in the beforeFilter the referer page, and redirect to the referer after login. You must watch for avoiding infinite redirects. – sibidiba Jan 31 '11 at 09:15

3 Answers3

1

you could do a quick search... Take user back to previous page after logging in?

Community
  • 1
  • 1
dogmatic69
  • 7,574
  • 4
  • 31
  • 49
0

I presume you've spent enough time with CakePHP to do steps below. Here is the solution;

  1. Add the Auth and Session components to AppController's components (if you haven't done). From now on all of your controllers able to use of Auth and Session functions.

  2. Override the beforeFilter() function of the UsersController (or similar controller to manage user actions) with that one-line-of-code;

    $this->Auth->loginRedirect = $this->Session->read("Auth.loginRedirect");

    This code should be placed into function since PHP doesn't support function calls into variable assingment.

  3. After that, to prevent mistaken redirection to already redirected pages, also add that line to the UsersController's beforeFilter() function;

    $this->Session->write('Auth.loginRedirect', "/");

    The above code is not required if you sure that done step 4 for every controller.

  4. Override the beforeFilter() function of the controller that you wanted to get back there after login with that one-line-of-code;

    $this->Session->write('Auth.loginRedirect', Router::url(null, true));.

    What this code does is simply writing the fullbase of controller/action[/param1...] URL (be careful with the parameters btw) to the Session with Auth.loginRedirect name.

PS: Read jocull's comment to find out why I didn't use the $this->here.

Community
  • 1
  • 1
ozanmuyes
  • 721
  • 12
  • 26
0

So from dogmatic's linked thread, it looks like all I needed to do is replace this line from the tutorial:

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

with this:

$this->Auth->loginRedirect = array('controller' => 'alerts', 'action' => 'home');
opike
  • 7,053
  • 14
  • 68
  • 95