From 411f7573842e6c0183e8c6b6ffdec49c4337f9aa Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Mon, 30 Nov 2026 12:08:38 +0000
Subject: [PATCH 1/7] Share login and signed-in destinations across
authentication flows
Resolve the shared login destination only when the exception handler needs a browser redirect. An application without a named login route can return a 401, including when the API exception policy chooses JSON independently of the Accept header.
Move the dashboard and home conventions into the shared resolver. Retain per-component callbacks and the route-specific redirectTo extension point. Resolve each destination against the current request and reset the boot-time callbacks between tests.
---
src/auth/README.md | 1 +
src/auth/src/AuthManager.php | 18 +--
src/auth/src/AuthenticationException.php | 3 +-
src/auth/src/AuthenticationRedirects.php | 105 +++++++++++-------
.../Middleware/RedirectIfAuthenticated.php | 26 +----
.../src/Configuration/ApplicationBuilder.php | 4 +-
.../src/Configuration/Middleware.php | 18 +--
.../src/PHPUnit/AfterEachTestSubscriber.php | 1 +
tests/Auth/AuthManagerTest.php | 6 +-
.../RedirectIfAuthenticatedMiddlewareTest.php | 2 +
.../Configuration/MiddlewareTest.php | 32 +-----
tests/Integration/Auth/AuthenticationTest.php | 23 ++++
12 files changed, 116 insertions(+), 123 deletions(-)
diff --git a/src/auth/README.md b/src/auth/README.md
index 6f129415f..1513cbb70 100644
--- a/src/auth/README.md
+++ b/src/auth/README.md
@@ -7,6 +7,7 @@ Documentation: https://hypervel.org/docs/authentication
## Differences From Laravel
+- Auth redirect setters configure the shared login and signed-in destinations. Component-specific redirect callbacks take precedence. Hypervel removes `RedirectIfAuthenticated::defaultRedirectUri()`. Set the shared signed-in destination with `Auth::redirectUsersTo()`, or override `redirectTo($request)` on route-specific guest middleware.
- The shipped database password broker schedules expired reset token cleanup. Configure the schedule on the broker when porting a manual `auth:clear-resets` entry.
- `Auth::routes()` is intentionally omitted because Hypervel does not integrate `laravel/ui`. Register authentication routes explicitly or use Fortify.
- Password brokers are guard-declared via `auth.guards.{guard}.passwords`; `auth.defaults.passwords` and `AUTH_PASSWORD_BROKER` do not exist, and bare `Password::` calls resolve through the current guard or throw.
diff --git a/src/auth/src/AuthManager.php b/src/auth/src/AuthManager.php
index 86a4fab39..02fbc394d 100755
--- a/src/auth/src/AuthManager.php
+++ b/src/auth/src/AuthManager.php
@@ -298,11 +298,9 @@ public function clearUserCache(mixed $identifier, UnitEnum|string|null $guard =
}
/**
- * Configure where guests are redirected by the "auth" middleware.
+ * Set the shared login destination for the worker lifetime.
*
- * The callback persists in authentication middleware and exception
- * static properties for the worker lifetime and affects every
- * subsequent unauthenticated or session-mismatch request.
+ * Pass null to disable guest redirects.
*
* @return $this
*/
@@ -315,11 +313,7 @@ public function redirectGuestsTo(callable|string|null $redirect): static
}
/**
- * Configure where users are redirected by the "guest" middleware.
- *
- * The callback persists in the guest middleware static property for the
- * worker lifetime and affects every subsequent already-authenticated
- * guest-route request.
+ * Set the shared signed-in destination for the worker lifetime.
*
* @return $this
*/
@@ -332,11 +326,7 @@ public function redirectUsersTo(callable|string $redirect): static
}
/**
- * Configure where users are redirected by the authentication and guest middleware.
- *
- * The callbacks persist in authentication middleware and exception
- * static properties for the worker lifetime and affect every
- * subsequent matching request.
+ * Configure the shared login and signed-in destinations for the worker lifetime.
*
* @return $this
*/
diff --git a/src/auth/src/AuthenticationException.php b/src/auth/src/AuthenticationException.php
index 98fa53034..148cbe898 100644
--- a/src/auth/src/AuthenticationException.php
+++ b/src/auth/src/AuthenticationException.php
@@ -59,7 +59,8 @@ public function redirectTo(Request $request): ?string
return call_user_func(static::$redirectToCallback, $request);
}
- return null;
+ // The handler resolves the shared login destination only after checking for a JSON response.
+ return AuthenticationRedirects::guestDestination($request);
}
/**
diff --git a/src/auth/src/AuthenticationRedirects.php b/src/auth/src/AuthenticationRedirects.php
index 289ae6620..d616a1e2c 100644
--- a/src/auth/src/AuthenticationRedirects.php
+++ b/src/auth/src/AuthenticationRedirects.php
@@ -4,71 +4,100 @@
namespace Hypervel\Auth;
-use Hypervel\Auth\Middleware\Authenticate;
-use Hypervel\Auth\Middleware\RedirectIfAuthenticated;
-use Hypervel\Session\Middleware\AuthenticateSession;
+use Closure;
+use Hypervel\Http\Request;
use Hypervel\Support\Attributes\BootOnly;
+use Hypervel\Support\Facades\Route;
-/**
- * Single source of truth for boot-time auth redirect wiring.
- *
- * Configures the worker-lifetime redirect callbacks on the auth/guest
- * middleware and the authentication exception; it does not resolve or issue
- * redirects at runtime.
- */
class AuthenticationRedirects
{
+ /** @var null|Closure(Request): ?string */
+ protected static ?Closure $guestDestinationCallback = null;
+
+ /** @var null|Closure(Request): string */
+ protected static ?Closure $userDestinationCallback = null;
+
/**
- * Configure where guests are redirected by the "auth" middleware.
+ * Set the shared login destination for the worker lifetime.
*
- * The callback persists in authentication middleware and exception
- * static properties for the worker lifetime and affects every
- * subsequent unauthenticated or session-mismatch request.
+ * Pass null to disable guest redirects.
*/
#[BootOnly]
public static function redirectGuestsTo(callable|string|null $redirect): void
{
- $redirect = $redirect === null
- ? static fn () => null
- : $redirect;
-
- self::redirectTo(guests: $redirect);
+ static::$guestDestinationCallback = is_string($redirect) || $redirect === null
+ ? static fn () => $redirect
+ : Closure::fromCallable($redirect);
}
/**
- * Configure where users are redirected by the "guest" middleware.
- *
- * The callback persists in the guest middleware static property for the
- * worker lifetime and affects every subsequent already-authenticated
- * guest-route request.
+ * Set the shared signed-in destination for the worker lifetime.
*/
#[BootOnly]
public static function redirectUsersTo(callable|string $redirect): void
{
- self::redirectTo(users: $redirect);
+ static::$userDestinationCallback = is_string($redirect) ? static fn () => $redirect : Closure::fromCallable($redirect);
}
/**
- * Configure where users are redirected by the authentication and guest middleware.
- *
- * The callbacks persist in authentication middleware and exception
- * static properties for the worker lifetime and affect every
- * subsequent matching request.
+ * Configure the shared login and signed-in destinations for the worker lifetime.
*/
#[BootOnly]
public static function redirectTo(callable|string|null $guests = null, callable|string|null $users = null): void
{
- $guests = is_string($guests) ? fn () => $guests : $guests;
- $users = is_string($users) ? fn () => $users : $users;
+ if ($guests !== null) {
+ static::redirectGuestsTo($guests);
+ }
+
+ if ($users !== null) {
+ static::redirectUsersTo($users);
+ }
+ }
+
+ /**
+ * Resolve the login destination, if the application provides one.
+ */
+ public static function guestDestination(Request $request): ?string
+ {
+ if (static::$guestDestinationCallback !== null) {
+ return (static::$guestDestinationCallback)($request);
+ }
+
+ return Route::has('login') ? route('login') : null;
+ }
+
+ /**
+ * Resolve the signed-in destination for the current request.
+ */
+ public static function userDestination(Request $request): string
+ {
+ if (static::$userDestinationCallback !== null) {
+ return (static::$userDestinationCallback)($request);
+ }
- if ($guests) {
- Authenticate::redirectUsing($guests);
- AuthenticateSession::redirectUsing($guests);
- AuthenticationException::redirectUsing($guests);
+ foreach (['dashboard', 'home'] as $uri) {
+ if (Route::has($uri)) {
+ return route($uri);
+ }
}
- if ($users) {
- RedirectIfAuthenticated::redirectUsing($users);
+ $routes = Route::getRoutes()->get('GET');
+
+ foreach (['dashboard', 'home'] as $uri) {
+ if (isset($routes[$uri])) {
+ return '/' . $uri;
+ }
}
+
+ return '/';
+ }
+
+ /**
+ * Flush all static state.
+ */
+ public static function flushState(): void
+ {
+ static::$guestDestinationCallback = null;
+ static::$userDestinationCallback = null;
}
}
diff --git a/src/auth/src/Middleware/RedirectIfAuthenticated.php b/src/auth/src/Middleware/RedirectIfAuthenticated.php
index 0057e214a..164ef6f71 100644
--- a/src/auth/src/Middleware/RedirectIfAuthenticated.php
+++ b/src/auth/src/Middleware/RedirectIfAuthenticated.php
@@ -5,10 +5,10 @@
namespace Hypervel\Auth\Middleware;
use Closure;
+use Hypervel\Auth\AuthenticationRedirects;
use Hypervel\Http\Request;
use Hypervel\Support\Attributes\BootOnly;
use Hypervel\Support\Facades\Auth;
-use Hypervel\Support\Facades\Route;
use Symfony\Component\HttpFoundation\Response;
class RedirectIfAuthenticated
@@ -57,30 +57,10 @@ protected function redirectTo(Request $request): ?string
{
return static::$redirectToCallback
? call_user_func(static::$redirectToCallback, $request)
- : $this->defaultRedirectUri();
+ : AuthenticationRedirects::userDestination($request);
}
- /**
- * Get the default URI the user should be redirected to when they are authenticated.
- */
- protected function defaultRedirectUri(): string
- {
- foreach (['dashboard', 'home'] as $uri) {
- if (Route::has($uri)) {
- return route($uri);
- }
- }
-
- $routes = Route::getRoutes()->get('GET');
-
- foreach (['dashboard', 'home'] as $uri) {
- if (isset($routes[$uri])) {
- return '/' . $uri;
- }
- }
-
- return '/';
- }
+ // AuthenticationRedirects owns the fallback shared with Fortify and Passkeys in place of defaultRedirectUri().
/**
* Specify the callback that should be used to generate the redirect path.
diff --git a/src/foundation/src/Configuration/ApplicationBuilder.php b/src/foundation/src/Configuration/ApplicationBuilder.php
index 096fc5def..76db6cb09 100644
--- a/src/foundation/src/Configuration/ApplicationBuilder.php
+++ b/src/foundation/src/Configuration/ApplicationBuilder.php
@@ -254,8 +254,8 @@ protected function buildRoutingCallback(
public function withMiddleware(?callable $callback = null): static
{
$this->app->afterResolving(HttpKernel::class, function ($kernel) use ($callback) {
- $middleware = (new Middleware)
- ->redirectGuestsTo(fn () => route('login'));
+ // AuthenticationRedirects supplies the login default when the application has a login route.
+ $middleware = new Middleware;
if (! is_null($callback)) {
$callback($middleware);
diff --git a/src/foundation/src/Configuration/Middleware.php b/src/foundation/src/Configuration/Middleware.php
index edd360e72..c836c8818 100644
--- a/src/foundation/src/Configuration/Middleware.php
+++ b/src/foundation/src/Configuration/Middleware.php
@@ -482,11 +482,9 @@ public function getMiddlewareGroups(): array
}
/**
- * Configure where guests are redirected by the "auth" middleware.
+ * Set the shared login destination for the worker lifetime.
*
- * The callback persists in authentication middleware and exception
- * static properties for the worker lifetime and affects every
- * subsequent unauthenticated or session-mismatch request.
+ * Pass null to disable guest redirects.
*
* @return $this
*/
@@ -499,11 +497,7 @@ public function redirectGuestsTo(callable|string|null $redirect): static
}
/**
- * Configure where users are redirected by the "guest" middleware.
- *
- * The callback persists in the guest middleware static property for the
- * worker lifetime and affects every subsequent already-authenticated
- * guest-route request.
+ * Set the shared signed-in destination for the worker lifetime.
*
* @return $this
*/
@@ -514,11 +508,7 @@ public function redirectUsersTo(callable|string $redirect): static
}
/**
- * Configure where users are redirected by the authentication and guest middleware.
- *
- * The callbacks persist in authentication middleware and exception
- * static properties for the worker lifetime and affect every
- * subsequent matching request.
+ * Configure the shared login and signed-in destinations for the worker lifetime.
*
* @return $this
*/
diff --git a/src/testing/src/PHPUnit/AfterEachTestSubscriber.php b/src/testing/src/PHPUnit/AfterEachTestSubscriber.php
index 20270df37..fac8613dd 100644
--- a/src/testing/src/PHPUnit/AfterEachTestSubscriber.php
+++ b/src/testing/src/PHPUnit/AfterEachTestSubscriber.php
@@ -138,6 +138,7 @@ protected function flushFrameworkState(): void
$this->callIfLoaded(\Hypervel\Auth\Access\Gate::class);
$this->callIfLoaded(\Hypervel\Auth\AuthenticationException::class);
+ $this->callIfLoaded(\Hypervel\Auth\AuthenticationRedirects::class);
$this->callIfLoaded(\Hypervel\Auth\EloquentUserProvider::class);
$this->callIfLoaded(\Hypervel\Auth\Middleware\Authenticate::class);
$this->callIfLoaded(\Hypervel\Auth\Middleware\RedirectIfAuthenticated::class);
diff --git a/tests/Auth/AuthManagerTest.php b/tests/Auth/AuthManagerTest.php
index fca0858c6..98ac17e88 100644
--- a/tests/Auth/AuthManagerTest.php
+++ b/tests/Auth/AuthManagerTest.php
@@ -635,7 +635,7 @@ public function testViaRequestGuardWithoutProviderKeyGetsNullProvider(): void
$this->assertSame($user, $guard->user());
}
- public function testRedirectGuestsToConfiguresAuthenticateMiddleware(): void
+ public function testRedirectGuestsToSetsTheAuthMiddlewareDestination(): void
{
$manager = new AuthManager($this->getContainer());
@@ -647,10 +647,6 @@ public function testRedirectGuestsToConfiguresAuthenticateMiddleware(): void
$manager->redirectGuestsTo('/login');
- // Isolate Authenticate's own slot so this test fails if the aggregate
- // stops configuring the auth-middleware redirect directly.
- AuthenticationException::flushState();
-
try {
(new Authenticate($factory))->handle(Request::create('/secret'), fn () => null);
} catch (AuthenticationException $exception) {
diff --git a/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php b/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
index 18599ae32..d499e2a85 100644
--- a/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
+++ b/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
@@ -4,6 +4,7 @@
namespace Hypervel\Tests\Auth;
+use Hypervel\Auth\AuthenticationRedirects;
use Hypervel\Auth\AuthManager;
use Hypervel\Auth\EloquentUserProvider;
use Hypervel\Auth\Middleware\RedirectIfAuthenticated;
@@ -74,6 +75,7 @@ public function testCustomRedirectCallbackIsUsed(): void
$this->swapAuthGuard(authenticated: true);
RedirectIfAuthenticated::redirectUsing(fn (Request $request) => '/custom-path');
+ AuthenticationRedirects::redirectUsersTo('/shared');
$request = Request::create('/login', 'GET');
diff --git a/tests/Foundation/Configuration/MiddlewareTest.php b/tests/Foundation/Configuration/MiddlewareTest.php
index 85e3d724f..4d1a13387 100644
--- a/tests/Foundation/Configuration/MiddlewareTest.php
+++ b/tests/Foundation/Configuration/MiddlewareTest.php
@@ -5,8 +5,7 @@
namespace Hypervel\Tests\Foundation\Configuration;
use Hypervel\Auth\AuthenticationException;
-use Hypervel\Auth\Middleware\Authenticate;
-use Hypervel\Auth\Middleware\RedirectIfAuthenticated;
+use Hypervel\Auth\AuthenticationRedirects;
use Hypervel\Contracts\Foundation\Application;
use Hypervel\Cookie\Middleware\EncryptCookies;
use Hypervel\Encryption\Encrypter;
@@ -22,7 +21,6 @@
use Hypervel\Http\Middleware\TrustProxies;
use Hypervel\Http\Request;
use Hypervel\Routing\Router;
-use Hypervel\Session\Middleware\AuthenticateSession;
use Hypervel\Session\Middleware\StartSession;
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
@@ -281,35 +279,17 @@ public function testRedirectUsersToDoesNotOverwriteRedirectGuestsTo(): void
$middleware->redirectGuestsTo(static fn (): string => '/login');
$middleware->redirectUsersTo('/dashboard');
- $authenticateCallback = (new ReflectionClass(Authenticate::class))
- ->getProperty('redirectToCallback')->getValue();
- $sessionCallback = (new ReflectionClass(AuthenticateSession::class))
- ->getProperty('redirectToCallback')->getValue();
- $exceptionCallback = (new ReflectionClass(AuthenticationException::class))
- ->getProperty('redirectToCallback')->getValue();
- $usersCallback = (new ReflectionClass(RedirectIfAuthenticated::class))
- ->getProperty('redirectToCallback')->getValue();
+ $request = Request::create('/login');
- $this->assertSame('/login', $authenticateCallback(null));
- $this->assertSame('/login', $sessionCallback(null));
- $this->assertSame('/login', $exceptionCallback(null));
- $this->assertSame('/dashboard', $usersCallback(null));
-
- $reflection = new ReflectionClass(RedirectIfAuthenticated::class);
- $method = $reflection->getMethod('redirectTo');
-
- $this->assertSame('/dashboard', $method->invoke(new RedirectIfAuthenticated, Request::create('/login')));
+ $this->assertSame('/login', (new AuthenticationException)->redirectTo($request));
+ $this->assertSame('/dashboard', AuthenticationRedirects::userDestination($request));
}
- public function testRedirectGuestsToNullRegistersNullCallback(): void
+ public function testRedirectGuestsToNullDisablesGuestRedirects(): void
{
(new Middleware)->redirectGuestsTo(null);
- $callback = (new ReflectionClass(Authenticate::class))
- ->getProperty('redirectToCallback')->getValue();
-
- $this->assertNotNull($callback);
- $this->assertNull($callback(null));
+ $this->assertNull((new AuthenticationException)->redirectTo(Request::create('/')));
}
public function testPreventRequestsDuringMaintenance(): void
diff --git a/tests/Integration/Auth/AuthenticationTest.php b/tests/Integration/Auth/AuthenticationTest.php
index b27c3dea3..94bf808c3 100644
--- a/tests/Integration/Auth/AuthenticationTest.php
+++ b/tests/Integration/Auth/AuthenticationTest.php
@@ -21,9 +21,12 @@
use Hypervel\Database\Schema\Blueprint;
use Hypervel\Events\Dispatcher;
use Hypervel\Foundation\Testing\RefreshDatabase;
+use Hypervel\Http\Request;
use Hypervel\Routing\Router;
use Hypervel\Session\SessionId;
+use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Event;
+use Hypervel\Support\Facades\Exceptions;
use Hypervel\Support\Facades\Route;
use Hypervel\Support\Facades\Schema;
use Hypervel\Support\Sleep;
@@ -103,6 +106,26 @@ protected function afterRefreshingDatabase(): void
]);
}
+ public function testGuestGetsUnauthorizedUntilALoginRouteIsAvailable(): void
+ {
+ Route::get('/protected', fn () => 'private')->middleware('auth');
+ $this->get('/protected')->assertUnauthorized();
+
+ Route::name('login')->get('/sign-in', fn () => 'login');
+ $this->get('/protected')->assertRedirect('/sign-in');
+ }
+
+ public function testApiJsonPolicyRunsBeforeTheSharedLoginCallback(): void
+ {
+ Route::get('/api/private', fn () => 'private')->middleware('auth');
+ Exceptions::shouldRenderJsonWhen(
+ static fn (Request $request): bool => $request->is('api/*'),
+ );
+ Auth::redirectGuestsTo(fn () => $this->fail('JSON authentication failures do not redirect.'));
+
+ $this->get('/api/private')->assertUnauthorized()->assertJsonPath('message', 'Unauthenticated.');
+ }
+
public function testBasicAuthProtectsRoute(): void
{
$this->get('basic')->assertStatus(401);
From 74304d54e54e7175a86d0ca3de1dbc8c8393ba98 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Mon, 30 Nov 2026 12:08:38 +0000
Subject: [PATCH 2/7] Allow a lazy fallback for intended redirects
Pull the saved intended URL before resolving a fallback closure. A stored destination can now be used even when a fallback requires tenant context that is unavailable on this request. The closure runs after the session pull so session changes it makes are preserved.
---
src/routing/src/Redirector.php | 7 +++++--
src/support/src/Facades/Redirect.php | 2 +-
tests/Routing/RoutingRedirectorTest.php | 8 ++++++++
3 files changed, 14 insertions(+), 3 deletions(-)
diff --git a/src/routing/src/Redirector.php b/src/routing/src/Redirector.php
index b98ed0357..98676c324 100755
--- a/src/routing/src/Redirector.php
+++ b/src/routing/src/Redirector.php
@@ -5,6 +5,7 @@
namespace Hypervel\Routing;
use BackedEnum;
+use Closure;
use DateInterval;
use DateTimeInterface;
use Hypervel\Http\RedirectResponse;
@@ -70,10 +71,12 @@ public function guest(string $path, int $status = 302, array $headers = [], ?boo
/**
* Create a new redirect response to the previously intended location.
+ *
+ * @param (Closure(): string)|string $default
*/
- public function intended(string $default = '/', int $status = 302, array $headers = [], ?bool $secure = null): RedirectResponse
+ public function intended(Closure|string $default = '/', int $status = 302, array $headers = [], ?bool $secure = null): RedirectResponse
{
- $path = $this->session->pull('url.intended', $default);
+ $path = $this->session->pull('url.intended') ?? value($default);
return $this->to($path, $status, $headers, $secure);
}
diff --git a/src/support/src/Facades/Redirect.php b/src/support/src/Facades/Redirect.php
index 7e1ea55ce..994afa2a8 100644
--- a/src/support/src/Facades/Redirect.php
+++ b/src/support/src/Facades/Redirect.php
@@ -14,7 +14,7 @@
* @method static \Hypervel\Routing\UrlGenerator getUrlGenerator()
* @method static \Hypervel\Http\RedirectResponse guest(string $path, int $status = 302, array $headers = [], bool|null $secure = null)
* @method static bool hasMacro(string $name)
- * @method static \Hypervel\Http\RedirectResponse intended(string $default = '/', int $status = 302, array $headers = [], bool|null $secure = null)
+ * @method static \Hypervel\Http\RedirectResponse intended(\Closure|string $default = '/', int $status = 302, array $headers = [], bool|null $secure = null)
* @method static void macro(string $name, callable|object $macro)
* @method static void mixin(object $mixin, bool $replace = true)
* @method static \Hypervel\Http\RedirectResponse refresh(int $status = 302, array $headers = [])
diff --git a/tests/Routing/RoutingRedirectorTest.php b/tests/Routing/RoutingRedirectorTest.php
index 3f75a04ac..b942c2b3d 100644
--- a/tests/Routing/RoutingRedirectorTest.php
+++ b/tests/Routing/RoutingRedirectorTest.php
@@ -104,6 +104,11 @@ public function testIntendedRedirectToIntendedUrlInSession(): void
$this->assertSame('http://foo.com/bar', $response->getTargetUrl());
$this->assertNull($this->session->get('url.intended'));
+
+ $this->session->put('url.intended', 'http://foo.com/bar');
+ $response = $this->redirect->intended(fn () => $this->fail('The intended URL already exists.'));
+
+ $this->assertSame('http://foo.com/bar', $response->getTargetUrl());
}
public function testIntendedWithoutIntendedUrlInSession(): void
@@ -115,6 +120,9 @@ public function testIntendedWithoutIntendedUrlInSession(): void
// with a fallback url
$response = $this->redirect->intended('bar');
$this->assertSame('http://foo.com/bar', $response->getTargetUrl());
+
+ $response = $this->redirect->intended(static fn (): string => 'bar');
+ $this->assertSame('http://foo.com/bar', $response->getTargetUrl());
}
public function testRefreshRedirectToCurrentUrl(): void
From b374783e65c2102556bb84c1d2f03b9b5874452e Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Mon, 30 Nov 2026 12:08:38 +0000
Subject: [PATCH 3/7] Use the shared auth destinations in Fortify and Passkeys
Remove the competing package defaults while preserving individual action overrides and the Fortify passkey login integration. Prefer the saved intended URL and avoid evaluating the login fallback when a password reset already has a destination.
Send visitors with an expired two-factor challenge to the shared login page without saving the challenge as an intended URL. Preserve the query and fragment of email verification destinations when adding the verified flag.
---
src/fortify/README.md | 2 +-
src/fortify/config/fortify.php | 1 -
src/fortify/src/Fortify.php | 8 +++++---
.../TwoFactorAuthenticatedSessionController.php | 10 +++++++++-
src/fortify/src/Http/Responses/LoginResponse.php | 2 +-
.../Http/Responses/PasswordConfirmedResponse.php | 2 +-
.../src/Http/Responses/PasswordResetResponse.php | 14 ++++++++++----
.../src/Http/Responses/RedirectAsIntended.php | 2 +-
.../src/Http/Responses/RegisterResponse.php | 2 +-
.../src/Http/Responses/TwoFactorLoginResponse.php | 2 +-
.../src/Http/Responses/VerifyEmailResponse.php | 11 ++++++++---
src/fortify/stubs/fortify.php | 6 ++----
src/passkeys/README.md | 2 +-
src/passkeys/config/passkeys.php | 11 -----------
.../src/Http/Responses/PasskeyLoginResponse.php | 6 +++---
src/passkeys/src/Passkeys.php | 3 ++-
...enticatedSessionControllerWithTwoFactorTest.php | 9 +++++++++
tests/Fortify/FortifyApiTest.php | 6 ++++++
tests/Fortify/FortifyStaticStateTest.php | 2 ++
tests/Fortify/PasskeyTest.php | 1 -
tests/Fortify/TestCase.php | 4 +++-
tests/Fortify/VerifyEmailControllerTest.php | 6 ++++++
tests/Passkeys/Feature/PasskeysTest.php | 5 ++---
tests/Passkeys/PasskeysStaticStateTest.php | 3 ++-
tests/Passkeys/TestCase.php | 1 -
25 files changed, 76 insertions(+), 45 deletions(-)
diff --git a/src/fortify/README.md b/src/fortify/README.md
index 2ed979f66..4adceb39b 100644
--- a/src/fortify/README.md
+++ b/src/fortify/README.md
@@ -8,7 +8,7 @@ Documentation: https://hypervel.org/docs/fortify
- Fortify follows Hypervel's current default guard selected by `Auth::shouldUse()` or `auth.defaults.guard`, with optional `fortify.guard` route-group selection for built-in routes.
- Fortify uses the password reset broker declared by the selected guard's `passwords` key instead of using a separate Fortify broker setting.
- Fortify integrates with the standalone `hypervel/passkeys` package and keeps passkeys polymorphic across authenticatable model classes.
-- Fortify supports boot-time request-aware redirect callbacks for dynamic post-login destinations, such as for custom domains, multi-guard apps, or multi-tenant apps.
+- Fortify uses the shared signed-in destination in place of `fortify.home`. Individual actions may override it with a configured path or a request-aware `Fortify::redirectUsing()` callback.
- Fortify throttles two-factor challenge submissions by default.
- Fortify scopes login throttling per guard (`guard|username|ip`), so a lockout in one actor silo never blocks logins in another.
- Fortify password confirmation follows the current guard: guard-scoped session key, optional per-guard `password_timeout`, and the confirmed-password status endpoint uses the same resolution. This also unifies Laravel's mismatched 900/10800 fallback defaults.
diff --git a/src/fortify/config/fortify.php b/src/fortify/config/fortify.php
index 022f52161..9b0bc9c2d 100644
--- a/src/fortify/config/fortify.php
+++ b/src/fortify/config/fortify.php
@@ -15,7 +15,6 @@
'username' => 'email',
'email' => 'email',
'views' => true,
- 'home' => '/home',
'prefix' => '',
'domain' => null,
'lowercase_usernames' => false,
diff --git a/src/fortify/src/Fortify.php b/src/fortify/src/Fortify.php
index f6c5dae98..1b3e462e7 100644
--- a/src/fortify/src/Fortify.php
+++ b/src/fortify/src/Fortify.php
@@ -5,6 +5,7 @@
namespace Hypervel\Fortify;
use Closure;
+use Hypervel\Auth\AuthenticationRedirects;
use Hypervel\Container\Container;
use Hypervel\Contracts\Auth\Factory as AuthFactory;
use Hypervel\Contracts\Auth\StatefulGuard;
@@ -82,7 +83,8 @@ public static function email(): string
*/
public static function redirects(string $redirect, mixed $default = null, ?Request $request = null): string
{
- if ($request !== null && isset(self::$redirectUsingCallbacks[$redirect])) {
+ if (isset(self::$redirectUsingCallbacks[$redirect])) {
+ $request ??= self::container()->make('request');
$resolved = (self::$redirectUsingCallbacks[$redirect])($request);
if (is_string($resolved) && $resolved !== '') {
@@ -91,8 +93,8 @@ public static function redirects(string $redirect, mixed $default = null, ?Reque
}
return (string) (self::config()->nullableString("fortify.redirects.{$redirect}", null)
- ?? $default
- ?? self::config()->string('fortify.home'));
+ ?? value($default)
+ ?? AuthenticationRedirects::userDestination($request ?? self::container()->make('request')));
}
/**
diff --git a/src/fortify/src/Http/Controllers/TwoFactorAuthenticatedSessionController.php b/src/fortify/src/Http/Controllers/TwoFactorAuthenticatedSessionController.php
index 9c210692a..1a6ec934f 100644
--- a/src/fortify/src/Http/Controllers/TwoFactorAuthenticatedSessionController.php
+++ b/src/fortify/src/Http/Controllers/TwoFactorAuthenticatedSessionController.php
@@ -4,6 +4,7 @@
namespace Hypervel\Fortify\Http\Controllers;
+use Hypervel\Auth\AuthenticationRedirects;
use Hypervel\Contracts\Auth\Authenticatable;
use Hypervel\Contracts\Container\Container;
use Hypervel\Database\Eloquent\Model;
@@ -38,7 +39,14 @@ public function __construct(
public function create(TwoFactorLoginRequest $request): TwoFactorChallengeViewResponse
{
if (! $request->hasChallengedUser()) {
- throw new HttpResponseException(redirect()->route('login'));
+ $destination = AuthenticationRedirects::guestDestination($request);
+
+ if ($destination === null) {
+ abort(401);
+ }
+
+ // A fresh login must not return the user to an expired challenge.
+ throw new HttpResponseException(redirect($destination));
}
return $this->container->make(TwoFactorChallengeViewResponse::class);
diff --git a/src/fortify/src/Http/Responses/LoginResponse.php b/src/fortify/src/Http/Responses/LoginResponse.php
index fb84562c2..a2fcf85a3 100644
--- a/src/fortify/src/Http/Responses/LoginResponse.php
+++ b/src/fortify/src/Http/Responses/LoginResponse.php
@@ -18,6 +18,6 @@ public function toResponse(Request $request): Response
{
return $request->wantsJson()
? response()->json(['two_factor' => false])
- : redirect()->intended(Fortify::redirects('login', request: $request));
+ : redirect()->intended(static fn (): string => Fortify::redirects('login', request: $request));
}
}
diff --git a/src/fortify/src/Http/Responses/PasswordConfirmedResponse.php b/src/fortify/src/Http/Responses/PasswordConfirmedResponse.php
index 725ded271..7475839c5 100644
--- a/src/fortify/src/Http/Responses/PasswordConfirmedResponse.php
+++ b/src/fortify/src/Http/Responses/PasswordConfirmedResponse.php
@@ -19,6 +19,6 @@ public function toResponse(Request $request): Response
{
return $request->wantsJson()
? new JsonResponse('', 201)
- : redirect()->intended(Fortify::redirects('password-confirmation', request: $request));
+ : redirect()->intended(static fn (): string => Fortify::redirects('password-confirmation', request: $request));
}
}
diff --git a/src/fortify/src/Http/Responses/PasswordResetResponse.php b/src/fortify/src/Http/Responses/PasswordResetResponse.php
index 8806d9175..a29a0fa50 100644
--- a/src/fortify/src/Http/Responses/PasswordResetResponse.php
+++ b/src/fortify/src/Http/Responses/PasswordResetResponse.php
@@ -4,6 +4,7 @@
namespace Hypervel\Fortify\Http\Responses;
+use Hypervel\Auth\AuthenticationRedirects;
use Hypervel\Contracts\Config\Repository as Config;
use Hypervel\Fortify\Contracts\PasswordResetResponse as PasswordResetResponseContract;
use Hypervel\Fortify\Fortify;
@@ -26,10 +27,15 @@ public function __construct(
*/
public function toResponse(Request $request): Response
{
- $views = app(Config::class)->boolean('fortify.views');
+ if ($request->wantsJson()) {
+ return new JsonResponse(['message' => trans($this->status)], 200);
+ }
- return $request->wantsJson()
- ? new JsonResponse(['message' => trans($this->status)], 200)
- : redirect(Fortify::redirects('password-reset', $views ? route('login') : null, $request))->with('status', trans($this->status));
+ $login = app(Config::class)->boolean('fortify.views')
+ ? static fn (): ?string => AuthenticationRedirects::guestDestination($request)
+ : null;
+
+ return redirect(Fortify::redirects('password-reset', $login, $request))
+ ->with('status', trans($this->status));
}
}
diff --git a/src/fortify/src/Http/Responses/RedirectAsIntended.php b/src/fortify/src/Http/Responses/RedirectAsIntended.php
index f2c85c6e8..385d32bf0 100644
--- a/src/fortify/src/Http/Responses/RedirectAsIntended.php
+++ b/src/fortify/src/Http/Responses/RedirectAsIntended.php
@@ -24,6 +24,6 @@ public function __construct(
*/
public function toResponse(Request $request): Response
{
- return redirect()->intended(Fortify::redirects($this->name, request: $request));
+ return redirect()->intended(fn (): string => Fortify::redirects($this->name, request: $request));
}
}
diff --git a/src/fortify/src/Http/Responses/RegisterResponse.php b/src/fortify/src/Http/Responses/RegisterResponse.php
index b47c0d641..b596bbfaa 100644
--- a/src/fortify/src/Http/Responses/RegisterResponse.php
+++ b/src/fortify/src/Http/Responses/RegisterResponse.php
@@ -16,6 +16,6 @@ public function toResponse(Request $request): Response
{
return $request->wantsJson()
? new JsonResponse('', 201)
- : redirect()->intended(Fortify::redirects('register', request: $request));
+ : redirect()->intended(static fn (): string => Fortify::redirects('register', request: $request));
}
}
diff --git a/src/fortify/src/Http/Responses/TwoFactorLoginResponse.php b/src/fortify/src/Http/Responses/TwoFactorLoginResponse.php
index 6980d6522..abd0c1738 100644
--- a/src/fortify/src/Http/Responses/TwoFactorLoginResponse.php
+++ b/src/fortify/src/Http/Responses/TwoFactorLoginResponse.php
@@ -16,6 +16,6 @@ public function toResponse(Request $request): Response
{
return $request->wantsJson()
? new JsonResponse('', 204)
- : redirect()->intended(Fortify::redirects('login', request: $request));
+ : redirect()->intended(static fn (): string => Fortify::redirects('login', request: $request));
}
}
diff --git a/src/fortify/src/Http/Responses/VerifyEmailResponse.php b/src/fortify/src/Http/Responses/VerifyEmailResponse.php
index a1f93d45b..bfe0182fe 100644
--- a/src/fortify/src/Http/Responses/VerifyEmailResponse.php
+++ b/src/fortify/src/Http/Responses/VerifyEmailResponse.php
@@ -8,14 +8,19 @@
use Hypervel\Fortify\Fortify;
use Hypervel\Http\JsonResponse;
use Hypervel\Http\Request;
+use Hypervel\Support\Uri;
use Symfony\Component\HttpFoundation\Response;
class VerifyEmailResponse implements VerifyEmailResponseContract
{
public function toResponse(Request $request): Response
{
- return $request->wantsJson()
- ? new JsonResponse('', 204)
- : redirect()->intended(Fortify::redirects('email-verification', request: $request) . '?verified=1');
+ if ($request->wantsJson()) {
+ return new JsonResponse('', 204);
+ }
+
+ return redirect()->intended(static fn (): string => (string) Uri::of(
+ Fortify::redirects('email-verification', request: $request)
+ )->withQuery(['verified' => '1']));
}
}
diff --git a/src/fortify/stubs/fortify.php b/src/fortify/stubs/fortify.php
index 09fdc542b..4e0ae508a 100644
--- a/src/fortify/stubs/fortify.php
+++ b/src/fortify/stubs/fortify.php
@@ -55,16 +55,14 @@
/*
|--------------------------------------------------------------------------
- | Home Path and Redirects
+ | Redirects
|--------------------------------------------------------------------------
|
| Fortify uses these destinations after successful authentication actions.
- | Null feature redirects fall back to the home path.
+ | Leave a destination unset to use the default for that action.
|
*/
- 'home' => '/home',
-
'redirects' => [
'login' => null,
'logout' => null,
diff --git a/src/passkeys/README.md b/src/passkeys/README.md
index fa9e556bc..3bc349386 100644
--- a/src/passkeys/README.md
+++ b/src/passkeys/README.md
@@ -10,7 +10,7 @@ Documentation: https://hypervel.org/docs/fortify
- The `{passkey}` route binding resolves only the authenticated owner's passkeys, so another user's passkey returns 404 instead of Laravel's 403. Routes that manage other users' passkeys should use a different parameter name.
- Passkeys omit Laravel's `relyingPartyName()` because `web-auth/webauthn-lib` deprecates non-empty relying party names.
- Passkeys include explicit orphan cleanup for polymorphic owners.
-- Passkeys support boot-time request-aware callbacks for redirects and WebAuthn relying party / origin settings, such as for custom domains, multi-guard apps, or multi-tenant apps.
+- Standalone passkey login uses the shared signed-in destination in place of `passkeys.redirect`. Use `Passkeys::redirectUsing()` for a passkey-specific destination. Passkeys also support request-aware WebAuthn relying party and origin settings.
- Passkeys keep Laravel's directly writable `$passkeyModel` static property private so worker-lifetime state remains typed and resettable. Use `usePasskeyModel()` instead.
- Passkeys omit Laravel's protected `StorePasskey::ensureCredentialIsUnique()` pre-check because the unique `credential_id` index rejects duplicates without an extra query. Override `createPasskey()` to customize duplicate handling.
diff --git a/src/passkeys/config/passkeys.php b/src/passkeys/config/passkeys.php
index 9dad596ed..dafaaff6c 100644
--- a/src/passkeys/config/passkeys.php
+++ b/src/passkeys/config/passkeys.php
@@ -108,15 +108,4 @@
*/
'throttle' => 'throttle:6,1',
-
- /*
- |--------------------------------------------------------------------------
- | Redirect
- |--------------------------------------------------------------------------
- |
- | The path to redirect to after successful passkey verification.
- |
- */
-
- 'redirect' => '/',
];
diff --git a/src/passkeys/src/Http/Responses/PasskeyLoginResponse.php b/src/passkeys/src/Http/Responses/PasskeyLoginResponse.php
index d64bc32f8..20bcb171f 100644
--- a/src/passkeys/src/Http/Responses/PasskeyLoginResponse.php
+++ b/src/passkeys/src/Http/Responses/PasskeyLoginResponse.php
@@ -17,14 +17,14 @@ class PasskeyLoginResponse implements PasskeyLoginResponseContract
*/
public function toResponse(Request $request): Response
{
- $redirect = Passkeys::redirectTo($request);
+ $redirect = redirect()->intended(static fn (): string => Passkeys::redirectTo($request));
if ($request->wantsJson()) {
return new JsonResponse([
- 'redirect' => redirect()->intended($redirect)->getTargetUrl(),
+ 'redirect' => $redirect->getTargetUrl(),
], 200);
}
- return redirect()->intended($redirect);
+ return $redirect;
}
}
diff --git a/src/passkeys/src/Passkeys.php b/src/passkeys/src/Passkeys.php
index 0530f22e0..02a21c6e7 100644
--- a/src/passkeys/src/Passkeys.php
+++ b/src/passkeys/src/Passkeys.php
@@ -5,6 +5,7 @@
namespace Hypervel\Passkeys;
use Closure;
+use Hypervel\Auth\AuthenticationRedirects;
use Hypervel\Container\Container;
use Hypervel\Context\RequestContext;
use Hypervel\Contracts\Auth\Factory as AuthFactory;
@@ -236,7 +237,7 @@ public static function redirectTo(Request $request): string
}
}
- return self::config()->string('passkeys.redirect', '/');
+ return AuthenticationRedirects::userDestination($request);
}
/**
diff --git a/tests/Fortify/AuthenticatedSessionControllerWithTwoFactorTest.php b/tests/Fortify/AuthenticatedSessionControllerWithTwoFactorTest.php
index cefc47e04..0efa25986 100644
--- a/tests/Fortify/AuthenticatedSessionControllerWithTwoFactorTest.php
+++ b/tests/Fortify/AuthenticatedSessionControllerWithTwoFactorTest.php
@@ -34,6 +34,15 @@ class AuthenticatedSessionControllerWithTwoFactorTest extends TestCase
{
use RefreshDatabase;
+ public function testMissingChallengeUsesTheSharedLoginWithoutSavingAnIntendedUrl(): void
+ {
+ Auth::redirectGuestsTo('/sign-in');
+ $this->get('/two-factor-challenge')->assertRedirect('/sign-in')->assertSessionMissing('url.intended');
+
+ Auth::redirectGuestsTo(null);
+ $this->get('/two-factor-challenge')->assertUnauthorized();
+ }
+
#[TestWith([false])]
#[TestWith([true])]
public function testFailedLoginIsTimeboxedUsingTheConfiguredDuration(bool $usingCallback): void
diff --git a/tests/Fortify/FortifyApiTest.php b/tests/Fortify/FortifyApiTest.php
index b46e2ace4..79458763d 100644
--- a/tests/Fortify/FortifyApiTest.php
+++ b/tests/Fortify/FortifyApiTest.php
@@ -46,6 +46,7 @@
use Hypervel\Http\RedirectResponse;
use Hypervel\Http\Request;
use Hypervel\RateLimiter\RateLimiter;
+use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Password;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
@@ -122,6 +123,11 @@ public function testPasswordResetResponseUsesStatusOnlyConstructionForJsonAndRed
$this->assertInstanceOf(RedirectResponse::class, $viewRedirectResponse);
$this->assertSame(route('login'), $viewRedirectResponse->getTargetUrl());
+
+ $this->app->make(Config::class)->set('fortify.redirects.password-reset', '/reset-complete');
+ Auth::redirectGuestsTo(fn () => $this->fail('The reset destination already exists.'));
+
+ $this->assertSame(url('/reset-complete'), $response->toResponse(Request::create('/'))->getTargetUrl());
}
public function testPackageConfigurationRetainsInternalDefaults(): void
diff --git a/tests/Fortify/FortifyStaticStateTest.php b/tests/Fortify/FortifyStaticStateTest.php
index 7b350aa9a..8ea1ce28b 100644
--- a/tests/Fortify/FortifyStaticStateTest.php
+++ b/tests/Fortify/FortifyStaticStateTest.php
@@ -22,6 +22,8 @@ public function testRedirectCallbackIsEvaluatedPerRequestAndResetByFlushState():
$this->assertSame('/dashboard', Fortify::redirects('login', request: Request::create('/', server: ['HTTP_X_ADMIN' => '1'])));
$this->assertSame('/account', Fortify::redirects('login', request: Request::create('/')));
+ $this->assertSame('/account', Fortify::redirects('login'));
+
Fortify::flushState();
$this->assertSame('/home', Fortify::redirects('login', request: Request::create('/')));
diff --git a/tests/Fortify/PasskeyTest.php b/tests/Fortify/PasskeyTest.php
index 16448dcfb..41b7da67b 100644
--- a/tests/Fortify/PasskeyTest.php
+++ b/tests/Fortify/PasskeyTest.php
@@ -90,7 +90,6 @@ public function testPasskeysConfigurationIsSynchronizedWithFortifyConfiguration(
$this->assertSame(['web'], config('passkeys.middleware'));
$this->assertSame(['password.confirm'], config('passkeys.management_middleware'));
$this->assertSame('throttle:6,1', config('passkeys.throttle'));
- $this->assertSame('/', config('passkeys.redirect'));
$request = Request::create('/');
diff --git a/tests/Fortify/TestCase.php b/tests/Fortify/TestCase.php
index d5108c554..a32c01060 100644
--- a/tests/Fortify/TestCase.php
+++ b/tests/Fortify/TestCase.php
@@ -10,6 +10,7 @@
use Hypervel\Fortify\Features;
use Hypervel\Fortify\FortifyServiceProvider;
use Hypervel\Passkeys\PasskeysServiceProvider;
+use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Schema;
use Hypervel\Testbench\TestCase as TestbenchTestCase;
use Hypervel\Tests\Fortify\Fixtures\Admin;
@@ -55,8 +56,9 @@ protected function defineEnvironment(ApplicationContract $app): void
'table' => 'admin_password_reset_tokens',
],
'database.default' => 'testing',
- 'fortify.home' => '/home',
]);
+
+ Auth::redirectUsersTo('/home');
}
/**
diff --git a/tests/Fortify/VerifyEmailControllerTest.php b/tests/Fortify/VerifyEmailControllerTest.php
index 24a5351f0..b418ff1e1 100644
--- a/tests/Fortify/VerifyEmailControllerTest.php
+++ b/tests/Fortify/VerifyEmailControllerTest.php
@@ -5,6 +5,7 @@
namespace Hypervel\Tests\Fortify;
use Hypervel\Auth\Events\Verified;
+use Hypervel\Fortify\Fortify;
use Hypervel\Foundation\Http\FormRequest;
use Hypervel\Foundation\Testing\RefreshDatabase;
use Hypervel\Support\Facades\Event;
@@ -47,6 +48,8 @@ protected function assertEmailCanBeVerified(): void
]
);
+ Fortify::redirectUsing('email-verification', fn () => $this->fail('The intended URL already exists.'));
+
$response = $this->actingAs($user)
->withSession(['url.intended' => 'http://foo.com/bar'])
->get($url);
@@ -77,6 +80,9 @@ public function testRedirectedIfEmailIsAlreadyVerified(): void
$response->assertStatus(302);
Event::assertNotDispatched(Verified::class);
+
+ config()->set('fortify.redirects.email-verification', '/account?tab=profile#email');
+ $this->actingAs($user)->get($url)->assertRedirect('/account?tab=profile&verified=1#email');
}
public function testEmailIsNotVerifiedIfIdDoesNotMatch(): void
diff --git a/tests/Passkeys/Feature/PasskeysTest.php b/tests/Passkeys/Feature/PasskeysTest.php
index b63f5fa4a..819e2b3de 100644
--- a/tests/Passkeys/Feature/PasskeysTest.php
+++ b/tests/Passkeys/Feature/PasskeysTest.php
@@ -43,14 +43,13 @@ public function testConfigDefaultsRemainAligned(): void
$this->assertSame('throttle:6,1', $config['throttle']);
}
- public function testOmittedTimeoutAndRedirectUseTheirDefaults(): void
+ public function testOmittedTimeoutUsesItsDefault(): void
{
$config = config()->array('passkeys');
- unset($config['timeout'], $config['redirect']);
+ unset($config['timeout']);
config()->set('passkeys', $config);
$this->assertSame(Passkeys::DEFAULT_TIMEOUT, Passkeys::timeout());
- $this->assertSame('/', Passkeys::redirectTo(Request::create('/')));
}
public function testItReturnsTheConfiguredUserHandleSecret(): void
diff --git a/tests/Passkeys/PasskeysStaticStateTest.php b/tests/Passkeys/PasskeysStaticStateTest.php
index ef61ea07e..bf74c009a 100644
--- a/tests/Passkeys/PasskeysStaticStateTest.php
+++ b/tests/Passkeys/PasskeysStaticStateTest.php
@@ -8,13 +8,14 @@
use Hypervel\Http\Request;
use Hypervel\Passkeys\Passkey;
use Hypervel\Passkeys\Passkeys;
+use Hypervel\Support\Facades\Auth;
use Hypervel\Tests\Passkeys\Fixtures\User;
class PasskeysStaticStateTest extends TestCase
{
public function testFlushStateResetsRouteRegistrationAndRedirectCallback(): void
{
- config(['passkeys.redirect' => '/account']);
+ Auth::redirectUsersTo('/account');
Passkeys::ignoreRoutes();
Passkeys::redirectUsing(static fn (Request $request): string => '/tenant-home');
diff --git a/tests/Passkeys/TestCase.php b/tests/Passkeys/TestCase.php
index 03b86a977..b7e168fc7 100644
--- a/tests/Passkeys/TestCase.php
+++ b/tests/Passkeys/TestCase.php
@@ -59,7 +59,6 @@ protected function defineEnvironment(ApplicationContract $app): void
'passkeys.relying_party_id' => 'localhost',
'passkeys.allowed_origins' => ['https://localhost'],
'passkeys.user_handle_secret' => 'test-passkey-secret',
- 'passkeys.redirect' => '/',
'passkeys.timeout' => 60000,
]);
}
From b974ae9abc3270e9f4adb3ea6916d143af9cdc41 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Mon, 30 Nov 2026 12:08:38 +0000
Subject: [PATCH 4/7] Document shared auth redirects and the migration from
package defaults
Show how to configure fixed and request-aware destinations, how to keep an override local to package middleware, and which destination takes precedence. Cover the removed config keys and the behavior of API-only applications without a login page.
---
src/docs/authentication.md | 25 ++++++++++++++++++++++---
src/docs/fortify.md | 7 +++----
src/docs/porting-from-laravel.md | 2 ++
3 files changed, 27 insertions(+), 7 deletions(-)
diff --git a/src/docs/authentication.md b/src/docs/authentication.md
index 0ad7f9984..929788d41 100644
--- a/src/docs/authentication.md
+++ b/src/docs/authentication.md
@@ -427,7 +427,7 @@ Route::get('/flights', function () {
#### Redirecting Unauthenticated Users
-When the `auth` middleware detects an unauthenticated user, it will redirect the user to the `login` [named route](/docs/{{version}}/routing#named-routes). You may modify this behavior using the `redirectGuestsTo` method within your application's `bootstrap/app.php` file:
+When the `auth` middleware detects an unauthenticated user, it redirects browser requests to the `login` [named route](/docs/{{version}}/routing#named-routes) if it exists. Without a login destination, the response is HTTP 401. Requests your exception handler renders as JSON receive a JSON 401. You may modify this behavior using the `redirectGuestsTo` method within your application's `bootstrap/app.php` file:
```php
use Hypervel\Foundation\Configuration\Middleware;
@@ -463,12 +463,12 @@ Redirect paths may be strings or request-aware callbacks. Passing `null` through
Configure these redirects from `bootstrap/app.php` with the middleware configurator, or from a service provider / package with the `Auth` facade. Both high-level APIs configure the same global redirect callbacks, so an application should generally choose one style for each redirect. If both high-level APIs are called for the same redirect, the most recent registration wins.
-Under the hood, the `auth` middleware throws a `Hypervel\Auth\AuthenticationException` when a user is unauthenticated. This exception is converted into a redirect (or a 401 JSON response for API requests) by your application's exception handler. If you need lower-level control beyond the high-level APIs, you may override the `unauthenticated` method in your exception handler or configure the low-level redirect callbacks directly on the relevant middleware or exception classes.
+Under the hood, the `auth` middleware throws a `Hypervel\Auth\AuthenticationException` when a user is unauthenticated. This exception is converted into a redirect (or a 401 JSON response for API requests) by your application's exception handler. A redirect configured directly on an individual middleware or authentication exception takes precedence over the shared destination for that component, regardless of registration order.
#### Redirecting Authenticated Users
-When the `guest` middleware detects an authenticated user, it will redirect the user to the `dashboard` or `home` named route. You may modify this behavior using the `redirectUsersTo` method within your application's `bootstrap/app.php` file:
+When the `guest` middleware detects an authenticated user, it tries the `dashboard` and `home` named routes, then the corresponding registered GET paths, then `/`. Fortify and standalone Passkeys also use this signed-in destination after login when there is no intended URL or flow-specific redirect. You may modify this behavior using the `redirectUsersTo` method within your application's `bootstrap/app.php` file:
```php
use Hypervel\Foundation\Configuration\Middleware;
@@ -497,6 +497,25 @@ public function boot(): void
}
```
+Pass a closure when the destination depends on the request. For example, generating a tenant route inside the closure uses the current request's route parameter defaults. Packages can read the shared destinations with `Hypervel\Auth\AuthenticationRedirects::guestDestination($request)` and `AuthenticationRedirects::userDestination($request)`.
+
+To redirect users from a package's guest routes to its own dashboard, attach a middleware subclass to those routes:
+
+```php
+use Hypervel\Auth\Middleware\RedirectIfAuthenticated;
+use Hypervel\Http\Request;
+
+class RedirectPackageUsers extends RedirectIfAuthenticated
+{
+ protected function redirectTo(Request $request): ?string
+ {
+ return route('admin.dashboard');
+ }
+}
+```
+
+If only some routes handled by this subclass need a custom destination, return `parent::redirectTo($request)` for the others.
+
When the `guest` middleware names a guard and the request continues, that guard becomes the current default guard for the request. If multiple guards are listed, the first guard is selected.
You may use the `RedirectIfAuthenticated` middleware's `using` method as an alternative to a middleware alias. For example, the following is equivalent to `guest:admin,web`:
diff --git a/src/docs/fortify.md b/src/docs/fortify.md
index cc13f55ea..63b0343ee 100644
--- a/src/docs/fortify.md
+++ b/src/docs/fortify.md
@@ -168,7 +168,7 @@ public function register(): void
### Redirects
-Static redirect fallbacks live in `fortify.redirects` and `fortify.home`. Successful login, registration, password confirmation, password reset, email verification, and logout responses use these paths as fallbacks.
+Fortify uses the [shared signed-in destination](/docs/{{version}}/authentication#redirecting-authenticated-users) after login, registration, password confirmation and email verification. A saved intended URL takes priority. Set a path in `fortify.redirects` to customize an individual action, such as sending newly registered users to onboarding.
Redirects may also be computed per request:
@@ -186,9 +186,9 @@ public function boot(): void
The callback is registered for the worker lifetime, but the callback result is computed for each request. This is safe for multi-tenant and multi-guard applications as long as you do not cache request-specific data in static properties.
-This Fortify redirect API controls successful Fortify action fallbacks, such as login or registration responses when no intended URL is stored. It does not configure auth or guest middleware redirects. Use `Auth::redirectGuestsTo()` and `Auth::redirectUsersTo()` for middleware redirects, or the middleware configurator equivalents in `bootstrap/app.php`.
+A non-empty destination returned by the action callback takes precedence over its configured path. After a password reset, Fortify uses the shared login destination when views are enabled and a login destination exists, otherwise the signed-in destination. Logout defaults to `/`. Both actions accept their own redirect overrides.
-Standalone Passkeys has its own `Passkeys::redirectUsing()` callback and `passkeys.redirect` fallback. When Fortify integrates passkeys, it installs a callback so passkey login uses the same request-aware login redirect as password login.
+Standalone Passkeys uses the same signed-in destination. Use `Passkeys::redirectUsing()` to customize passkey login specifically. When Fortify integrates passkeys, its login redirect applies to both password and passkey login.
### Multi-Guard Applications
@@ -914,7 +914,6 @@ Standalone routes use the following configuration options:
| `middleware` | The required middleware applied to every standalone route. |
| `management_middleware` | The required additional middleware applied when creating or deleting passkeys. |
| `throttle` | The throttle middleware applied to passkey login, confirmation, and registration endpoints. Omission uses `throttle:6,1`; null disables throttling. |
-| `redirect` | The successful login destination used when no intended URL exists. Omission uses `/`. |
Call `Passkeys::ignoreRoutes()` during boot before registering your own endpoints:
diff --git a/src/docs/porting-from-laravel.md b/src/docs/porting-from-laravel.md
index a0f451a5a..58122c328 100644
--- a/src/docs/porting-from-laravel.md
+++ b/src/docs/porting-from-laravel.md
@@ -650,6 +650,8 @@ Replace references to Laravel's deprecated `VerifyCsrfToken` and `ValidateCsrfTo
### Fortify
+Replace `fortify.home` and `passkeys.redirect` with `Auth::redirectUsersTo()` for the shared signed-in destination. See [authentication redirects](/docs/{{version}}/authentication#redirecting-authenticated-users).
+
User models that use Fortify's `TwoFactorAuthenticatable` trait must also implement `Hypervel\Fortify\Contracts\TwoFactorAuthenticationUser`, or two-factor challenges will fail. See [two-factor authentication](/docs/{{version}}/fortify#two-factor-authentication).
Fortify ignores Laravel's `fortify.passwords` setting. Declare the password reset broker with the guard's `passwords` key in `config/auth.php` instead. See [password resets](/docs/{{version}}/fortify#password-resets). Laravel's deprecated `Laravel\Fortify\Rules\Password` rule is not available; use `Hypervel\Validation\Rules\Password`.
From 048a6e742944257aac2c80a6b71b7b2b61ca2e29 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Mon, 30 Nov 2026 12:44:16 +0000
Subject: [PATCH 5/7] Skip conventional auth destinations with missing route
parameters
Try the next implicit destination when the current request cannot supply a required path or domain parameter. Explicit redirect callbacks retain their normal errors. Document the exception on the URL generation entry points and declare the routing dependency directly.
Exercise compiled routes, tenant URL defaults and the Testbench guest request without a login route. With exception handling disabled, this request now raises the authentication exception.
---
src/auth/composer.json | 1 +
src/auth/src/AuthenticationRedirects.php | 23 ++++++++++++++++---
src/contracts/src/Routing/UrlGenerator.php | 2 ++
src/docs/authentication.md | 4 ++--
src/foundation/src/helpers.php | 2 ++
src/routing/src/UrlGenerator.php | 1 +
.../RedirectIfAuthenticatedMiddlewareTest.php | 21 ++++++++++++++++-
tests/Integration/Auth/AuthenticationTest.php | 8 +++++--
.../SlimSkeletonApplicationTest.php | 6 ++---
9 files changed, 57 insertions(+), 11 deletions(-)
diff --git a/src/auth/composer.json b/src/auth/composer.json
index aedb672b9..312bde60b 100644
--- a/src/auth/composer.json
+++ b/src/auth/composer.json
@@ -40,6 +40,7 @@
"hypervel/macroable": "^0.4",
"hypervel/notifications": "^0.4",
"hypervel/queue": "^0.4",
+ "hypervel/routing": "^0.4",
"hypervel/session": "^0.4",
"hypervel/support": "^0.4",
"nesbot/carbon": "^3.13.1",
diff --git a/src/auth/src/AuthenticationRedirects.php b/src/auth/src/AuthenticationRedirects.php
index d616a1e2c..76ad34076 100644
--- a/src/auth/src/AuthenticationRedirects.php
+++ b/src/auth/src/AuthenticationRedirects.php
@@ -6,6 +6,7 @@
use Closure;
use Hypervel\Http\Request;
+use Hypervel\Routing\Exceptions\UrlGenerationException;
use Hypervel\Support\Attributes\BootOnly;
use Hypervel\Support\Facades\Route;
@@ -63,7 +64,7 @@ public static function guestDestination(Request $request): ?string
return (static::$guestDestinationCallback)($request);
}
- return Route::has('login') ? route('login') : null;
+ return static::namedDestination('login');
}
/**
@@ -76,8 +77,8 @@ public static function userDestination(Request $request): string
}
foreach (['dashboard', 'home'] as $uri) {
- if (Route::has($uri)) {
- return route($uri);
+ if (($destination = static::namedDestination($uri)) !== null) {
+ return $destination;
}
}
@@ -92,6 +93,22 @@ public static function userDestination(Request $request): string
return '/';
}
+ /**
+ * Resolve a conventional route when its required parameters are available.
+ */
+ protected static function namedDestination(string $name): ?string
+ {
+ if (! Route::has($name)) {
+ return null;
+ }
+
+ try {
+ return route($name);
+ } catch (UrlGenerationException) {
+ return null;
+ }
+ }
+
/**
* Flush all static state.
*/
diff --git a/src/contracts/src/Routing/UrlGenerator.php b/src/contracts/src/Routing/UrlGenerator.php
index fafa010c8..80dcae8e7 100644
--- a/src/contracts/src/Routing/UrlGenerator.php
+++ b/src/contracts/src/Routing/UrlGenerator.php
@@ -7,6 +7,7 @@
use BackedEnum;
use DateInterval;
use DateTimeInterface;
+use Hypervel\Routing\Exceptions\UrlGenerationException;
use Hypervel\Support\Attributes\BootOnly;
use InvalidArgumentException;
@@ -41,6 +42,7 @@ public function asset(string $path, ?bool $secure = null): string;
* Get the URL to a named route.
*
* @throws InvalidArgumentException
+ * @throws UrlGenerationException
*/
public function route(BackedEnum|string $name, mixed $parameters = [], bool $absolute = true): string;
diff --git a/src/docs/authentication.md b/src/docs/authentication.md
index 929788d41..fbaa8879d 100644
--- a/src/docs/authentication.md
+++ b/src/docs/authentication.md
@@ -427,7 +427,7 @@ Route::get('/flights', function () {
#### Redirecting Unauthenticated Users
-When the `auth` middleware detects an unauthenticated user, it redirects browser requests to the `login` [named route](/docs/{{version}}/routing#named-routes) if it exists. Without a login destination, the response is HTTP 401. Requests your exception handler renders as JSON receive a JSON 401. You may modify this behavior using the `redirectGuestsTo` method within your application's `bootstrap/app.php` file:
+When the `auth` middleware detects an unauthenticated user, it redirects browser requests to the `login` [named route](/docs/{{version}}/routing#named-routes) if it exists. If the login route is missing or needs a parameter without a URL default, the response is HTTP 401. Requests your exception handler renders as JSON receive a JSON 401. You may modify this behavior using the `redirectGuestsTo` method within your application's `bootstrap/app.php` file:
```php
use Hypervel\Foundation\Configuration\Middleware;
@@ -468,7 +468,7 @@ Under the hood, the `auth` middleware throws a `Hypervel\Auth\AuthenticationExce
#### Redirecting Authenticated Users
-When the `guest` middleware detects an authenticated user, it tries the `dashboard` and `home` named routes, then the corresponding registered GET paths, then `/`. Fortify and standalone Passkeys also use this signed-in destination after login when there is no intended URL or flow-specific redirect. You may modify this behavior using the `redirectUsersTo` method within your application's `bootstrap/app.php` file:
+When the `guest` middleware detects an authenticated user, it tries the `dashboard` and `home` named routes, then the corresponding registered GET paths, then `/`. Named routes that need a missing parameter are skipped. Fortify and standalone Passkeys also use this signed-in destination after login when there is no intended URL or flow-specific redirect. You may modify this behavior using the `redirectUsersTo` method within your application's `bootstrap/app.php` file:
```php
use Hypervel\Foundation\Configuration\Middleware;
diff --git a/src/foundation/src/helpers.php b/src/foundation/src/helpers.php
index 0bd96d0f5..abbcd321c 100644
--- a/src/foundation/src/helpers.php
+++ b/src/foundation/src/helpers.php
@@ -38,6 +38,7 @@
use Hypervel\Log\Context\Repository as ContextRepository;
use Hypervel\Log\LogManager;
use Hypervel\Queue\CallQueuedClosure;
+use Hypervel\Routing\Exceptions\UrlGenerationException;
use Hypervel\Routing\Redirector;
use Hypervel\Routing\Router;
use Hypervel\Session\SessionManager;
@@ -874,6 +875,7 @@ function response(mixed $content = null, int $status = 200, array $headers = [])
* Generate the URL to a named route.
*
* @throws InvalidArgumentException
+ * @throws UrlGenerationException
*/
function route(BackedEnum|string $name, mixed $parameters = [], bool $absolute = true): string
{
diff --git a/src/routing/src/UrlGenerator.php b/src/routing/src/UrlGenerator.php
index a82bc728a..1fb0b37b4 100755
--- a/src/routing/src/UrlGenerator.php
+++ b/src/routing/src/UrlGenerator.php
@@ -503,6 +503,7 @@ public function signatureHasNotExpired(Request $request): bool
*
* @throws RouteNotFoundException
* @throws InvalidArgumentException
+ * @throws UrlGenerationException
*/
public function route(BackedEnum|string $name, mixed $parameters = [], bool $absolute = true): string
{
diff --git a/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php b/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
index d499e2a85..7ec97c217 100644
--- a/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
+++ b/tests/Auth/RedirectIfAuthenticatedMiddlewareTest.php
@@ -17,6 +17,8 @@
use Hypervel\Contracts\Auth\Guard;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;
+use Hypervel\Support\Facades\Route;
+use Hypervel\Support\Facades\URL;
use Hypervel\Testbench\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
@@ -95,8 +97,25 @@ public function testDefaultRedirectFallsBackToSlash(): void
$middleware = new RedirectIfAuthenticated;
$result = $middleware->handle($request, fn () => new Response('should not reach'));
- // No 'dashboard' or 'home' routes registered, so it falls back to '/'
$this->assertSame(302, $result->getStatusCode());
+ $this->assertSame(url('/'), $result->getTargetUrl());
+ }
+
+ public function testSignedInDestinationPrefersRoutableNamesThenRegisteredGetPaths(): void
+ {
+ $request = Request::create('/login');
+ Route::get('home', fn () => 'home');
+ Route::get('dashboard', fn () => 'dashboard');
+ Route::name('dashboard')->get('{tenant}/panel', fn () => 'panel');
+ Route::compileAndWarm();
+
+ $this->assertSame('/dashboard', AuthenticationRedirects::userDestination($request));
+
+ Route::name('home')->get('welcome', fn () => 'welcome');
+ $this->assertSame(url('/welcome'), AuthenticationRedirects::userDestination($request));
+
+ URL::defaults(['tenant' => 'acme']);
+ $this->assertSame(url('/acme/panel'), AuthenticationRedirects::userDestination($request));
}
public function testMultipleGuardsRedirectsIfAnyAuthenticated(): void
diff --git a/tests/Integration/Auth/AuthenticationTest.php b/tests/Integration/Auth/AuthenticationTest.php
index 94bf808c3..748bf2576 100644
--- a/tests/Integration/Auth/AuthenticationTest.php
+++ b/tests/Integration/Auth/AuthenticationTest.php
@@ -29,6 +29,7 @@
use Hypervel\Support\Facades\Exceptions;
use Hypervel\Support\Facades\Route;
use Hypervel\Support\Facades\Schema;
+use Hypervel\Support\Facades\URL;
use Hypervel\Support\Sleep;
use Hypervel\Support\Str;
use Hypervel\Support\Testing\Fakes\EventFake;
@@ -111,8 +112,11 @@ public function testGuestGetsUnauthorizedUntilALoginRouteIsAvailable(): void
Route::get('/protected', fn () => 'private')->middleware('auth');
$this->get('/protected')->assertUnauthorized();
- Route::name('login')->get('/sign-in', fn () => 'login');
- $this->get('/protected')->assertRedirect('/sign-in');
+ Route::name('login')->get('/{tenant}/sign-in', fn () => 'login');
+ $this->get('/protected')->assertUnauthorized();
+
+ URL::defaults(['tenant' => 'acme']);
+ $this->get('/protected')->assertRedirect('/acme/sign-in');
}
public function testApiJsonPolicyRunsBeforeTheSharedLoginCallback(): void
diff --git a/tests/Testbench/Integrations/SlimSkeletonApplicationTest.php b/tests/Testbench/Integrations/SlimSkeletonApplicationTest.php
index 42e773f4e..7ee862b13 100644
--- a/tests/Testbench/Integrations/SlimSkeletonApplicationTest.php
+++ b/tests/Testbench/Integrations/SlimSkeletonApplicationTest.php
@@ -4,13 +4,13 @@
namespace Hypervel\Tests\Testbench\Integrations;
+use Hypervel\Auth\AuthenticationException;
use Hypervel\Routing\Router;
use Hypervel\Testbench\Attributes\DefineRoute;
use Hypervel\Testbench\Attributes\WithConfig;
use Hypervel\Testbench\Concerns\WithWorkbench;
use Hypervel\Tests\Testbench\TestCase;
use PHPUnit\Framework\Attributes\Test;
-use Symfony\Component\Routing\Exception\RouteNotFoundException;
#[WithConfig('app.key', 'AckfSECXIvnK5r28GVIWUAxmbBSjTsmF')]
class SlimSkeletonApplicationTest extends TestCase
@@ -27,8 +27,8 @@ public function itCanAccessWelcomePageUsingRouteName(): void
#[Test]
public function itThrowsExceptionWhenTryingToAccessAuthenticatedRoutesAsGuestWithoutLoginRouteName(): void
{
- $this->expectException(RouteNotFoundException::class);
- $this->expectExceptionMessageIs('Route [login] not defined.');
+ $this->expectException(AuthenticationException::class);
+ $this->expectExceptionMessageIs('Unauthenticated.');
$this->withoutExceptionHandling()
->get(route('dashboard'));
From bf8d99f946f105eb29a0e3ca05cfa0dc56b98fac Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Mon, 30 Nov 2026 12:44:16 +0000
Subject: [PATCH 6/7] Preserve repeated query keys in verification redirects
Replace only the verified query field through the PSR-7 URI API. Other occurrences of the same key can carry distinct values and must retain their order along with the destination fragment.
---
src/fortify/composer.json | 1 +
src/fortify/src/Http/Responses/VerifyEmailResponse.php | 10 ++++++----
tests/Fortify/VerifyEmailControllerTest.php | 4 ++--
3 files changed, 9 insertions(+), 6 deletions(-)
diff --git a/src/fortify/composer.json b/src/fortify/composer.json
index c31b22717..5624f0cc1 100644
--- a/src/fortify/composer.json
+++ b/src/fortify/composer.json
@@ -26,6 +26,7 @@
"require": {
"php": "^8.4",
"chillerlan/php-qrcode": "^6.0",
+ "guzzlehttp/psr7": "^3.1",
"hypervel/attributes": "^0.4",
"hypervel/auth": "^0.4",
"hypervel/collections": "^0.4",
diff --git a/src/fortify/src/Http/Responses/VerifyEmailResponse.php b/src/fortify/src/Http/Responses/VerifyEmailResponse.php
index bfe0182fe..598d21599 100644
--- a/src/fortify/src/Http/Responses/VerifyEmailResponse.php
+++ b/src/fortify/src/Http/Responses/VerifyEmailResponse.php
@@ -4,11 +4,11 @@
namespace Hypervel\Fortify\Http\Responses;
+use GuzzleHttp\Psr7\Uri;
use Hypervel\Fortify\Contracts\VerifyEmailResponse as VerifyEmailResponseContract;
use Hypervel\Fortify\Fortify;
use Hypervel\Http\JsonResponse;
use Hypervel\Http\Request;
-use Hypervel\Support\Uri;
use Symfony\Component\HttpFoundation\Response;
class VerifyEmailResponse implements VerifyEmailResponseContract
@@ -19,8 +19,10 @@ public function toResponse(Request $request): Response
return new JsonResponse('', 204);
}
- return redirect()->intended(static fn (): string => (string) Uri::of(
- Fortify::redirects('email-verification', request: $request)
- )->withQuery(['verified' => '1']));
+ return redirect()->intended(static fn (): string => (string) Uri::withQueryValue(
+ new Uri(Fortify::redirects('email-verification', request: $request)),
+ 'verified',
+ '1',
+ ));
}
}
diff --git a/tests/Fortify/VerifyEmailControllerTest.php b/tests/Fortify/VerifyEmailControllerTest.php
index b418ff1e1..43e9890c2 100644
--- a/tests/Fortify/VerifyEmailControllerTest.php
+++ b/tests/Fortify/VerifyEmailControllerTest.php
@@ -81,8 +81,8 @@ public function testRedirectedIfEmailIsAlreadyVerified(): void
$response->assertStatus(302);
Event::assertNotDispatched(Verified::class);
- config()->set('fortify.redirects.email-verification', '/account?tab=profile#email');
- $this->actingAs($user)->get($url)->assertRedirect('/account?tab=profile&verified=1#email');
+ config()->set('fortify.redirects.email-verification', '/account?tag=one&tag=two&verified=0#email');
+ $this->actingAs($user)->get($url)->assertRedirect('/account?tag=one&tag=two&verified=1#email');
}
public function testEmailIsNotVerifiedIfIdDoesNotMatch(): void
From 7665b6039ba403de30590fd93260070032658610 Mon Sep 17 00:00:00 2001
From: Raj Siva-Rajah <5361908+binaryfire@users.noreply.github.com>
Date: Mon, 30 Nov 2026 12:44:16 +0000
Subject: [PATCH 7/7] Forward lazy intended destinations through the response
factory
Accept the same closure or string through the response helper and facade as through the redirector. Pass the closure on unchanged so a saved intended URL can be used without evaluating the fallback.
---
src/contracts/src/Routing/ResponseFactory.php | 4 +++-
src/routing/src/ResponseFactory.php | 4 +++-
src/support/src/Facades/Response.php | 2 +-
tests/Routing/RoutingResponseFactoryTest.php | 16 ++++++++++++++--
4 files changed, 21 insertions(+), 5 deletions(-)
diff --git a/src/contracts/src/Routing/ResponseFactory.php b/src/contracts/src/Routing/ResponseFactory.php
index 090252b87..b8647ecc7 100644
--- a/src/contracts/src/Routing/ResponseFactory.php
+++ b/src/contracts/src/Routing/ResponseFactory.php
@@ -102,6 +102,8 @@ public function redirectGuest(string $path, int $status = 302, array $headers =
/**
* Create a new redirect response to the previously intended location.
+ *
+ * @param (Closure(): string)|string $default
*/
- public function redirectToIntended(string $default = '/', int $status = 302, array $headers = [], ?bool $secure = null): RedirectResponse;
+ public function redirectToIntended(Closure|string $default = '/', int $status = 302, array $headers = [], ?bool $secure = null): RedirectResponse;
}
diff --git a/src/routing/src/ResponseFactory.php b/src/routing/src/ResponseFactory.php
index 066bb12f9..29454fdca 100644
--- a/src/routing/src/ResponseFactory.php
+++ b/src/routing/src/ResponseFactory.php
@@ -291,8 +291,10 @@ public function redirectGuest(string $path, int $status = 302, array $headers =
/**
* Create a new redirect response to the previously intended location.
+ *
+ * @param (Closure(): string)|string $default
*/
- public function redirectToIntended(string $default = '/', int $status = 302, array $headers = [], ?bool $secure = null): RedirectResponse
+ public function redirectToIntended(Closure|string $default = '/', int $status = 302, array $headers = [], ?bool $secure = null): RedirectResponse
{
return $this->redirector->intended($default, $status, $headers, $secure);
}
diff --git a/src/support/src/Facades/Response.php b/src/support/src/Facades/Response.php
index 26560446f..d1cf4a30a 100644
--- a/src/support/src/Facades/Response.php
+++ b/src/support/src/Facades/Response.php
@@ -23,7 +23,7 @@
* @method static \Hypervel\Http\RedirectResponse redirectGuest(string $path, int $status = 302, array $headers = [], bool|null $secure = null)
* @method static \Hypervel\Http\RedirectResponse redirectTo(string $path, int $status = 302, array $headers = [], bool|null $secure = null)
* @method static \Hypervel\Http\RedirectResponse redirectToAction(array|string $action, mixed $parameters = [], int $status = 302, array $headers = [])
- * @method static \Hypervel\Http\RedirectResponse redirectToIntended(string $default = '/', int $status = 302, array $headers = [], bool|null $secure = null)
+ * @method static \Hypervel\Http\RedirectResponse redirectToIntended(\Closure|string $default = '/', int $status = 302, array $headers = [], bool|null $secure = null)
* @method static \Hypervel\Http\RedirectResponse redirectToRoute(\BackedEnum|string $route, mixed $parameters = [], int $status = 302, array $headers = [])
* @method static \Symfony\Component\HttpFoundation\StreamedResponse stream(callable|null $callback = null, int $status = 200, array $headers = [])
* @method static \Symfony\Component\HttpFoundation\StreamedResponse streamDownload(callable $callback, string|null $name = null, array $headers = [], string $disposition = 'attachment')
diff --git a/tests/Routing/RoutingResponseFactoryTest.php b/tests/Routing/RoutingResponseFactoryTest.php
index 88ed99f1f..a8b6e4a1b 100644
--- a/tests/Routing/RoutingResponseFactoryTest.php
+++ b/tests/Routing/RoutingResponseFactoryTest.php
@@ -9,12 +9,14 @@
use Hypervel\Contracts\Debug\ExceptionHandler;
use Hypervel\Contracts\View\Factory as ViewFactory;
use Hypervel\Http\IterableStreamedResponse;
+use Hypervel\Http\RedirectResponse;
use Hypervel\Http\StreamedEvent;
use Hypervel\Routing\Redirector;
use Hypervel\Routing\ResponseFactory;
use Hypervel\Tests\TestCase;
use JMac\Testing\Double;
use JMac\Testing\Integrations\PHPUnit\VerifiesDoubles;
+use JMac\Testing\Matching\Argument;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
use RuntimeException;
@@ -29,6 +31,16 @@ class RoutingResponseFactoryTest extends TestCase
// PHPUnit's output capture runs outside the test coroutine.
protected bool $runTestsInCoroutine = false;
+ public function testRedirectToIntendedForwardsTheLazyFallback(): void
+ {
+ $fallback = static fn (): string => '/account';
+ $response = new RedirectResponse('/saved');
+ $redirector = Double::for(Redirector::class)->strict();
+ $redirector->expects('intended')->with(Argument::same($fallback), 302, [], null)->returns($response);
+
+ $this->assertSame($response, $this->factory($redirector)->redirectToIntended($fallback));
+ }
+
public function testStreamDownloadFilenameWithoutAsciiEquivalent(): void
{
$response = $this->factory()->streamDownload(fn (): null => null, '請求書');
@@ -225,11 +237,11 @@ public static function streamingFactoryMethods(): array
];
}
- private function factory(): ResponseFactory
+ private function factory(?Redirector $redirector = null): ResponseFactory
{
return new ResponseFactory(
Double::for(ViewFactory::class)->strict(),
- Double::for(Redirector::class)->strict(),
+ $redirector ?? Double::for(Redirector::class)->strict(),
);
}
}