Authentication System
Relevant source files
The following files were used as context for generating this wiki page:
The Authentication System in flext-cli provides a unified abstraction layer for managing user identity, credentials, and secure token persistence within CLI applications. It serves as the primary interface for implementing login/logout functionality, managing API tokens, and validating user access levels. The system is designed to work seamlessly with the project's Railway Pattern for error handling, returning p.Result types to ensure robust operation without broad try/except blocks.
The system encapsulates credential validation, secure token generation via secrets.token_urlsafe, and local filesystem persistence in JSON format. It leverages FlextCliFileTools for input/output operations and relies on project-wide settings for determining secure storage locations.
Sources: src/flext_cli/services/auth.py:1-25, examples/ex_05_authentication.py:1-20
Core Components and Services
FlextCliAuth Service
The FlextCliAuth class is the central service responsible for orchestrating the authentication lifecycle. It inherits from FlextCliServiceBase, gaining access to global settings and logging capabilities. This service abstracts the underlying CLI framework (Typer/Click) while providing high-level methods for token management.
Key methods include:
authenticate(credentials): High-level entry point that handles either token-based or username/password authentication.save_auth_token(token): Persists a string token to a configured JSON file.fetch_auth_token(): Retrieves the saved token, returning a result object.clear_auth_tokens(): Removes the local session by deleting the token file.
Sources: src/flext_cli/services/auth.py:28-55, tests/unit/test_services_auth_cov.py:20-25
Authentication Utility Layer
The FlextCliUtilitiesAuth (referenced via u.Cli) provides the low-level logic for credential validation and token extraction. It ensures that tokens are extracted correctly from JSON mappings and that usernames/passwords meet the application's basic validity criteria.
Sources: src/flext_cli/services/auth.py:40, src/flext_cli/_utilities/init.py:80
Data Flow and Architecture
The authentication process follows a structured flow from credential input to secure persistence. The following diagram illustrates the internal logic of the authenticate method, which determines whether to use an existing token or generate a new one based on provided credentials.
The diagram shows the logic within the authenticate and _resolve_token methods where the system branches based on the type of credentials supplied.
Sources: src/flext_cli/services/auth.py:57-89
Authentication Lifecycle Sequence
When a consumer application initiates a login, the system interacts with the filesystem to secure the session.
This sequence tracks the transition from raw user input to a persisted session token.
Sources: src/flext_cli/services/auth.py:57-95, examples/ex_05_authentication.py:32-48
Token Management and Persistence
Authentication tokens are stored locally in a file specified by the Cli.token_file setting. The system enforces that tokens cannot be empty or whitespace-only.
Persistence Configuration
| Parameter | Type | Description |
|---|---|---|
token_file | str | Filename or path for the persistent JSON auth token. |
DICT_KEY_AUTH_TOKEN | str | The JSON key used to store the token (default: "auth_token"). |
username | str | Key for username in credential payloads. |
password | str | Key for password/secret in credential payloads. |
Sources: src/flext_cli/services/auth.py:45-55, tests/_constants_parts/tests_yaml_output.py:116-120
Error Handling in Authentication
The system returns specific error messages for various failure modes, avoiding silent failures:
- Empty Token: "token cannot be empty" (using
VALIDATION_MSG_FIELD_CANNOT_BE_EMPTY). - Invalid Credentials: Triggered if the Pydantic model validation fails or user/pass validation fails.
- Save Failure: "Auth save failed" (using
ERR_AUTH_SAVE_FAILED). - Logout Failure: Handled via
OSerrorduringPath.unlink()calls in example implementations.
Sources: src/flext_cli/services/auth.py:47-49, src/flext_cli/services/auth.py:61, examples/ex_05_authentication.py:91-98
Implementation Example
The following snippet demonstrates how the FlextCliAuth service is typically consumed within an application's login logic.
# Based on examples/ex_05_authentication.py
def login_to_service(username: str, password: str) -> p.Result[bool]:
"""Perform login using the public facade."""
auth_result = cli.authenticate({
"username": username,
"password": password,
})
if auth_result.failure:
return r[bool].fail(auth_result.error or "Login failed")
# Retrieve path for reporting
token_file_path = u.Cli.auth_token_file_path(cli.settings.Cli.token_file)
return r[bool].ok(True)
Sources: examples/ex_05_authentication.py:32-48
Summary
The Authentication System provides a secure, result-oriented framework for managing CLI sessions. By centralizing credential validation and token persistence, it allows developers to implement robust security features with minimal boilerplate. The reliance on flext-core result types ensures that authentication failures are handled as data flows rather than exceptional events, leading to more stable and predictable CLI tools.
Sources: src/flext_cli/services/auth.py, examples/ex_05_authentication.py