zen of coding

Be mindful of the redirect(s)

Just a couple of tidbits about CakePHP redirects, prefix routing and Auth.

1. Auth mysteriously redirects your logged in user into the abyss…

After you’ve checked all your setting in beforeFilter()’s of App Controller and relevant Controllers, it still seems like a completely bizarre situation where all of a sudden your well-authenticated users get completely kicked out of their “designated” area.
One more thing to check is any element (which is called from an “Authed” view) that might be using requestAction() from some Controller, which had not been granted the right privileges. To explain in more detail, requestAction() might attempt to access information (action) from a slightly unrelated controller, to which the current user has not been granted any permission. At this point the Auth component will kick-in and do its job by redirecting the user to a homepage or other “strange” location.
This one is always tricky to spot, since the bugger is hiding in the view/element, yet behaves as though something that should be taking place in your controllers.

2. Be explicit about your prefix routing destinations

If you have more than one routing prefix, such as “user” and “admin”, there are a few ways to move from one “prefixed” area to another.

For example:

$this->redirect(array(
   'controller' => 'users',
   'action' => 'something',
   'admin' => false
));

In many cases this will get you out of the “admin” area and move to the Users Controller.
However, depending on other (routing) issues, a more detailed instruction would be:

$this->redirect(array(
  'controller' => 'users',
  'action' => 'something',
  'admin' => false,
  'plugin' => false,
  'user' => true
));

The above situation might happen in case your something action is actually an alias of prefixed user_ action (such as user_details).
The plugin key is not as common, but also good to keep in mind.

  • I think you mean ‘plugin’ => null, false won’t get you what you as last I poked my head into the core, the router checks for null, not the evaluation of ‘plugin’.

    Why not use ‘prefix’ => ‘user’ instead of ‘admin’ => false, ‘user’ => true?

    $this->redirect(array(
    ‘controller’ => ‘users’,
    ‘action’ => ‘something’,
    ‘prefix’ => ‘user’,
    ‘plugin’ => null
    ));

    Nick

  • Pingback: Be mindful of the redirect(s) | DEEP in PHP()

  • good point!
    thats why i enhanced my html helper with the function defaultLink()
    which automatically resets all non-given keys like plugin and admin to false.
    saves a lot of typing.
    otherwise it behaves exactly like link()

%d bloggers like this: