Store JWT tokens securely for reuse across requests:
import osimport asynciofrom praisonai_platform.client import PlatformClientasync def persistent_auth(): client = PlatformClient("http://localhost:8000") # Check for existing token in environment stored_token = os.getenv('PLATFORM_AUTH_TOKEN') if not stored_token: # Register or login to get new token result = await client.login("user@example.com", "password") stored_token = result['token'] # Store token for future use os.environ['PLATFORM_AUTH_TOKEN'] = stored_token # Use stored token for requests client.set_token(stored_token) user_info = await client.get_current_user() print(f"Authenticated as: {user_info['name']}")asyncio.run(persistent_auth())
Error Handling for Auth Failures
Handle common authentication errors gracefully:
import httpximport asyncioasync def robust_auth(): async with httpx.AsyncClient(base_url="http://localhost:8000") as client: try: # Attempt login resp = await client.post("/api/v1/auth/login", json={ "email": "user@example.com", "password": "mypassword" }) resp.raise_for_status() token = resp.json()["token"] print(f"Authentication successful") except httpx.HTTPStatusError as e: if e.response.status_code == 401: print("Invalid credentials - check email/password") elif e.response.status_code == 404: print("User not found - register first") else: print(f"Authentication failed: {e}") except Exception as e: print(f"Network error: {e}")asyncio.run(robust_auth())
Multi-User Session Management
Manage authentication for multiple users in the same application:
import asynciofrom typing import Dictfrom praisonai_platform.client import PlatformClientclass MultiUserAuth: def __init__(self, base_url: str): self.base_url = base_url self.user_tokens: Dict[str, str] = {} async def authenticate_user(self, email: str, password: str): client = PlatformClient(self.base_url) # Check if user is already authenticated if email in self.user_tokens: return self.user_tokens[email] # Login and store token result = await client.login(email, password) self.user_tokens[email] = result['token'] return result['token'] async def get_user_client(self, email: str) -> PlatformClient: if email not in self.user_tokens: raise ValueError(f"User {email} not authenticated") client = PlatformClient(self.base_url) client.set_token(self.user_tokens[email]) return clientasync def multi_user_example(): auth_manager = MultiUserAuth("http://localhost:8000") # Authenticate multiple users await auth_manager.authenticate_user("admin@example.com", "admin_pass") await auth_manager.authenticate_user("user@example.com", "user_pass") # Use clients for different users admin_client = await auth_manager.get_user_client("admin@example.com") user_client = await auth_manager.get_user_client("user@example.com") admin_info = await admin_client.get_current_user() user_info = await user_client.get_current_user() print(f"Admin: {admin_info['name']}") print(f"User: {user_info['name']}")asyncio.run(multi_user_example())
Verify authentication functionality with comprehensive tests:
# Install test dependenciespip install praisonai-platform[test]# Run authentication service testspytest tests/test_services.py::TestAuthService -v# Run API integration tests pytest tests/test_api_integration.py::TestAuthErrors -v# Run all authentication testspytest tests/ -k "auth" -v
Tests require a running platform server instance. Start the server before running tests: