Application
extends BaseApplication
in package
implements
AuthenticationServiceProviderInterface, AuthorizationServiceProviderInterface
Kingdom Management Portal Application Class
This is the main application class that orchestrates the entire KMP system. It extends CakePHP's BaseApplication to provide KMP-specific functionality including authentication, authorization, middleware configuration, and dependency injection setup.
Key Responsibilities:
- Bootstrap application configuration and plugin registration
- Configure middleware stack for security, routing, and request handling
- Set up authentication service with session and form-based login
- Configure authorization service with policy-based access control
- Register core services in the dependency injection container
- Initialize navigation system for dynamic menu generation
- Manage application settings with version-based updates
Middleware Stack (in order):
- ErrorHandlerMiddleware - Exception handling and error pages
- Request performance logging middleware (optional)
- Security Headers - CSP, HSTS, XSS protection, frame options
- AssetMiddleware - Static asset serving with caching
- RoutingMiddleware - URL routing and route matching
- BodyParserMiddleware - Request body parsing (JSON, XML, etc.)
- CsrfProtectionMiddleware - CSRF token validation
- AuthenticationMiddleware - User authentication
- AuthorizationMiddleware - Permission checking and access control
- FootprintMiddleware - User activity tracking
Security Model:
- Session-based authentication with secure cookie settings
- Form-based login with brute force protection
- Policy-based authorization using ORM and controller resolvers
- Comprehensive CSP headers for XSS prevention
- HSTS for secure connections
Service Container:
- ActiveWindowManagerInterface for date-bounded entities
- WarrantManagerInterface for warrant lifecycle management
- CsvExportService for data export functionality
Tags
Table of Contents
Interfaces
- AuthenticationServiceProviderInterface
- AuthorizationServiceProviderInterface
Methods
- bootstrap() : void
- Application Bootstrap Process
- getAuthenticationService() : AuthenticationServiceInterface
- Authentication Service Configuration
- getAuthorizationService() : AuthorizationServiceInterface
- Authorization Service Configuration
- middleware() : MiddlewareQueue
- Middleware Stack Configuration
- services() : void
- Dependency Injection Container Service Registration
Methods
bootstrap()
Application Bootstrap Process
public
bootstrap() : void
This method handles the initial application setup and configuration. It performs several critical initialization tasks:
-
Parent Bootstrap: Calls CakePHP's parent bootstrap to load configuration files and perform standard framework initialization
-
Table Locator Configuration: Optimizes the ORM table locator for web requests (CLI requests use different optimization)
-
Navigation System Registration: Registers the core navigation provider that generates the main application menu structure
-
Application Settings Management: Implements a version-based configuration system that automatically updates settings when the application is upgraded
Version-Based Configuration: The system tracks a configuration version and automatically applies new default settings when the version changes. This ensures that application updates don't break existing installations while still providing new configuration options.
Settings Categories Managed:
- KMP Core Settings (site titles, branding, maintenance mode)
- Member Management (verification emails, registration settings)
- Email Configuration (system addresses, signatures)
- Activity Management (secretary contacts)
- Warrant System (approval requirements, checking schedules)
- Branch Management (organizational structure types)
Performance Notes:
- Table locator optimization reduces memory usage in web contexts
- Settings are cached after initial load to prevent database queries
- Navigation registration uses callback for lazy loading
Tags
getAuthenticationService()
Authentication Service Configuration
public
getAuthenticationService(ServerRequestInterface $request) : AuthenticationServiceInterface
This method configures the authentication service that handles user login, session management, and credential validation. KMP uses a multi-layered authentication approach with session persistence and form-based login with brute force protection.
Authentication Flow:
- Check for existing valid session
- If no session, attempt form-based authentication
- Validate credentials against database with password hashing
- Apply brute force protection to prevent password attacks
- Redirect unauthenticated users to login page
Authenticators (in order of precedence):
-
Session Authenticator: Checks for existing user session
- Fastest authentication method
- Validates session tokens and user identity
- Handles session persistence across requests
-
Form Authenticator: Processes login form submissions
- Validates username/password from POST data
- Uses email address as username field
- Redirects to login page when credentials are invalid
Identifier Configuration:
- KMPBruteForcePassword: Custom identifier with attack protection
- ORM Resolver: Validates against Members table in database
- Fallback Password Hasher: Supports multiple password formats
- Default: Modern bcrypt hashing (preferred)
- Legacy: MD5 hashing (for existing passwords, migrated on login)
Security Features:
- Brute force protection prevents password guessing attacks
- Password migration from legacy MD5 to secure bcrypt
- Session-based authentication with secure cookie settings
- Automatic redirect to login page for unauthenticated requests
Configuration Options:
- Login URL: /members/login (form submission target)
- Redirect URL: Preserved in query parameter for post-login navigation
- Username Field: email_address (unique identifier)
- Password Field: password (hashed storage)
Parameters
- $request : ServerRequestInterface
-
Current HTTP request
Tags
Return values
AuthenticationServiceInterface —Configured authentication service
getAuthorizationService()
Authorization Service Configuration
public
getAuthorizationService(ServerRequestInterface $request) : AuthorizationServiceInterface
This method configures the authorization service that handles permission checking and access control throughout the application. KMP uses a policy-based authorization system with multiple resolvers to handle different types of authorization scenarios.
Authorization Architecture: KMP implements a multi-layered authorization system that checks permissions at both the ORM (entity) level and controller level. This provides fine-grained access control for data operations and coarse-grained control for application functionality.
Policy Resolvers (in order of precedence):
-
ORM Resolver: Handles entity-level authorization
- Resolves policies for CakePHP entities and tables
- Checks permissions for CRUD operations (create, read, update, delete)
- Handles data scoping (users only see data they're authorized for)
- Example: MemberPolicy::canView(), BranchPolicy::canEdit()
-
Controller Resolver: Handles controller-level authorization
- Resolves policies for controller actions
- Provides application-level access control
- Handles complex business logic authorization
- Example: ReportsControllerPolicy::canGenerateReports()
Policy Resolution Process:
- Authorization request is made (e.g., $this->Authorization->can('view', $member))
- ORM resolver attempts to find and execute appropriate entity policy
- If no entity policy found, controller resolver handles the request
- Policy method is executed with user context and resource
- Boolean result determines access (true = allowed, false = denied)
Authorization Features:
- Entity-level scoping (filter data based on user permissions)
- Controller action authorization (restrict access to functionality)
- Resource-based permissions (different permissions per entity instance)
- Role-based access control integration
- Custom policy logic for complex business rules
Security Benefits:
- Defense in depth through multiple authorization layers
- Consistent permission checking across the application
- Centralized authorization logic in policy classes
- Automatic authorization requirement enforcement
- Audit trail through authorization service logging
Parameters
- $request : ServerRequestInterface
-
Current HTTP request
Tags
Return values
AuthorizationServiceInterface —Configured authorization service
middleware()
Middleware Stack Configuration
public
middleware(MiddlewareQueue $middlewareQueue) : MiddlewareQueue
This method configures the HTTP middleware stack that processes every request. The middleware stack follows a specific order where each layer can modify the request/response or halt processing entirely.
Middleware Stack Order and Purpose:
-
ErrorHandlerMiddleware: Catches exceptions and converts them to appropriate HTTP error responses. Must be first to catch all errors.
-
Request Performance Middleware: Optionally logs request timing metrics when PERF_REQUEST_LOG_ENABLED is enabled.
-
Security Headers Middleware: Adds comprehensive security headers including CSP, HSTS, XSS protection, and frame options. This is a custom inline middleware that implements defense-in-depth security.
-
AssetMiddleware: Serves static assets (CSS, JS, images) with proper caching headers. Handles plugin and theme assets.
-
RoutingMiddleware: Matches URLs to controllers and actions. Populates route parameters in the request object.
-
BodyParserMiddleware: Parses request bodies (JSON, XML, form data) and makes them available via $request->getData().
-
CsrfProtectionMiddleware: Validates CSRF tokens to prevent cross-site request forgery attacks. Uses secure cookie settings.
-
AuthenticationMiddleware: Handles user authentication using session and form-based authentication.
-
AuthorizationMiddleware: Checks user permissions and enforces access control policies. Requires authorization check on all requests.
-
FootprintMiddleware: Tracks user activity for auditing purposes.
Security Configuration Details:
- CSP headers prevent XSS attacks by restricting resource loading
- HSTS enforces HTTPS connections
- CSRF tokens use secure, HTTP-only, same-site cookies
- Authorization requires checks on all requests with redirect handling
Performance Considerations:
- Asset middleware includes caching configuration
- Route caching can be enabled for large applications
- Authorization checks are required but cached for performance
Parameters
- $middlewareQueue : MiddlewareQueue
-
The middleware queue to configure
Tags
Return values
MiddlewareQueue —The configured middleware queue
services()
Dependency Injection Container Service Registration
public
services(ContainerInterface $container) : void
This method configures the application's dependency injection container by registering core services and their dependencies. The container manages object lifecycle and handles dependency resolution automatically.
Registered Services:
-
ActiveWindowManagerInterface: Manages date-bounded entities that have specific validity periods (like warrants, authorizations).
- Implementation: DefaultActiveWindowManager
- Purpose: Handles entity activation/deactivation based on date ranges
- Usage: Warrant management, officer terms, event registrations
-
WarrantManagerInterface: Handles warrant lifecycle management including creation, approval, expiration, and renewal processes.
- Implementation: DefaultWarrantManager
- Dependencies: ActiveWindowManagerInterface (for date management)
- Purpose: Officer warrant processing and workflow management
- Usage: Officer appointments, warrant approvals, roster management
-
CsvExportService: Provides standardized CSV export functionality for various data types with consistent formatting and security.
- No dependencies
- Purpose: Data export for reports and bulk operations
- Usage: Member lists, warrant reports, activity data
Container Benefits:
- Automatic dependency resolution
- Singleton instance management
- Interface-based programming support
- Testability through dependency injection
- Service lifecycle management
Service Resolution Example:
// Container automatically resolves dependencies
$warrantManager = $container->get(WarrantManagerInterface::class);
// ActiveWindowManagerInterface is automatically injected
Parameters
- $container : ContainerInterface
-
The DI container to configure