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
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'
$userAuthWordsModel
protected
static Model|null
$userAuthWordsModel
= null
$userModel
protected
static Model|null
$userModel
= null
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
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 authenticationmax_login_attempts
- Failed attempts before account lockoutlockout_time
- Lockout duration in secondslocked_out_url
- Where to show lockout notificationafter_logout_url
- Destination after successful logouttimeout_url
- Where to redirect on session timeouttimeout_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
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
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
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
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
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
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
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
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
- Verifies user ID exists in Safe session storage
- Checks if session has exceeded inactivity timeout duration
- Updates last activity timestamp for valid sessions
- 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
- Checks if user model is set (for authentication)
- Checks if auth words model is set (for authorization)
- 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
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
- Increments failed_attempts counter in user record
- Updates last_failed timestamp to current time
- Checks if max attempts exceeded
- If exceeded, sets locked_until timestamp for lockout period
- Sets appropriate flash message for user feedback
- 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
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
- Resets failed_attempts counter to 0
- Clears last_failed timestamp
- Clears locked_until timestamp
- Saves cleaned user record to database
- Creates authenticated session with user ID
- Sets last_activity timestamp for timeout tracking
- Sets login_time timestamp for session duration tracking
- Sets welcome flash message with username
Session Data Created
auth_user_id
- User's database ID for identityauth_last_activity
- Timestamp for timeout checkingauth_login_time
- Timestamp for session duration
Parameters
- $user : Model
-
The user model instance to update and create session for