Skip to content

Commit 57788d6

Browse files
authored
Merge pull request #796 from hypervel/feature/shared-auth-redirects
Share authentication redirects across Auth, Fortify, and Passkeys
2 parents dea182d + 7665b60 commit 57788d6

53 files changed

Lines changed: 307 additions & 187 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎src/auth/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Documentation: https://hypervel.org/docs/authentication
77

88
## Differences From Laravel
99

10+
- 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.
1011
- The shipped database password broker schedules expired reset token cleanup. Configure the schedule on the broker when porting a manual `auth:clear-resets` entry.
1112
- `Auth::routes()` is intentionally omitted because Hypervel does not integrate `laravel/ui`. Register authentication routes explicitly or use Fortify.
1213
- 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.

‎src/auth/composer.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@
4040
"hypervel/macroable": "^0.4",
4141
"hypervel/notifications": "^0.4",
4242
"hypervel/queue": "^0.4",
43+
"hypervel/routing": "^0.4",
4344
"hypervel/session": "^0.4",
4445
"hypervel/support": "^0.4",
4546
"nesbot/carbon": "^3.13.1",

‎src/auth/src/AuthManager.php‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -298,11 +298,9 @@ public function clearUserCache(mixed $identifier, UnitEnum|string|null $guard =
298298
}
299299

300300
/**
301-
* Configure where guests are redirected by the "auth" middleware.
301+
* Set the shared login destination for the worker lifetime.
302302
*
303-
* The callback persists in authentication middleware and exception
304-
* static properties for the worker lifetime and affects every
305-
* subsequent unauthenticated or session-mismatch request.
303+
* Pass null to disable guest redirects.
306304
*
307305
* @return $this
308306
*/
@@ -315,11 +313,7 @@ public function redirectGuestsTo(callable|string|null $redirect): static
315313
}
316314

317315
/**
318-
* Configure where users are redirected by the "guest" middleware.
319-
*
320-
* The callback persists in the guest middleware static property for the
321-
* worker lifetime and affects every subsequent already-authenticated
322-
* guest-route request.
316+
* Set the shared signed-in destination for the worker lifetime.
323317
*
324318
* @return $this
325319
*/
@@ -332,11 +326,7 @@ public function redirectUsersTo(callable|string $redirect): static
332326
}
333327

334328
/**
335-
* Configure where users are redirected by the authentication and guest middleware.
336-
*
337-
* The callbacks persist in authentication middleware and exception
338-
* static properties for the worker lifetime and affect every
339-
* subsequent matching request.
329+
* Configure the shared login and signed-in destinations for the worker lifetime.
340330
*
341331
* @return $this
342332
*/

‎src/auth/src/AuthenticationException.php‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,8 @@ public function redirectTo(Request $request): ?string
5959
return call_user_func(static::$redirectToCallback, $request);
6060
}
6161

62-
return null;
62+
// The handler resolves the shared login destination only after checking for a JSON response.
63+
return AuthenticationRedirects::guestDestination($request);
6364
}
6465

