Skip to content

Commit 4ab8cc7

Browse files
committed
Handle already logged in state
1 parent 0296882 commit 4ab8cc7

1 file changed

Lines changed: 27 additions & 1 deletion

File tree

src/fastapi_cloud_cli/commands/login.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from fastapi_cloud_cli.config import Settings
1010
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
1212
from fastapi_cloud_cli.utils.cli import get_rich_toolkit, handle_http_errors
1313

1414
logger = logging.getLogger(__name__)
@@ -72,10 +72,36 @@ def _fetch_access_token(client: httpx.Client, device_code: str, interval: int) -
7272
return response_data.access_token
7373

7474

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+
7589
def login() -> Any:
7690
"""
7791
Login to FastAPI Cloud. 🚀
7892
"""
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+
79105
with get_rich_toolkit() as toolkit, APIClient() as client:
80106
toolkit.print_title("Login to FastAPI Cloud", tag="FastAPI")
81107

0 commit comments

Comments
 (0)