Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/auth/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions src/auth/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
18 changes: 4 additions & 14 deletions src/auth/src/AuthManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand All @@ -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
*/
Expand All @@ -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
*/
Expand Down
3 changes: 2 additions & 1 deletion src/auth/src/AuthenticationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

/**
Expand Down
122 changes: 84 additions & 38 deletions src/auth/src/AuthenticationRedirects.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,71 +4,117 @@

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\Routing\Exceptions\UrlGenerationException;
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 static::namedDestination('login');
}

/**
* Resolve the signed-in destination for the current request.
*/
public static function userDestination(Request $request): string
{
if (static::$userDestinationCallback !== null) {
return (static::$userDestinationCallback)($request);
}

foreach (['dashboard', 'home'] as $uri) {
if (($destination = static::namedDestination($uri)) !== null) {
return $destination;
}
}

$routes = Route::getRoutes()->get('GET');

foreach (['dashboard', 'home'] as $uri) {
if (isset($routes[$uri])) {
return '/' . $uri;
Comment on lines +79 to +89

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Shared defaults lack tests

The default destinations now shared by Fortify and standalone Passkeys lack direct tests. Fortify's test base always sets /home, the Passkeys redirect test sets /account, and the guest middleware's fallback test checks only the status. A wrong destination could therefore go unnoticed.

Add destination assertions for named dashboard/home routes, unnamed GET paths, and /, including cached routes. Also check a Fortify response and a standalone Passkeys response without a shared override.

Fix in Claude Code Fix in Codex

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added direct destination assertions, including compiled routes and a route added after compilation. The test checks the GET fallback and named home and dashboard destinations with and without a tenant parameter default. Fortify and Passkeys already exercise their calls to the same resolver.

}
}

return '/';
}

if ($guests) {
Authenticate::redirectUsing($guests);
AuthenticateSession::redirectUsing($guests);
AuthenticationException::redirectUsing($guests);
/**
* Resolve a conventional route when its required parameters are available.
*/
protected static function namedDestination(string $name): ?string
{
if (! Route::has($name)) {
return null;
}

if ($users) {
RedirectIfAuthenticated::redirectUsing($users);
try {
return route($name);
} catch (UrlGenerationException) {
return null;
}
}

/**
* Flush all static state.
*/
public static function flushState(): void
{
static::$guestDestinationCallback = null;
static::$userDestinationCallback = null;
}
}
26 changes: 3 additions & 23 deletions src/auth/src/Middleware/RedirectIfAuthenticated.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
4 changes: 3 additions & 1 deletion src/contracts/src/Routing/ResponseFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
2 changes: 2 additions & 0 deletions src/contracts/src/Routing/UrlGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use BackedEnum;
use DateInterval;
use DateTimeInterface;
use Hypervel\Routing\Exceptions\UrlGenerationException;
use Hypervel\Support\Attributes\BootOnly;
use InvalidArgumentException;

Expand Down Expand Up @@ -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;

Expand Down
25 changes: 22 additions & 3 deletions src/docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ Route::get('/flights', function () {
<a name="redirecting-unauthenticated-users"></a>
#### 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. 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;
Expand Down Expand Up @@ -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.

<a name="redirecting-authenticated-users"></a>
#### 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 `/`. 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;
Expand Down Expand Up @@ -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`:
Expand Down
7 changes: 3 additions & 4 deletions src/docs/fortify.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public function register(): void
<a name="redirects"></a>
### 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:

Expand All @@ -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.

<a name="multi-guard-applications"></a>
### Multi-Guard Applications
Expand Down Expand Up @@ -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:

Expand Down
2 changes: 2 additions & 0 deletions src/docs/porting-from-laravel.md
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,8 @@ Replace references to Laravel's deprecated `VerifyCsrfToken` and `ValidateCsrfTo
<a name="fortify"></a>
### 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`.
Expand Down
Loading