Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /promptdriven_pdd /context /auth_service_example.py
| """Example usage of pdd.auth_service for CLI commands. | |
| This module provides shared authentication helper functions for: | |
| - Checking authentication status (JWT cache, keyring tokens) | |
| - Clearing tokens (logout functionality) | |
| - Getting current auth state | |
| """ | |
| from pathlib import Path | |
| from typing import Optional, Tuple, Dict, Any | |
| # Constants for token storage locations | |
| JWT_CACHE_FILE = Path.home() / ".pdd" / "jwt_cache" | |
| KEYRING_SERVICE_NAME = "firebase-auth-PDD CLI" | |
| KEYRING_USER_NAME = "refresh_token" | |
| LEGACY_KEYRING_SERVICE_NAMES = ("firebase-auth-pdd",) | |
| def get_jwt_cache_info() -> Tuple[bool, Optional[float]]: | |
| """ | |
| Check JWT cache file for valid token. | |
| Returns: | |
| Tuple of (is_valid, expires_at). If valid, expires_at is the timestamp | |
| when the token expires. If invalid or not found, returns (False, None). | |
| """ | |
| ... | |
| def has_refresh_token() -> bool: | |
| """ | |
| Check if there's a stored refresh token in keyring. | |
| Keyring reads are wrapped with _keyring_op_with_timeout so `pdd auth status` | |
| does not hang when a desktop keychain is locked in CI or SSH. | |
| The current keyring service is checked first, followed by legacy services | |
| written by older server auth flows. | |
| Returns: | |
| True if a refresh token exists, False otherwise. | |
| """ | |
| ... | |
| def clear_jwt_cache() -> Tuple[bool, Optional[str]]: | |
| """ | |
| Clear the JWT cache file. | |
| Returns: | |
| Tuple of (success, error_message). If successful, error_message is None. | |
| """ | |
| ... | |
| def clear_refresh_token() -> Tuple[bool, Optional[str]]: | |
| """ | |
| Clear the refresh token from keyring. | |
| Keyring deletion is wrapped with _keyring_op_with_timeout so logout returns | |
| a clear timeout error instead of blocking indefinitely. | |
| Cleanup deletes both the current keyring service and legacy services written | |
| by older server auth flows. | |
| Returns: | |
| Tuple of (success, error_message). If successful, error_message is None. | |
| """ | |
| ... | |
| def get_auth_status() -> Dict[str, Any]: | |
| """ | |
| Get current authentication status. | |
| Returns: | |
| Dict with keys: | |
| - authenticated: bool - True if user has valid auth | |
| - cached: bool - True if using cached JWT (vs refresh token) | |
| - expires_at: Optional[float] - JWT expiration timestamp if cached | |
| - refresh_token_error: Optional[str] - present when keyring status is inconclusive | |
| """ | |
| ... | |
| def logout() -> Tuple[bool, Optional[str]]: | |
| """ | |
| Clear all authentication tokens (logout). | |
| Clears both the JWT cache file and the refresh token from keyring. | |
| Returns: | |
| Tuple of (success, error_message). If any error occurred, | |
| success is False and error_message contains the details. | |
| """ | |
| ... | |
| def get_refresh_token() -> Optional[str]: | |
| """ | |
| Get the stored refresh token from keyring. | |
| Tries standard keyring first, falls back to keyrings.alt.file.PlaintextKeyring. | |
| Keyring reads are bounded by _keyring_op_with_timeout so server-side auth | |
| routes do not hang in headless environments. | |
| The current keyring service is checked first, followed by legacy services | |
| written by older server auth flows. | |
| Returns: | |
| The refresh token string if found, None otherwise. | |
| """ | |
| ... | |
| async def verify_auth() -> Dict[str, Any]: | |
| """ | |
| Verify authentication by attempting to get a valid token. | |
| This function performs a deep validation of authentication state by | |
| actually attempting to refresh the token if the JWT is expired. | |
| Returns: | |
| Dict with keys: | |
| - valid: bool - True if we can get a valid token | |
| - error: Optional[str] - Error message if validation failed | |
| - needs_reauth: bool - True if user needs to re-login | |
| - username: Optional[str] - User email/identifier if available | |
| """ | |
| ... | |
| def get_cached_jwt() -> Optional[str]: | |
| """ | |
| Get the cached JWT token if it exists and is valid. | |
| Reads from JWT_CACHE_FILE, checks expiration with 5-minute buffer, | |
| and returns the token if valid. Supports both 'id_token' (new format) | |
| and 'jwt' (legacy format) keys for backwards compatibility. | |
| Returns: | |
| The JWT token string if valid, None otherwise. | |
| """ | |
| ... | |
| # Example usage in CLI commands: | |
| # | |
| # # In status command: | |
| # from pdd.auth_service import get_auth_status | |
| # status = get_auth_status() | |
| # if status["authenticated"]: | |
| # click.echo("Authenticated") | |
| # else: | |
| # click.echo("Not authenticated") | |
| # | |
| # # In logout command: | |
| # from pdd.auth_service import logout | |
| # success, error = logout() | |
| # if success: | |
| # click.echo("Logged out of PDD Cloud.") | |
| # else: | |
| # click.echo(f"Failed to logout: {error}", err=True) | |
| # | |
| # # Get cached JWT for API calls: | |
| # from pdd.auth_service import get_cached_jwt | |
| # token = get_cached_jwt() | |
| # if token: | |
| # headers = {"Authorization": f"Bearer {token}"} | |
| # # Make API call with headers | |
| # else: | |
| # click.echo("Not authenticated or token expired") | |
| # | |
| # # Get refresh token (for re-authentication flows): | |
| # from pdd.auth_service import get_refresh_token | |
| # refresh = get_refresh_token() | |
| # if refresh: | |
| # # Can attempt token refresh | |
| # pass | |
| # | |
| # # Deep verification with auto-refresh (async): | |
| # import asyncio | |
| # from pdd.auth_service import verify_auth | |
| # | |
| # async def check_auth(): | |
| # result = await verify_auth() | |
| # if result["valid"]: | |
| # click.echo(f"Authenticated as: {result['username']}") | |
| # elif result["needs_reauth"]: | |
| # click.echo(f"Please re-login: {result['error']}") | |
| # else: | |
| # click.echo(f"Temporary error: {result['error']}") | |
| # | |
| # asyncio.run(check_auth()) | |
Xet Storage Details
- Size:
- 5.63 kB
- Xet hash:
- cb3890680c862d565ba1b1897680c92b123b1950acdb88bad28711448609a31e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.