Primordyx Framework Documentation

AuthManager
in package

Comprehensive Authentication and Authorization System for Primordyx Applications

Provides secure session management, role-based access control, and protection against common attack vectors like brute force login attempts. Built specifically for the Primordyx framework with seamless Safe class integration and flexible model support.

Core Features

  • Secure Session Management - Uses Safe class for tamper-resistant session storage
  • Failed Login Protection - Automatic account lockout after configurable failed attempts
  • Role-Based Authorization - Flexible permission system using authorization words
  • Session Timeout - Automatic logout after configurable inactivity periods
  • Flash Messaging - Built-in support for user notifications across redirects
  • Configurable URLs - Customizable redirect destinations for all authentication scenarios
  • Model Agnostic - Works with any Model implementation following Primordyx conventions
  • Attack Prevention - Protection against brute force, session fixation, and timing attacks

Security Architecture

  • Password verification using PHP's secure password_verify() function
  • Failed attempt tracking with temporary account lockouts
  • Session data stored via Safe class (tamper-resistant)
  • Automatic cleanup of expired sessions and stale return URLs
  • Authorization words normalized to lowercase for consistent checking

Quick Start Integration

// Bootstrap configuration
AuthManager::config([
    'login_url' => '/auth/login.php',
    'max_login_attempts' => 5,
    'lockout_time' => 900,
    'timeout_seconds' => 3600,
    'after_logout_url' => '/'
]);

// Set required models
AuthManager::userModel(new User());
AuthManager::userAuthWordsModel(new UserAuthWords());

Common Usage Patterns

// Page protection
AuthManager::setReturnUrl($_SERVER['REQUEST_URI']);
AuthManager::requireAuth('admin');

// Login processing
AuthManager::login($_POST['username'], $_POST['password']); // Never returns

// Authorization checks
if (AuthManager::isAuthorizedAny(['admin', 'manager'])) {
    showLeadershipDashboard();
}
Tags
see
Safe

For secure session management

see
Model

For database model requirements

since
1.0.0

Table of Contents

Properties

$afterLogoutUrl  : string
$lockedOutUrl  : string
$lockoutTime  : int
$loginUrl  : string
$maxLoginAttempts  : int
$timeoutSeconds  : int
$timeoutUrl  : string
$userAuthWordsModel  : Model|null
$userModel  : Model|null

Methods

afterLogoutUrl()  : string
Get or set the URL where users are redirected after successful logout
config()  : void
Configure multiple AuthManager settings at once for streamlined setup
forceLogin()  : void
Force user to login page with optional message - never returns
getFlash()  : array{type: string, message: string}|null
Retrieve and consume flash message from session (removes after retrieval)
getReturnUrl()  : string|null
Get and consume the stored return URL for post-login redirect
getUserAuthWords()  : array<string|int, string>
Get array of authorization words (roles/permissions) for the current user
isAuthorized()  : bool
Check if current authenticated user has a specific authorization word (role/permission)
isAuthorizedAll()  : bool
Check if user has all of the specified authorization words (AND logic)
isAuthorizedAny()  : bool
Check if user has at least one of the specified authorization words (OR logic)
isLoggedIn()  : bool
Check if user is currently authenticated with a valid, non-expired session
lockedOutUrl()  : string
Get or set the URL where locked-out users are redirected for notification
lockoutTime()  : int
Get or set the lockout duration in seconds after exceeding max login attempts
login()  : never
Attempt to authenticate user with username and password - always redirects, never returns
loginUrl()  : string
Get or set the login URL where users are redirected for authentication
logout()  : never
Log out current user, clean up all session data, and redirect - never returns
maxLoginAttempts()  : int
Get or set the maximum login attempts before triggering account lockout
requireAuth()  : void
Enforce authentication and optional authorization requirements - redirects if not met
setFlash()  : void
Set flash message for display after redirect (consumed on next request)
setReturnUrl()  : void
Set return URL for post-login redirect to user's intended destination
timeoutSeconds()  : int
Get or set the session timeout duration in seconds for inactivity-based logout
timeoutUrl()  : string
Get or set the URL where users are redirected when their session times out
user()  : Model|null
Get the current authenticated user's model instance from the database
userAuthWordsModel()  : Model|null
Get or set the user authorization words model for role-based access control
userModel()  : Model|null
Get or set the user model instance for database authentication operations
ensureModelsConfigured()  : void
Ensure required models are configured before performing database operations
handleFailedLogin()  : void
Handle failed login attempt by updating attempt counters and applying lockouts
handleSuccessfulLogin()  : void
Handle successful login by resetting failure counters and creating session

Properties

$afterLogoutUrl

protected static string $afterLogoutUrl = '/'

$lockedOutUrl

protected static string $lockedOutUrl = '/locked.php'

$lockoutTime

protected static int $lockoutTime = 900

$loginUrl

protected static string $loginUrl = '/login.php'

$maxLoginAttempts

protected static int $maxLoginAttempts = 5

$timeoutSeconds

protected static int $timeoutSeconds = 3600

$timeoutUrl

protected static string $timeoutUrl = '/timeout.php'

Methods

afterLogoutUrl()

Get or set the URL where users are redirected after successful logout

public static afterLogoutUrl([string|null $url = null ]) : string

When logout() is called, users will be redirected to this URL after their session data has been cleaned up.

Parameters
$url : string|null = null

If provided, sets the after logout URL and returns the previous value

Tags
since
1.0.0
example

Get Current Destination

$current = AuthManager::afterLogoutUrl();       // Get current URL
echo "Post-logout: $current";                   // Shows '/' (default)
example

Custom Goodbye Page

$old = AuthManager::afterLogoutUrl('/goodbye.php');
echo "Logout destination changed from: $old";
Return values
string

The current after logout URL (if getting) or previous URL (if setting)

config()

Configure multiple AuthManager settings at once for streamlined setup

public static config(array<string, mixed> $config) : void

Provides bulk configuration of all AuthManager settings through a single method call. This is the recommended approach for application bootstrap as it ensures all related settings are configured together and provides better maintainability.

Available Configuration Keys

  • login_url - Where to redirect users for authentication
  • max_login_attempts - Failed attempts before account lockout
  • lockout_time - Lockout duration in seconds
  • locked_out_url - Where to show lockout notification
  • after_logout_url - Destination after successful logout
  • timeout_url - Where to redirect on session timeout
  • timeout_seconds - Session inactivity timeout duration

Configuration Strategy

Settings are applied individually using the respective setter methods, ensuring consistency with individual configuration calls and maintaining backward compatibility.

Parameters
$config : array<string, mixed>

Configuration array with the following supported keys:

  • 'login_url' (string): URL to redirect to for login (default: '/login.php')
  • 'max_login_attempts' (int): Maximum failed attempts before lockout (default: 5)
  • 'lockout_time' (int): Lockout duration in seconds (default: 900 = 15 minutes)
  • 'locked_out_url' (string): URL to show when user is locked out (default: '/locked.php')
  • 'after_logout_url' (string): URL to redirect after logout (default: '/')
  • 'timeout_url' (string): URL to redirect on session timeout (default: '/timeout.php')
  • 'timeout_seconds' (int): Session timeout in seconds (default: 3600 = 1 hour)
Tags
throws
RuntimeException

If invalid configuration values are provided

since
1.0.0
example

Bootstrap Configuration

AuthManager::config([
    'login_url' => '/auth/login.php',           // Authentication entry point
    'max_login_attempts' => 3,                  // Lock after 3 failures
    'lockout_time' => 1800,                     // 30 minute lockout
    'locked_out_url' => '/auth/locked.php',     // Lockout notification page
    'after_logout_url' => '/goodbye.php',       // Post-logout destination
    'timeout_url' => '/auth/timeout.php',       // Session timeout page
    'timeout_seconds' => 7200                   // 2 hour session timeout
]);
example

Production Security Configuration

AuthManager::config([
    'max_login_attempts' => 5,
    'lockout_time' => 900,          // 15 minutes
    'timeout_seconds' => 3600       // 1 hour timeout
]);
// Other settings remain at defaults

forceLogin()

Force user to login page with optional message - never returns

public static forceLogin([string|null $message = null ]) : void

Immediately redirects user to the configured login URL with an optional flash message. This method is typically used when authentication is required but not present, or when specific access requirements are not met.

Redirect Process

  • Sets flash message (if provided) for user feedback
  • Redirects to configured login URL
  • Calls exit to stop script execution
  • Does NOT automatically set return URL (caller responsibility)

Usage Patterns

  • Call setReturnUrl() first if you want user returned to current page
  • Provide descriptive message for better user experience
  • Use for both authentication and authorization failures
Parameters
$message : string|null = null

Optional flash message to display on login page

Tags
throws
Exception

If Safe session operations fail

since
1.0.0
example

Simple Force Login

AuthManager::forceLogin();
// User redirected to login with default message
example

With Custom Message

AuthManager::forceLogin('Administrator access required.');
// User sees specific message explaining access requirement
example

With Return URL

AuthManager::setReturnUrl('/admin/reports');
AuthManager::forceLogin('Please log in to view reports.');
// User returned to reports page after successful login
Attributes
#[NoReturn]
Return values
void

This method never returns - always redirects and calls exit

getFlash()

Retrieve and consume flash message from session (removes after retrieval)

public static getFlash() : array{type: string, message: string}|null

Gets the current flash message and automatically removes it from the session, ensuring it displays exactly once. Returns structured data with both message type and content for easy rendering in templates.

Auto-Consumption Behavior

  • Message is removed from session when this method is called
  • Subsequent calls return null until new flash message is set
  • Prevents accidental duplicate message display
  • Implements standard flash message pattern

Return Format

Returns associative array with keys:

  • type - Message type for CSS classes (success, error, warning, info)
  • message - The actual message content to display
Tags
throws
Exception

If Safe session operations fail

since
1.0.0
example

Display Flash Message

$flash = AuthManager::getFlash();
if ($flash) {
    echo '<div class="alert alert-' . htmlspecialchars($flash['type']) . '">';
    echo htmlspecialchars($flash['message']);
    echo '</div>';
}
example

Template Integration

if ($flash = AuthManager::getFlash()) {
    displayAlert($flash['type'], $flash['message']);
}
Return values
array{type: string, message: string}|null

Flash message data or null if no message exists

getReturnUrl()

Get and consume the stored return URL for post-login redirect

public static getReturnUrl() : string|null

Retrieves the stored return URL from session and automatically removes it to prevent reuse. This method is called internally by login() to determine where to redirect users after successful authentication.

URL Lifecycle

  • URL is set via setReturnUrl() before authentication
  • Persists through login process in Safe session storage
  • Retrieved and removed by this method after successful login
  • Returns null if no return URL was previously set

Security Notes

  • URL is automatically cleared to prevent session fixation attacks
  • Old return URLs are cleared on logout to prevent stale redirects
  • No validation performed on URL - caller must ensure safety
Tags
throws
Exception

If Safe session operations fail

since
1.0.0
example

Internal Usage by login()

// Called internally by login() method:
$returnUrl = self::getReturnUrl() ?? self::$afterLogoutUrl;
header('Location: ' . $returnUrl);
example

Manual Retrieval (Rare)

$pendingUrl = AuthManager::getReturnUrl();
if ($pendingUrl) {
    echo "You were trying to access: $pendingUrl";
}
Return values
string|null

The stored return URL, or null if none exists

getUserAuthWords()

Get array of authorization words (roles/permissions) for the current user

public static getUserAuthWords() : array<string|int, string>

Retrieves all authorization words associated with the currently authenticated user from the authorization words model. Authorization words are normalized to lowercase and returned as a simple array for easy checking and iteration.

Database Query Process

  • Verifies user authentication status first
  • Queries auth words model filtering by current user ID
  • Extracts and normalizes authorization word values
  • Returns empty array if not authenticated or no authorizations found

Authorization Word Format

  • All returned values are lowercase for consistency
  • Duplicates are automatically removed by database constraints
  • Array values are strings representing role/permission names
Tags
throws
RuntimeException

If auth words model is not configured

throws
Exception

If Safe session operations fail

since
1.0.0
example

Display User Roles

$permissions = AuthManager::getUserAuthWords();
if (!empty($permissions)) {
    echo "Your roles: " . implode(', ', $permissions);
    // Output: "Your roles: admin, user, manager"
}
example

Check Specific Permission

$permissions = AuthManager::getUserAuthWords();
if (in_array('admin', $permissions)) {
    echo "User has admin role";
}
Return values
array<string|int, string>

Array of lowercase authorization words, or empty array if not authenticated

isAuthorized()

Check if current authenticated user has a specific authorization word (role/permission)

public static isAuthorized(string $authWord) : bool

Verifies both user authentication and specific authorization. Authorization words are case-insensitive and automatically normalized to lowercase for consistent matching across the application.

Authorization Logic

  • First ensures user is logged in with valid session
  • Retrieves all user authorization words from database
  • Performs case-insensitive comparison with requested auth word
  • Returns false immediately if user is not authenticated
Parameters
$authWord : string

The authorization word (role/permission) to check for

Tags
throws
RuntimeException

If auth words model is not configured

throws
Exception

If Safe session operations fail

since
1.0.0
example

Admin Panel Access

if (AuthManager::isAuthorized('admin')) {
    // User has admin privileges
    showAdminPanel();
} else {
    echo "Admin access required";
}
example

Manager Tools Access

if (AuthManager::isAuthorized('manager')) {
    // User has manager privileges
    showManagerTools();
}
Return values
bool

True if user is authenticated AND has the specified authorization

isAuthorizedAll()

Check if user has all of the specified authorization words (AND logic)

public static isAuthorizedAll(array<string|int, string> $authWords) : bool

Evaluates multiple authorization words with AND logic - returns true only if the user has ALL of the provided authorization words. Useful for "admin AND finance" type access control where multiple specific permissions are required.

AND Logic Implementation

  • Iterates through all provided authorization words
  • Returns false immediately when first missing authorization is found
  • All authorization words are normalized to lowercase
  • Short-circuits on first failed match for performance
Parameters
$authWords : array<string|int, string>

Array of authorization words that must all be present

Tags
throws
RuntimeException

If auth words model is not configured

throws
Exception

If Safe session operations fail

since
1.0.0
example

Financial Admin Access

if (AuthManager::isAuthorizedAll(['admin', 'finance'])) {
    // User has both admin AND finance privileges
    showFinancialAdminTools();
}
example

Complex Permission Requirements

if (AuthManager::isAuthorizedAll(['manager', 'hr', 'payroll'])) {
    // User has all three specific privileges
    showPayrollManagement();
}
Return values
bool

True if user is authenticated AND has all specified authorizations

isAuthorizedAny()

Check if user has at least one of the specified authorization words (OR logic)

public static isAuthorizedAny(array<string|int, string> $authWords) : bool

Evaluates multiple authorization words with OR logic - returns true if the user has ANY of the provided authorization words. Useful for "admin OR manager" type access control where multiple roles can access the same resource.

OR Logic Implementation

  • Iterates through provided authorization words
  • Returns true immediately when first match is found
  • All authorization words are normalized to lowercase
  • Short-circuits on first successful match for performance
Parameters
$authWords : array<string|int, string>

Array of authorization words to check for

Tags
throws
RuntimeException

If auth words model is not configured

throws
Exception

If Safe session operations fail

since
1.0.0
example

Leadership Dashboard Access

if (AuthManager::isAuthorizedAny(['admin', 'manager', 'supervisor'])) {
    // User has at least one leadership role
    showLeadershipDashboard();
}
example

Multiple Role Options

if (AuthManager::isAuthorizedAny(['admin', 'manager'])) {
    // User has admin OR manager privileges
    showManagementTools();
}
Return values
bool

True if user is authenticated AND has at least one specified authorization

isLoggedIn()

Check if user is currently authenticated with a valid, non-expired session

public static isLoggedIn() : bool

Performs comprehensive session validation including existence check, timeout verification, and activity timestamp updates. This method is the authoritative way to determine if a user has valid authentication credentials.

Validation Process

  1. Verifies user ID exists in Safe session storage
  2. Checks if session has exceeded inactivity timeout duration
  3. Updates last activity timestamp for valid sessions
  4. Redirects to timeout URL if session has expired

Session Timeout Handling

  • Compares current time against stored last activity timestamp
  • Automatically redirects to timeout URL with flash message if expired
  • Updates activity timestamp to current time for valid sessions
  • Uses configured timeoutSeconds for inactivity threshold
Tags
throws
Exception

If Safe session operations fail

since
1.0.0
example

Basic Authentication Check

if (AuthManager::isLoggedIn()) {
    // User is authenticated and session is valid
    $user = AuthManager::user();
    echo "Welcome, " . $user->username;
} else {
    // Not authenticated or session expired
    AuthManager::forceLogin('Please log in to continue');
}
example

Page Guard Pattern

if (!AuthManager::isLoggedIn()) {
    AuthManager::setReturnUrl($_SERVER['REQUEST_URI']);
    AuthManager::forceLogin('Please log in to access this page');
}
// Page content here - only reached by authenticated users
Return values
bool

True if user has valid authentication, false if not logged in

lockedOutUrl()

Get or set the URL where locked-out users are redirected for notification

public static lockedOutUrl([string|null $url = null ]) : string

When a user attempts to login but their account is currently locked due to too many failed attempts, they will be redirected to this URL with an appropriate flash message explaining the lockout.

Parameters
$url : string|null = null

If provided, sets the locked out URL and returns the previous value

Tags
since
1.0.0
example

Default Usage

$current = AuthManager::lockedOutUrl();         // Get current URL
echo "Lockout page: $current";                  // Shows '/locked.php' (default)
example

Custom Lockout Page

$old = AuthManager::lockedOutUrl('/auth/account-locked.php');
echo "Lockout page changed from: $old";
Return values
string

The current locked out URL (if getting) or previous URL (if setting)

lockoutTime()

Get or set the lockout duration in seconds after exceeding max login attempts

public static lockoutTime([int|null $seconds = null ]) : int

When a user account is locked due to too many failed attempts, they will be prevented from attempting to login again for this duration.

Parameters
$seconds : int|null = null

If provided, sets lockout time and returns the previous value

Tags
since
1.0.0
example

Get Current Lockout Duration

$current = AuthManager::lockoutTime();          // Returns current duration
$minutes = $current / 60;                       // Convert to minutes
echo "Lockout duration: $minutes minutes";      // Shows '15 minutes' (default)
example

Set 30 Minute Lockout

$old = AuthManager::lockoutTime(1800);          // 30 minutes in seconds
echo "Lockout changed from " . ($old/60) . " to 30 minutes";
Return values
int

The current lockout time in seconds (if getting) or previous lockout time (if setting)

login()

Attempt to authenticate user with username and password - always redirects, never returns

public static login(string $username, string $password) : never

Handles complete login workflow including password verification, failed attempt tracking, account lockout enforcement, and session creation. This method performs all authentication logic and always redirects the user to either a success or failure destination.

Successful Login Process

  • Resets failed attempt counters in database
  • Creates secure session using Safe class
  • Redirects to return URL (if set) or configured success destination

Failed Login Process

  • Increments failed attempt counter in database
  • Applies account lockout if max attempts exceeded
  • Redirects to login page with appropriate error flash message

Security Features

  • Uses password_verify() for secure password comparison
  • Protects against timing attacks through consistent processing
  • Enforces account lockouts to prevent brute force attacks
  • Cleans up stale session data before creating new session
Parameters
$username : string

The username to authenticate against

$password : string

The plaintext password to verify (never stored)

Tags
throws
RuntimeException

If user or auth words models aren't configured

throws
Exception

If Safe session operations fail

since
1.0.0
example

Login Form Processing

if ($_POST['login']) {
    AuthManager::login($_POST['username'], $_POST['password']);
    // Code below this line never executes - user is redirected
}
example

With Return URL

AuthManager::setReturnUrl('/admin/dashboard');
AuthManager::login($username, $password);
// User goes to dashboard on success, login page on failure
Return values
never

This method never returns - always redirects and calls exit

loginUrl()

Get or set the login URL where users are redirected for authentication

public static loginUrl([string|null $url = null ]) : string

This URL is used whenever the system needs to redirect users for authentication, such as when using forceLogin() or when authentication is required but not present.

Parameters
$url : string|null = null

If provided, sets the login URL and returns the previous value

Tags
since
1.0.0
example

Get Current Login URL

$current = AuthManager::loginUrl();              // Returns current URL
echo "Login page: $current";                     // Shows '/login.php' (default)
example

Set New Login URL

$old = AuthManager::loginUrl('/new-login.php');  // Set new URL, get old one back
echo "Changed from: $old";                       // Shows previous URL
Return values
string

The current login URL (if getting) or previous login URL (if setting)

logout()

Log out current user, clean up all session data, and redirect - never returns

public static logout() : never

Performs complete logout workflow including session cleanup, return URL clearing, and user notification. This method ensures all authentication-related data is properly removed from the session to prevent security issues.

Logout Process

  • Removes all authentication data from Safe session storage
  • Clears saved return URLs to prevent stale redirects
  • Sets success flash message for user feedback
  • Redirects to configured after-logout URL and exits

Security Considerations

  • Completely clears session authentication state
  • Prevents session fixation by removing all auth data
  • Cleans up potentially stale return URL redirects
  • Provides clear feedback that logout was successful
Tags
throws
Exception

If Safe session operations fail

since
1.0.0
example

Simple Logout

AuthManager::logout();
// User is redirected to after-logout page - code below never runs
example

In Logout Handler

if ($_POST['logout'] || $_GET['logout']) {
    AuthManager::logout();
    // Automatic redirect to configured destination
}
Return values
never

This method never returns - always redirects and calls exit

maxLoginAttempts()

Get or set the maximum login attempts before triggering account lockout

public static maxLoginAttempts([int|null $attempts = null ]) : int

When a user exceeds this number of failed login attempts, their account will be temporarily locked for the duration specified by lockoutTime().

Parameters
$attempts : int|null = null

If provided, sets max attempts and returns the previous value

Tags
since
1.0.0
example

Get Current Max Attempts

$current = AuthManager::maxLoginAttempts();     // Returns current limit
echo "Max attempts: $current";                  // Shows '5' (default)
example

Set Stricter Limit

$old = AuthManager::maxLoginAttempts(3);        // Allow only 3 attempts
echo "Attempts limit changed from $old to 3";
Return values
int

The current max attempts (if getting) or previous max attempts (if setting)

requireAuth()

Enforce authentication and optional authorization requirements - redirects if not met

public static requireAuth([string|array<string|int, string>|null $requiredAuthWord = null ]) : void

Provides declarative access control by checking authentication and authorization requirements. If requirements are not met, automatically redirects with appropriate flash messages. This method never returns when access is denied.

Access Control Logic

  • Always requires valid authentication (logged-in user)
  • Optionally requires specific authorization word(s)
  • Supports both single auth word and multiple auth words (ANY logic)
  • Sets appropriate flash messages before redirect
  • Does NOT automatically set return URLs (controller responsibility)

Authorization Modes

  • No auth word: Requires login only
  • Single string: Requires specific authorization word
  • Array of strings: Requires ANY of the authorization words (OR logic)
Parameters
$requiredAuthWord : string|array<string|int, string>|null = null

Single auth word, array of auth words, or null for login-only

Tags
throws
RuntimeException

If models are not configured

throws
Exception

If Safe session operations fail

since
1.0.0
example

Require Login Only

AuthManager::requireAuth();
// Code below only runs for authenticated users
example

Require Specific Role

AuthManager::setReturnUrl($_SERVER['REQUEST_URI']);
AuthManager::requireAuth('admin');
// Only admin users can access this code
example

Require Multiple Role Options

AuthManager::setReturnUrl($_SERVER['REQUEST_URI']);
AuthManager::requireAuth(['admin', 'manager']);
// Admin OR manager users can access this code
Return values
void

Returns normally if access granted, redirects and exits if denied

setFlash()

Set flash message for display after redirect (consumed on next request)

public static setFlash(string $type, string $message) : void

Flash messages provide user feedback across HTTP redirects by storing the message in the session temporarily. Messages are automatically consumed (removed) when retrieved with getFlash(), ensuring they display exactly once.

Flash Message Lifecycle

  • Message is stored in Safe session using flash storage
  • Survives exactly one HTTP redirect cycle
  • Automatically removed when retrieved with getFlash()
  • Perfect for post-redirect-get pattern feedback

Common Message Types

  • success - Green/positive feedback (login success, save confirmation)
  • error - Red/negative feedback (login failure, validation errors)
  • warning - Yellow/caution feedback (session timeout, deprecated features)
  • info - Blue/informational feedback (tips, announcements)
Parameters
$type : string

Message type for CSS styling (success, error, warning, info)

$message : string

The actual message content to display to the user

Tags
throws
Exception

If Safe session operations fail

since
1.0.0
example

Success Messages

AuthManager::setFlash('success', 'Profile updated successfully!');
AuthManager::setFlash('success', 'Password changed successfully!');
example

Error Messages

AuthManager::setFlash('error', 'Invalid username or password.');
AuthManager::setFlash('error', 'Account is temporarily locked.');
example

Warning and Info Messages

AuthManager::setFlash('warning', 'Session will expire in 5 minutes.');
AuthManager::setFlash('info', 'New features are now available.');

setReturnUrl()

Set return URL for post-login redirect to user's intended destination

public static setReturnUrl(string $url) : void

Stores a URL in the session that will be used as the redirect destination after successful login. This allows users to return to their intended page after being forced to authenticate, improving user experience by maintaining navigation context.

URL Management Strategy

  • Overwrites any existing return URL in session
  • URL persists until login success or session timeout
  • Automatically cleared after successful login to prevent reuse
  • Should be called before redirecting user to login page

Security Considerations

  • No validation performed on URL format (trusts caller)
  • Caller responsible for sanitizing URLs if needed
  • URLs can be relative or absolute paths
  • Return URLs are cleared on logout to prevent stale redirects
Parameters
$url : string

The destination URL where user should be sent after login

Tags
throws
Exception

If Safe session operations fail

since
1.0.0
example

Standard Page Protection

AuthManager::setReturnUrl($_SERVER['REQUEST_URI']);
AuthManager::requireAuth('admin');
// User returns to exact same page after login
example

Secure Redirect Strategy

if ($sensitiveAction) {
    AuthManager::setReturnUrl('/admin/dashboard');  // Safe destination
} else {
    AuthManager::setReturnUrl($_SERVER['REQUEST_URI']); // Original page
}
AuthManager::forceLogin();

timeoutSeconds()

Get or set the session timeout duration in seconds for inactivity-based logout

public static timeoutSeconds([int|null $seconds = null ]) : int

When a user's session is inactive for longer than this duration, they will be automatically logged out and redirected to the timeout URL on their next request.

Parameters
$seconds : int|null = null

If provided, sets the timeout duration and returns the previous value

Tags
since
1.0.0
example

Get Current Timeout

$current = AuthManager::timeoutSeconds();       // Get current timeout
$hours = $current / 3600;                       // Convert to hours
echo "Session timeout: $hours hours";           // Shows '1 hours' (default)
example

Set 2 Hour Timeout

$old = AuthManager::timeoutSeconds(7200);       // 2 hours, get old timeout
echo "Timeout changed from " . ($old/3600) . " to 2 hours";
Return values
int

The current timeout in seconds (if getting) or previous timeout (if setting)

timeoutUrl()

Get or set the URL where users are redirected when their session times out

public static timeoutUrl([string|null $url = null ]) : string

When a user's session expires due to inactivity (exceeds timeoutSeconds()), they will be redirected to this URL with appropriate notification.

Parameters
$url : string|null = null

If provided, sets the timeout URL and returns the previous value

Tags
since
1.0.0
example

Get Current Timeout Destination

$current = AuthManager::timeoutUrl();           // Get current URL
echo "Timeout page: $current";                  // Shows '/timeout.php' (default)
example

Custom Timeout Page

$old = AuthManager::timeoutUrl('/auth/session-expired.php');
echo "Timeout destination changed from: $old";
Return values
string

The current timeout URL (if getting) or previous URL (if setting)

user()

Get the current authenticated user's model instance from the database

public static user() : Model|null

Retrieves the complete user record from the database for the currently authenticated user. This method first verifies authentication, then fetches the full user model with all available fields and relationships.

Database Query Process

  • Verifies user authentication with isLoggedIn() check
  • Extracts user ID from Safe session storage
  • Queries user model using the stored user ID
  • Returns null if not authenticated or user record not found

Use Cases

  • Displaying user profile information
  • Accessing user preferences and settings
  • Checking user-specific database fields
  • Audit logging with user context
Tags
throws
RuntimeException

If user model is not configured

throws
Exception

If Safe session operations fail

since
1.0.0
example

Display User Information

$user = AuthManager::user();
if ($user) {
    echo "Welcome, " . htmlspecialchars($user->username);
    echo "Email: " . htmlspecialchars($user->email);
    echo "Member since: " . $user->created_at;
}
example

Safe Chaining (PHP 8+)

$username = AuthManager::user()?->username ?? 'Guest';
$isVerified = AuthManager::user()?->email_verified ?? false;
Return values
Model|null

The complete user model instance, or null if not authenticated

userAuthWordsModel()

Get or set the user authorization words model for role-based access control

public static userAuthWordsModel([Model|null $model = null ]) : Model|null

The auth words model manages the many-to-many relationship between users and their authorization words (roles/permissions). Must support user_id and auth_word fields.

Parameters
$model : Model|null = null

If provided, sets the auth words model and returns the previous value

Tags
throws
RuntimeException

If model doesn't support required authorization fields

since
1.0.0
example

Get Current Model

$current = AuthManager::userAuthWordsModel();   // Get current model
if ($current) {
    echo "Auth model: " . get_class($current);
}
example

Set Authorization Model

