SessionManager

Introduction

The SessionManager class in JiFramework provides a comprehensive solution for managing sessions, CSRF tokens, and flash messages within your application. It simplifies common session-related tasks and enhances security by handling CSRF protection automatically. Once configured, the SessionManager class will automatically manage CSRF tokens and flash messages throughout your application without additional code changes.

Key Features:

  • CSRF Protection: Generates and verifies CSRF tokens to protect against Cross-Site Request Forgery attacks.
  • Flash Messaging: Easily set and retrieve flash messages for user notifications.
  • Session Management: Handles session initialization, regeneration, and cookie parameters.
  • Automatic Enforcement: CSRF verification can be automatically enforced via middleware.

Note: To activate CSRF protection and customize session behavior, you can configure settings in your Config class. The SessionManager class will then automatically handle CSRF tokens and flash messages based on your configuration.

Usage:

// Option 1: Initialize the SessionManager through the App
use JIFramework\Core\App\App;
$app = new App();
$sessionManager = $app->SessionManager;

OR 

// Option 2: Directly instantiate the SessionManager
use JIFramework\Core\Session\SessionManager;
$sessionManager = new SessionManager();

Why Use SessionManager:

Implementing the SessionManager class in your application provides several benefits:

  • Enhanced Security: Protects against CSRF attacks by automatically generating and verifying CSRF tokens.
  • Simplified Session Handling: Provides methods for common session tasks, reducing boilerplate code.
  • User Notifications: Easily manage flash messages for displaying success, error, and informational messages to users.
  • Automatic Enforcement: CSRF protection can be automatically enforced for POST requests via middleware.
  • Customization: Easily configure session settings to match your application's requirements.

Configuration

Before using the SessionManager class, you may want to configure various settings in your Config class to customize session management, CSRF tokens, and flash messages.

Configuration Options:

namespace JIFramework\Config;

class Config {
    // Session key for storing CSRF tokens
    const CSRF_TOKEN_KEY = '_csrf_tokens';

    // CSRF token expiration time in seconds (default: 3600 seconds = 1 hour)
    const CSRF_TOKEN_EXPIRY = 3600;

    // Maximum number of CSRF tokens to store (default: 100)
    const CSRF_TOKEN_LIMIT = 100;

    // Length of the CSRF token in bytes (default: 32 bytes)
    const CSRF_TOKEN_LENGTH = 32;

    // Session key for storing flash messages
    const FLASH_MESSAGE_KEY = '_flash_messages';

    // Additional session configurations can be added as needed
}

Explanation:

  • CSRF_TOKEN_KEY (string): The session key under which CSRF tokens are stored.
    • Default: '_csrf_tokens'.
  • CSRF_TOKEN_EXPIRY (int): The duration (in seconds) before a CSRF token expires.
    • Default: 3600 seconds (1 hour).
  • CSRF_TOKEN_LIMIT (int): The maximum number of CSRF tokens to store per session.
    • Default: 100.
  • CSRF_TOKEN_LENGTH (int): The length of the generated CSRF token in bytes.
    • Default: 32 bytes.
  • FLASH_MESSAGE_KEY (string): The session key under which flash messages are stored.
    • Default: '_flash_messages'.

generateCsrfToken()

Method: generateCsrfToken(): string

Description: Generates a new CSRF token, stores it in the session, and returns it.

Parameters: None

Returns: A string representing the generated CSRF token.

Usage:

// Generate a CSRF token
$csrfToken = $sessionManager->generateCsrfToken();

// Include the token in your form
echo '';

Explanation:

  • Generates a cryptographically secure random token using random_bytes().
  • Stores the token in the session along with the current timestamp.
  • Maintains a maximum number of tokens to prevent session bloat.
  • Returns the generated token for inclusion in forms or AJAX requests.

verifyCsrfToken()

Method: verifyCsrfToken(string $token): bool

Description: Verifies the provided CSRF token against the tokens stored in the session.

Parameters:

  • $token (string): The CSRF token to verify.

Returns: true if the token is valid and not expired; false otherwise.

Usage:

// Retrieve the token from the request
$token = $_POST['_csrf_token'] ?? '';

if ($sessionManager->verifyCsrfToken($token)) {
    // Token is valid; proceed with processing
} else {
    // Invalid token; handle the error
    $sessionManager->setErrorMessage('Invalid CSRF token.', '/');
}

Explanation:

  • Checks if the token exists in the session.
  • Verifies that the token has not expired based on the configured expiry time.
  • Removes the token from the session after verification to prevent reuse (single-use tokens).
  • Cleans up expired tokens from the session.

setFlashMessage()

Method: setFlashMessage(string $type, string $message, array $data = []): void

Description: Sets a flash message in the session for displaying to the user on the next page load.

Parameters:

  • $type (string): The type of message ('success', 'error', 'info', 'warning').
  • $message (string): The message content.
  • $data (array, optional): Additional data associated with the message.

Usage:

// Set a success flash message
$sessionManager->setFlashMessage('success', 'Your changes have been saved.');

// Set an error flash message with additional data
$sessionManager->setFlashMessage('error', 'An error occurred.', ['error_code' => 123]);

Explanation:

  • Adds the message to the session under the flash message key.
  • Supports different message types for flexible styling in your views.
  • Optional data can be included for additional context.

getFlashMessages()

Method: getFlashMessages(): array

Description: Retrieves all flash messages from the session and clears them.

Parameters: None

Returns: An array of flash messages.

Usage:

// Retrieve flash messages in your view
$flashMessages = $sessionManager->getFlashMessages();

foreach ($flashMessages as $message) {
    echo '' . htmlspecialchars($message['message']) . '';
}

Explanation:

  • Fetches all flash messages stored in the session.
  • Clears the messages from the session to ensure they are displayed only once.
  • Useful for displaying messages to the user after redirects or form submissions.

regenerateSession()

Method: regenerateSession(bool $deleteOldSession = false): void

Description: Regenerates the session ID to prevent session fixation attacks.

Parameters:

  • $deleteOldSession (bool, optional): Whether to delete the old session data. Default is false.

Usage:

// Regenerate the session ID after login
$sessionManager->regenerateSession(true);

Explanation:

  • Calls session_regenerate_id() to create a new session ID.
  • Optionally deletes the old session data for enhanced security.
  • Recommended to use after user authentication or privilege changes.

setSessionCookieParams()

Method: setSessionCookieParams(array $params = []): void

Description: Sets the session cookie parameters for security and customization.

Parameters:

  • $params (array, optional): An array of parameters to set (e.g., lifetime, path, domain, secure, httponly, samesite).

Usage:

// Customize session cookie parameters
$sessionManager->setSessionCookieParams([
    'lifetime' => 86400, // 1 day
    'secure'   => true,
    'httponly' => true,
    'samesite' => 'Strict',
]);

Explanation:

  • Merges provided parameters with default values.
  • Calls session_set_cookie_params() to apply the settings.
  • Enhances session security by setting appropriate cookie attributes.

redirect()

Method: redirect(string $url): void

Description: Redirects the user to a specified URL and terminates the script.

Parameters:

  • $url (string): The URL to redirect to.

Usage:

// Redirect to the home page
$sessionManager->redirect('/home');

Explanation:

  • Sends an HTTP Location header to redirect the user.
  • Calls exit() to stop script execution.
  • Useful for redirecting after form submissions or authentication.

setJsonErrorMessage()

Method: setJsonErrorMessage(string $message): void

Description: Sends a JSON-formatted error message and terminates the script.

Parameters:

  • $message (string): The error message to send.

Usage:

// Send a JSON error response
$sessionManager->setJsonErrorMessage('An unexpected error occurred.');

Explanation:

  • Sets the Content-Type header to application/json.
  • Outputs a JSON-encoded error message.
  • Calls exit() to stop script execution.
  • Useful for API responses or AJAX error handling.

setJsonSuccessMessage()

Method: setJsonSuccessMessage(string $message, array $data = []): void

Description: Sends a JSON-formatted success message with optional data and terminates the script.

Parameters:

  • $message (string): The success message to send.
  • $data (array, optional): Additional data to include in the response.

Usage:

// Send a JSON success response
$sessionManager->setJsonSuccessMessage('Operation completed successfully.', ['id' => 42]);

Explanation:

  • Sets the Content-Type header to application/json.
  • Outputs a JSON-encoded success message with optional data.
  • Calls exit() to stop script execution.
  • Useful for API responses or AJAX success handling.

csrfMiddleware()

Method: csrfMiddleware(): void

Description: Middleware function to automatically verify CSRF tokens on POST requests.

Parameters: None

Usage:

// Include CSRF middleware at the beginning of your script
$sessionManager->csrfMiddleware();

Explanation:

  • Checks if the request method is POST.
  • Retrieves the CSRF token from the POST data.
  • Verifies the token using verifyCsrfToken().
  • If verification fails, sets an error message and redirects (default to home page).
  • Automates CSRF protection for all POST requests.

setErrorMessage()

Method: setErrorMessage(string $message, string $redirect = ''): void

Description: Sets an error flash message and optionally redirects the user.

Parameters:

  • $message (string): The error message to set.
  • $redirect (string, optional): The URL to redirect to. If empty, no redirect occurs.

Usage:

// Set an error message and redirect
$sessionManager->setErrorMessage('Invalid credentials.', '/login');

Explanation:

  • Uses setFlashMessage() to store the error message.
  • Calls redirect() if a redirect URL is provided.
  • Simplifies error handling and user notification.

setSuccessMessage()

Method: setSuccessMessage(string $message, string $redirect = '', array $data = []): void

Description: Sets a success flash message with optional data and optionally redirects the user.

Parameters:

  • $message (string): The success message to set.
  • $redirect (string, optional): The URL to redirect to. If empty, no redirect occurs.
  • $data (array, optional): Additional data associated with the message.

Usage:

// Set a success message and redirect
$sessionManager->setSuccessMessage('Profile updated successfully.', '/profile');

Explanation:

  • Uses setFlashMessage() to store the success message.
  • Calls redirect() if a redirect URL is provided.
  • Simplifies success handling and user notification.

Usage Examples

Example 1: CSRF Protection in Forms

// Initialize the SessionManager
use JIFramework\Core\App\App;
$app = new App();
$sessionManager = $app->SessionManager;

// Generate a CSRF token
$csrfToken = $sessionManager->generateCsrfToken();

// Include the token in your form
echo '';
echo '';
echo '';
echo '';
echo '';

Explanation:

  • Generates a CSRF token and includes it as a hidden input in the form.
  • Ensures that the token is submitted with the form data for verification.

Example 2: Verifying CSRF Token on Form Submission

// Initialize the SessionManager
use JIFramework\Core\App\App;
$app = new App();
$sessionManager = $app->SessionManager;

// Verify CSRF token on form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['_csrf_token'] ?? '';

    if ($sessionManager->verifyCsrfToken($token)) {
        // Token is valid; process the form
        // ...
        $sessionManager->setSuccessMessage('Form submitted successfully.', '/thank-you');
    } else {
        // Invalid token; handle the error
        $sessionManager->setErrorMessage('Invalid CSRF token.', '/form');
    }
}

Explanation:

  • Retrieves the CSRF token from the submitted form.
  • Verifies the token using verifyCsrfToken().
  • Sets appropriate flash messages and redirects based on the verification result.

Example 3: Displaying Flash Messages

// Initialize the SessionManager
use JIFramework\Core\App\App;
$app = new App();
$sessionManager = $app->SessionManager;

// Retrieve flash messages
$flashMessages = $sessionManager->getFlashMessages();

// Display messages
foreach ($flashMessages as $message) {
    echo '' . htmlspecialchars($message['message']) . '';
}

Explanation:

  • Retrieves flash messages set during previous requests.
  • Displays messages to the user and ensures they are cleared from the session.

Example 4: CSRF Middleware Usage

// Initialize the SessionManager
use JIFramework\Core\App\App;
$app = new App();
$sessionManager = $app->SessionManager;

// Enforce CSRF protection on POST requests
$sessionManager->csrfMiddleware();

// Proceed with the rest of the application logic
// ...

Explanation:

  • Calls csrfMiddleware() to automatically verify CSRF tokens on all POST requests.
  • Simplifies CSRF protection by centralizing verification.