Authentication Service
The Spark Authentication Service provides a robust, driver-based authentication system with session management, remember me functionality, route protection, and user caching.
Configuration
Register and configure the Auth service in your AppServiceProvider
:
use Spark\Http\Auth;
use App\Models\User;
$container->singleton(Auth::class, function(Container $container) {
return new Auth(
$container->get(Session::class),
User::class,
[
'session_key' => 'user_id',
'cache_enabled' => true,
'cache_name' => 'auth_cache',
'cache_expire' => '30 minutes',
'guest_route' => 'login',
'logged_in_route' => 'dashboard',
'cookie_enabled' => true,
'cookie_name' => 'logged_user_token',
'cookie_expire' => '30 days',
'driver' => null
]
);
});
Configuration Options
Option | Type | Default | Description |
---|---|---|---|
session_key | string | 'admin_user_id' | Session key for storing authenticated user ID |
cache_enabled | bool | false | Enable caching of user objects |
cache_name | string | 'logged_user' | Cache storage identifier |
cache_expire | string | '10 minutes' | Cache expiration time (strtotime compatible) |
guest_route | string | 'admin.auth.login' | Route name for guest redirects |
logged_in_route | string | 'admin.dashboard' | Route name for authenticated redirects |
cookie_enabled | bool | false | Enable remember me functionality |
cookie_name | string|null | null | Remember me cookie name (null disables remember me) |
cookie_expire | string | '6 months' | Remember me cookie expiration |
driver | AuthDriverContract|null | null | Custom authentication driver |
Core Methods
getUser(): false|Model
Retrieves the currently authenticated user.
- Returns user model if authenticated
- Returns false if no user is authenticated
- Handles session, cookie, and cache automatically
$user = $auth->getUser();
if ($user !== false) {
echo "Welcome, {$user->name}";
}
user(?string $key = null, mixed $default = null): mixed
Retrieves user or specific user attribute.
// Get entire user model
$user = $auth->user();
// Get specific attribute
$email = $auth->user('email');
// With default value
$phone = $auth->user('phone', 'No phone set');
login(Model $user, bool $remember = false): void
Authenticates a user.
- Sets session data
- Optionally sets remember me cookie
- Caches user if enabled
// Basic login
$auth->login($user);
// With remember me
$auth->login($user, true);
logout(): void
Terminates the user session.
- Clears session data
- Removes remember me cookie if set
- Clears user cache if enabled
$auth->logout();
isGuest(): bool
Checks if current user is not authenticated.
if ($auth->isGuest()) {
return redirect('login');
}
refresh(): void
Refreshes user data from storage.
- Clears cache
- Reloads user from database
// After updating user profile
$auth->refresh();
Authentication Drivers
Implement custom authentication logic by creating a driver:
use Spark\Contracts\Http\AuthDriverContract;
class CustomAuthDriver implements AuthDriverContract
{
public function getUser(): false|Model
{
// Custom logic to retrieve user
}
public function login(Model $user, bool $remember = false): void
{
// Custom login handling
}
public function logout(): void
{
// Custom logout handling
}
}
// Configure the driver
$auth->configure(['driver' => new CustomAuthDriver()]);
Remember Me Functionality
Secure remember me implementation using encrypted cookies:
// Configuration
'cookie_enabled' => true,
'cookie_name' => 'auth_token',
'cookie_expire' => '30 days',
// During login
$auth->login($user, true); // Second parameter enables remember me
// Automatic authentication flow:
// 1. Checks session for user ID
// 2. If no session, checks 'auth_token' cookie
// 3. Validates cookie, logs in user if valid
// 4. Sets new session
User Caching
Improve performance by caching authenticated users:
// Enable caching
'cache_enabled' => true,
'cache_name' => 'auth_users',
'cache_expire' => '1 hour',
// Caching behavior:
// - User cached on first access after login
// - Cache cleared on logout or refresh
// - Automatically used by getUser()
Route Protection
Example auth middleware implementation:
class AuthMiddleware
{
public function handle($request, $next)
{
if (auth()->isGuest()) {
return redirect(auth()->getGuestRoute());
}
return $next($request);
}
}
// Register middleware
Route::group(['middleware' => 'auth'], function() {
// Protected routes
});
Full Authentication Flow Example
// Login Controller
public function authenticate(Request $request, Auth $auth, Hash $hash)
{
$credentials = $request->validate([
'email' => 'required|email',
'password' => 'required'
]);
$user = User::where('email', $credentials['email'])->first();
if ($user && $hash->validatePassword($credentials['password'], $user->password)) {
$auth->login($user, $request->has('remember'));
return redirect($auth->getLoggedInRoute());
}
return back()->with('error', 'Invalid credentials');
}
// Dashboard Controller
public function dashboard(Auth $auth)
{
return view('dashboard', [
'user' => $auth->user()
]);
}
// Logout Controller
public function logout(Auth $auth)
{
$auth->logout();
return redirect('/');
}
Security Best Practices:
- Always hash passwords using the Hash service
- Regenerate session ID after login
- Use HTTPS for all authentication requests
- Implement CSRF protection for login forms
- Set secure and HttpOnly flags for cookies
Helper Functions:
auth()
- Returns Auth service instanceuser()
- Returns current user or attributeis_guest()
- Checks if user is not authenticated