$old = AuthManager::userAuthWordsModel(new UserAuthWords());
echo "Auth model changed from: " . ($old ? get_class($old) : 'none');
Return values
Model|null

The current auth words model (if getting) or previous model (if setting)

userModel()

Get or set the user model instance for database authentication operations

public static userModel([Model|null $model = null ]) : Model|null

The user model must support the Primordyx Model interface and should have fields for username, password_hash, failed_attempts, last_failed, and locked_until.

Parameters
$model : Model|null = null

If provided, sets the user model and returns the previous value

Tags
throws
RuntimeException

If model doesn't support required authentication fields

since
1.0.0
example

Get Current Model

$current = AuthManager::userModel();            // Get current model
if ($current) {
    echo "Using model: " . get_class($current);
}
example

Set User Model

$old = AuthManager::userModel(new User());      // Set new model, get old one back
echo "Model changed from: " . ($old ? get_class($old) : 'none');
Return values
Model|null

The current user model (if getting) or previous model (if setting)

ensureModelsConfigured()

Ensure required models are configured before performing database operations

protected static ensureModelsConfigured() : void

Validates that both the user model and user authorization words model have been properly set via the configuration methods. Throws descriptive runtime exceptions if either model is missing.

Validation Process

  1. Checks if user model is set (for authentication)
  2. Checks if auth words model is set (for authorization)
  3. Throws RuntimeException with clear instructions if missing

Configuration Requirements

Models must be configured before any authentication operations:

  • User model: Handles user records and authentication
  • Auth words model: Handles user permissions/roles
Tags
throws
RuntimeException

If user model or auth words model is not configured

since
1.0.0
example

Bootstrap Configuration

// Configure models in bootstrap to avoid exceptions:
AuthManager::userModel(new User());
AuthManager::userAuthWordsModel(new UserAuthWords());
example

Exception Messages

// If user model not set:
// "User model must be set using AuthManager::userModel() before use."

// If auth words model not set:
// "UserAuthWords model must be set using AuthManager::userAuthWordsModel() before use."
used-by

Various AuthManager methods that require database access

handleFailedLogin()

Handle failed login attempt by updating attempt counters and applying lockouts

protected static handleFailedLogin(Model $user) : void

Increments the failed attempt counter, records the failure timestamp, and applies account lockout if the maximum attempts threshold is exceeded. Sets appropriate flash messages indicating remaining attempts or lockout status.

Failed Login Process

  1. Increments failed_attempts counter in user record
  2. Updates last_failed timestamp to current time
  3. Checks if max attempts exceeded
  4. If exceeded, sets locked_until timestamp for lockout period
  5. Sets appropriate flash message for user feedback
  6. Saves updated user record to database

Flash Message Logic

  • Under limit: Shows remaining attempts count
  • At limit: Indicates account is now locked
  • Provides clear feedback about security status
Parameters
$user : Model

The user model instance to update

Tags
throws
Exception

If database operations fail

since
1.0.0
example

Called by login() Method

// Automatically called when password verification fails:
if (!password_verify($password, $user->password_hash)) {
    self::handleFailedLogin($user);
    header('Location: ' . self::$loginUrl);
    exit;
}
used-by

AuthManager::login() Called automatically on password failure

handleSuccessfulLogin()

Handle successful login by resetting failure counters and creating session

protected static handleSuccessfulLogin(Model $user) : void

Resets all failed login tracking fields, creates the authenticated session in Safe storage, and sets a welcome flash message. Called automatically after successful password verification.

Successful Login Process

  1. Resets failed_attempts counter to 0
  2. Clears last_failed timestamp
  3. Clears locked_until timestamp
  4. Saves cleaned user record to database
  5. Creates authenticated session with user ID
  6. Sets last_activity timestamp for timeout tracking
  7. Sets login_time timestamp for session duration tracking
  8. Sets welcome flash message with username

Session Data Created

  • auth_user_id - User's database ID for identity
  • auth_last_activity - Timestamp for timeout checking
  • auth_login_time - Timestamp for session duration
Parameters
$user : Model

The user model instance to update and create session for

Tags
throws
Exception

If Safe session operations fail

since
1.0.0
example

Called by login() Method

// Automatically called after successful password verification:
if (password_verify($password, $user->password_hash)) {
    self::handleSuccessfulLogin($user);
    // Redirect to return URL or default
}
used-by

AuthManager::login() Called automatically on password success


        
On this page

Search results