|
8 | 8 |
|
9 | 9 | from fastapi_cloud_cli.config import Settings |
10 | 10 | from fastapi_cloud_cli.utils.api import APIClient |
11 | | -from fastapi_cloud_cli.utils.auth import AuthConfig, write_auth_config |
| 11 | +from fastapi_cloud_cli.utils.auth import AuthConfig, is_logged_in, write_auth_config |
12 | 12 | from fastapi_cloud_cli.utils.cli import get_rich_toolkit, handle_http_errors |
13 | 13 |
|
14 | 14 | logger = logging.getLogger(__name__) |
@@ -72,10 +72,36 @@ def _fetch_access_token(client: httpx.Client, device_code: str, interval: int) - |
72 | 72 | return response_data.access_token |
73 | 73 |
|
74 | 74 |
|
| 75 | +def _verify_token(client: httpx.Client) -> tuple[bool, str | None]: |
| 76 | + try: |
| 77 | + response = client.get("/users/me") |
| 78 | + response.raise_for_status() |
| 79 | + data = response.json() |
| 80 | + return True, data.get("email") |
| 81 | + except httpx.HTTPStatusError as e: |
| 82 | + if e.response.status_code in (401, 403): |
| 83 | + return False, None |
| 84 | + raise |
| 85 | + except Exception: |
| 86 | + return False, None |
| 87 | + |
| 88 | + |
75 | 89 | def login() -> Any: |
76 | 90 | """ |
77 | 91 | Login to FastAPI Cloud. 🚀 |
78 | 92 | """ |
| 93 | + if is_logged_in(): |
| 94 | + with APIClient() as client: |
| 95 | + is_valid, email = _verify_token(client) |
| 96 | + |
| 97 | + if is_valid: |
| 98 | + with get_rich_toolkit(minimal=True) as toolkit: |
| 99 | + toolkit.print(f"Already logged in as [bold]{email}[/bold]") |
| 100 | + toolkit.print( |
| 101 | + "Run [bold]fastapi logout[/bold] first if you want to switch accounts." |
| 102 | + ) |
| 103 | + return |
| 104 | + |
79 | 105 | with get_rich_toolkit() as toolkit, APIClient() as client: |
80 | 106 | toolkit.print_title("Login to FastAPI Cloud", tag="FastAPI") |
81 | 107 |
|
|
0 commit comments