Skip to content

Add redirectAfterLogin() helper#787

Open
dereuromark wants to merge 5 commits into4.xfrom
feat/redirect-after-login-helper
Open

Add redirectAfterLogin() helper#787
dereuromark wants to merge 5 commits into4.xfrom
feat/redirect-after-login-helper

Conversation

@dereuromark
Copy link
Copy Markdown
Member

@dereuromark dereuromark commented Apr 16, 2026

Summary

This adds a small controller-level helper to make the safe post-login redirect path the obvious one:

return $this->Authentication->redirectAfterLogin('/dashboard');

Internally this builds on the existing safe redirect parsing already present in the plugin via AuthenticationService::getLoginRedirect() and AuthenticationComponent::getLoginRedirect().

Why

The plugin already does the hard part correctly:

  • AuthenticationService::getLoginRedirect() rejects redirect targets with a scheme or host
  • it normalizes local paths
  • it applies optional redirect-loop validation

The gap is ergonomics.

In real applications, controller code often ends up doing this instead:

$redirect = $this->request->getQuery('redirect', '/dashboard');
return $this->redirect($redirect);

or this:

$redirect = $this->Authentication->getLoginRedirect('/dashboard') ?? '/dashboard';
return $this->redirect($redirect);

The second version is safe, but it is a two-step pattern that is easy to bypass or forget. A first-class helper makes the secure path shorter and more discoverable.

What this adds

This PR adds:

AuthenticationComponent::redirectAfterLogin(array|string|null $default = '/')

Behavior:

  1. Resolve the validated local redirect target using existing logic: getLoginRedirect($default)
  2. Fallback to $default when no valid redirect is available
  3. Return the controller redirect response directly

Example:

if ($result->isValid()) {
    return $this->Authentication->redirectAfterLogin('/dashboard');
}

We could release this as a new minor.

@dereuromark dereuromark marked this pull request as ready for review April 16, 2026 22:25
Comment thread src/Controller/Component/AuthenticationComponent.php Outdated
Comment thread tests/TestCase/Controller/Component/AuthenticationComponentTest.php
The helper always has a sensible default ('/'), so accepting null as an
explicit argument added no value and required a dead null-check branch.
The return type stays nullable because Controller::redirect() itself can
return null when a beforeRedirect event cancels the redirect.
@dereuromark
Copy link
Copy Markdown
Member Author

Yeah, sounds right.
I adjusted it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants