Auth Filters
Protect routes or groups of routes so they only execute for authenticated users. Lightpack provides two built-in filters: AuthFilter for protected routes and GuestFilter for guest-only routes.
AuthFilter
The AuthFilter protects routes by ensuring users are authenticated. It supports both web (session-based) and API (token-based) authentication.
Web Authentication
For session-based routes, use auth:web:
route()->group(['filters' => 'auth:web'], function() {
// protected routes list here
});
How it works:
- Checks if user is logged in via session
- If not logged in:
- Stores the current URL as "intended" (for GET requests)
- Attempts auto-login via remember-me cookie (
recall()) - If recall fails, redirects to login page
- If logged in: Allows the request to proceed
API Authentication
For API routes, use auth:api:
route()->group(['filters' => 'auth:api'], function() {
// protected routes list here
});
How it works:
- Extracts Bearer token from
Authorizationheader - Validates token via
auth()->viaToken() - If invalid: Returns
401 UnauthorizedJSON response - If valid: Allows the request to proceed
Configuring Redirect Routes
The AuthFilter uses named routes from your config/auth.php to determine where to redirect unauthenticated users:
'routes' => [
'login' => 'login', // Redirect here when not authenticated
],
Make sure you have a corresponding named route:
route()->get('/login', AuthController::class, 'showLogin')->name('login');
See Configuration for more details.
GuestFilter
The GuestFilter ensures only unauthenticated users can access certain routes. This is useful for login, registration, and password reset pages.
route()->group(['filters' => 'guest'], function() {
// routes only for guests (not logged-in users)
});
How it works:
- Checks if user is logged in
- If logged in: Redirects to the home page
- If not logged in: Allows the request to proceed
Configuring Authenticated Route
The GuestFilter uses the routes.authenticated config to determine where to redirect authenticated users:
'routes' => [
'authenticated' => 'dashboard', // Redirect here when already authenticated
],
Make sure you have a corresponding named route:
route()->get('/dashboard', DashboardController::class, 'index')->name('dashboard');
Per-Route Filters
You can apply filters to individual routes:
$router->get('/admin', [AdminController::class, 'index'])
->filter('auth:web');
$router->get('/login', [AuthController::class, 'showLogin'])
->filter('guest');
Remember Me Behavior
The AuthFilter automatically attempts to log in users via their remember-me cookie. This means:
- User visits a protected route
- No active session found
- Valid remember-me cookie exists
- User is automatically logged in
- Request proceeds normally
This provides a seamless experience for users who checked "Remember me" during login.