6566
/**

‎src/auth/src/AuthenticationRedirects.php‎

Lines changed: 84 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -4,71 +4,117 @@
44

55
namespace Hypervel\Auth;
66

7-
use Hypervel\Auth\Middleware\Authenticate;
8-
use Hypervel\Auth\Middleware\RedirectIfAuthenticated;
9-
use Hypervel\Session\Middleware\AuthenticateSession;
7+
use Closure;
8+
use Hypervel\Http\Request;
9+
use Hypervel\Routing\Exceptions\UrlGenerationException;
1010
use Hypervel\Support\Attributes\BootOnly;
11+
use Hypervel\Support\Facades\Route;
1112

12-
/**
13-
* Single source of truth for boot-time auth redirect wiring.
14-
*
15-
* Configures the worker-lifetime redirect callbacks on the auth/guest
16-
* middleware and the authentication exception; it does not resolve or issue
17-
* redirects at runtime.
18-
*/
1913
class AuthenticationRedirects
2014
{
15+
/** @var null|Closure(Request): ?string */
16+
protected static ?Closure $guestDestinationCallback = null;
17+
18+
/** @var null|Closure(Request): string */
19+
protected static ?Closure $userDestinationCallback = null;
20+
2121
/**
22-
* Configure where guests are redirected by the "auth" middleware.
22+
* Set the shared login destination for the worker lifetime.
2323
*
24-
* The callback persists in authentication middleware and exception
25-
* static properties for the worker lifetime and affects every
26-
* subsequent unauthenticated or session-mismatch request.
24+
* Pass null to disable guest redirects.
2725
*/
2826
#[BootOnly]
2927
public static function redirectGuestsTo(callable|string|null $redirect): void
3028
{
31-
$redirect = $redirect === null
32-
? static fn () => null
33-
: $redirect;
34-
35-
self::redirectTo(guests: $redirect);
29+
static::$guestDestinationCallback = is_string($redirect) || $redirect === null
30+
? static fn () => $redirect
31+
: Closure::fromCallable($redirect);
3632
}
3733

3834
/**
39-
* Configure where users are redirected by the "guest" middleware.
40-
*
41-
* The callback persists in the guest middleware static property for the
42-
* worker lifetime and affects every subsequent already-authenticated
43-
* guest-route request.
35+
* Set the shared signed-in destination for the worker lifetime.
4436
*/
4537
#[BootOnly]
4638
public static function redirectUsersTo(callable|string $redirect): void
4739
{
48-
self::redirectTo(users: $redirect);
40+
static::$userDestinationCallback = is_string($redirect) ? static fn () => $redirect : Closure::fromCallable($redirect);
4941
}
5042

5143
/**
52-
* Configure where users are redirected by the authentication and guest middleware.
53-
*
54-
* The callbacks persist in authentication middleware and exception
55-
* static properties for the worker lifetime and affect every
56-
* subsequent matching request.
44+
* Configure the shared login and signed-in destinations for the worker lifetime.
5745
*/
5846
#[BootOnly]
5947
public static function redirectTo(callable|string|null $guests = null, callable|string|null $users = null): void
6048
{
61-
$guests = is_string($guests) ? fn () => $guests : $guests;
62-
$users = is_string($users) ? fn () => $users : $users;
49+
if ($guests !== null) {
50+
static::redirectGuestsTo($guests);
51+
}
52+
53+
if ($users !== null) {
54+
static::redirectUsersTo($users);
55+
}
56+
}
57+
58+
/**
59+
* Resolve the login destination, if the application provides one.
60+
*/
61+
public static function guestDestination(Request $request): ?string
62+
{
63+
if (static::$guestDestinationCallback !== null) {
64+
return (static::$guestDestinationCallback)($request);
65+
}
66+
67+
return static::namedDestination('login');
68+
}
69+
70+
/**
71+
* Resolve the signed-in destination for the current request.
72+
*/
73+
public static function userDestination(Request $request): string
74+
{
75+
if (static::$userDestinationCallback !== null) {
76+
return (static::$userDestinationCallback)($request);
77+
}
78+
79+
foreach (['dashboard', 'home'] as $uri) {
80+
if (($destination = static::namedDestination($uri)) !== null) {
81+
return $destination;
82+
}
83+
}
84+
85+
$routes = Route::getRoutes()->get('GET');
86+
87+
foreach (['dashboard', 'home'] as $uri) {
88+
if (isset($routes[$uri])) {
89+
return '/' . $uri;
90+
}
91+
}
92+
93+
return '/';
94+
}
6395

64-
if ($guests) {
65-
Authenticate::redirectUsing($guests);
66-
AuthenticateSession::redirectUsing($guests);
67-
AuthenticationException::redirectUsing($guests);
96+
/**
97+
* Resolve a conventional route when its required parameters are available.
98+
*/
99+
protected static function namedDestination(string $name): ?string
100+
{
101+
if (! Route::has($name)) {
102+
return null;
68103
}
69104

70-
if ($users) {
71-
RedirectIfAuthenticated::redirectUsing($users);
105+
try {
106+
return route($name);
107+
} catch (UrlGenerationException) {
108+
return null;
72109
}
73110
}
111+
112+
/**
113+
* Flush all static state.
114+
*/
115+
public static function flushState(): void
116+
{
117+
static::$guestDestinationCallback = null;
118+
static::$userDestinationCallback = null;
119+
}
74120
}

‎src/auth/src/Middleware/RedirectIfAuthenticated.php‎

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
namespace Hypervel\Auth\Middleware;
66

77
use Closure;
8+
use Hypervel\Auth\AuthenticationRedirects;
89
use Hypervel\Http\Request;
910
use Hypervel\Support\Attributes\BootOnly;
1011
use Hypervel\Support\Facades\Auth;
11-
use Hypervel\Support\Facades\Route;
1212
use Symfony\Component\HttpFoundation\Response;
1313

1414
class RedirectIfAuthenticated
@@ -57,30 +57,10 @@ protected function redirectTo(Request $request): ?string
5757
{
5858
return static::$redirectToCallback
5959
? call_user_func(static::$redirectToCallback, $request)
60-
: $this->defaultRedirectUri();
60+
: AuthenticationRedirects::userDestination($request);
6161
}
6262

63-
/**
64-
* Get the default URI the user should be redirected to when they are authenticated.
65-
*/
66-
protected function defaultRedirectUri(): string
67-
{
68-
foreach (['dashboard', 'home'] as $uri) {
69-
if (Route::has($uri)) {
70-
return route($uri);
71-
}
72-
}
73-
74-
$routes = Route::getRoutes()->get('GET');
75-
76-
foreach (['dashboard', 'home'] as $uri) {
77-
if (isset($routes[$uri])) {
78-
return '/' . $uri;
79-
}
80-
}
81-
82-
return '/';
83-
}
63+
// AuthenticationRedirects owns the fallback shared with Fortify and Passkeys in place of defaultRedirectUri().
8464

8565
/**
8666
* Specify the callback that should be used to generate the redirect path.

‎src/contracts/src/Routing/ResponseFactory.php‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ public function redirectGuest(string $path, int $status = 302, array $headers =
102102

103103
/**
104104
* Create a new redirect response to the previously intended location.
105+
*
106+
* @param (Closure(): string)|string $default
105107
*/
106-
public function redirectToIntended(string $default = '/', int $status = 302, array $headers = [], ?bool $secure = null): RedirectResponse;
108+
public function redirectToIntended(Closure|string $default = '/', int $status = 302, array $headers = [], ?bool $secure = null): RedirectResponse;
107109
}

‎src/contracts/src/Routing/UrlGenerator.php‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use BackedEnum;
88
use DateInterval;
99
use DateTimeInterface;
10+
use Hypervel\Routing\Exceptions\UrlGenerationException;
1011
use Hypervel\Support\Attributes\BootOnly;
1112
use InvalidArgumentException;
1213

@@ -41,6 +42,7 @@ public function asset(string $path, ?bool $secure = null): string;
4142
* Get the URL to a named route.
4243
*
4344
* @throws InvalidArgumentException
45+
* @throws UrlGenerationException
4446
*/
4547
public function route(BackedEnum|string $name, mixed $parameters = [], bool $absolute = true): string;
4648

‎src/docs/authentication.md‎

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ Route::get('/flights', function () {
427427
<a name="redirecting-unauthenticated-users"></a>
428428
#### Redirecting Unauthenticated Users
429429

430-
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:
430+
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:
431431

432432
```php
433433
use Hypervel\Foundation\Configuration\Middleware;
@@ -463,12 +463,12 @@ Redirect paths may be strings or request-aware callbacks. Passing `null` through
463463

464464
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.
465465

466-
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.
466+
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.
467467

468468
<a name="redirecting-authenticated-users"></a>
469469
#### Redirecting Authenticated Users
470470

471-
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:
471+
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:
472472

473473
```php
474474
use Hypervel\Foundation\Configuration\Middleware;
@@ -497,6 +497,25 @@ public function boot(): void
497497
}
498498
```
499499

500+
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)`.
501+
502+
To redirect users from a package's guest routes to its own dashboard, attach a middleware subclass to those routes:
503+
504+
```php
505+
use Hypervel\Auth\Middleware\RedirectIfAuthenticated;
506+
use Hypervel\Http\Request;
507+
508+
class RedirectPackageUsers extends RedirectIfAuthenticated
509+
{
510+
protected function redirectTo(Request $request): ?string
511+
{
512+
return route('admin.dashboard');
513+
}
514+
}
515+
```
516+
517+
If only some routes handled by this subclass need a custom destination, return `parent::redirectTo($request)` for the others.
518+
500519
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.
501520

502521
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`:

‎src/docs/fortify.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -168,7 +168,7 @@ public function register(): void
168168
<a name="redirects"></a>
169169
### Redirects
170170

171-
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.
171+
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.
172172

173173
Redirects may also be computed per request:
174174

@@ -186,9 +186,9 @@ public function boot(): void
186186

187187
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.
188188

189-
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`.
189+
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.
190190

191-
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.
191+
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.
192192

193193
<a name="multi-guard-applications"></a>
194194
### Multi-Guard Applications
@@ -914,7 +914,6 @@ Standalone routes use the following configuration options:
914914
| `middleware` | The required middleware applied to every standalone route. |
915915
| `management_middleware` | The required additional middleware applied when creating or deleting passkeys. |
916916
| `throttle` | The throttle middleware applied to passkey login, confirmation, and registration endpoints. Omission uses `throttle:6,1`; null disables throttling. |
917-
| `redirect` | The successful login destination used when no intended URL exists. Omission uses `/`. |
918917

919918
Call `Passkeys::ignoreRoutes()` during boot before registering your own endpoints:
920919

0 commit comments

Comments
 (0)