proxy-platform 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of proxy-platform might be problematic. Click here for more details.

@@ -0,0 +1,3 @@
1
+ """PBD CLI - Command line client for PBD APIs."""
2
+
3
+ __version__ = "0.2.0"
@@ -0,0 +1,324 @@
1
+ """HTTP client for PBD APIs."""
2
+
3
+ import base64
4
+ import json
5
+ import logging
6
+ from datetime import datetime, timedelta
7
+ from typing import Any
8
+
9
+ import requests
10
+ from rich.console import Console
11
+
12
+ from .config import (
13
+ get_api_urls,
14
+ get_default_api_type,
15
+ get_refresh_token,
16
+ get_token,
17
+ save_tokens,
18
+ )
19
+
20
+ console = Console()
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ class APIClient:
25
+ """HTTP client for making authenticated requests to PBD APIs."""
26
+
27
+ def __init__(self, api_type: str | None = None):
28
+ """Initialize the API client.
29
+
30
+ Args:
31
+ api_type: Either 'admin' or 'user'. If None, uses default from config.
32
+ """
33
+ self.api_type = api_type or get_default_api_type()
34
+ urls = get_api_urls()
35
+ self.base_url = urls[f"{self.api_type}_api"]
36
+ self._token_refreshed = False # Prevent infinite refresh loops
37
+
38
+ def _is_token_expired(self, token: str) -> bool:
39
+ """Check if a JWT token is expired or close to expiring."""
40
+ try:
41
+ payload = token.split(".")[1]
42
+ # Add padding if needed
43
+ payload += "=" * (-len(payload) % 4)
44
+ decoded = json.loads(base64.urlsafe_b64decode(payload))
45
+
46
+ exp = decoded.get("exp")
47
+ if not exp:
48
+ return False
49
+
50
+ return datetime.fromtimestamp(exp) < (datetime.now() + timedelta(minutes=1))
51
+
52
+ except Exception:
53
+ return False
54
+
55
+ def _refresh_access_token(self) -> bool:
56
+ """Try to refresh the access token using refresh token.
57
+
58
+ Returns:
59
+ True if refresh successful, False otherwise
60
+ """
61
+ if self._token_refreshed:
62
+ # Already tried to refresh in this request, prevent loop
63
+ return False
64
+
65
+ refresh_token = get_refresh_token(self.api_type)
66
+ if not refresh_token:
67
+ return False
68
+
69
+ try:
70
+ # Call refresh endpoint
71
+ response = requests.post(
72
+ f"{self.base_url}/api/v1/auth/refresh",
73
+ headers={
74
+ "Authorization": f"Bearer {refresh_token}",
75
+ "Content-Type": "application/json",
76
+ },
77
+ timeout=10,
78
+ )
79
+
80
+ if response.status_code == 200:
81
+ data = response.json()
82
+
83
+ # Handle both dict response and string response
84
+ if isinstance(data, dict):
85
+ new_access_token = data.get("access_token")
86
+ new_refresh_token = data.get("refresh_token")
87
+ elif isinstance(data, str):
88
+ # API returned a plain token string
89
+ new_access_token = data
90
+ new_refresh_token = None
91
+ else:
92
+ console.print(f"[dim]Unexpected refresh response type: {type(data)}[/dim]")
93
+ return False
94
+
95
+ if new_access_token:
96
+ # Save new tokens
97
+ if self.api_type == "admin":
98
+ save_tokens(
99
+ admin_token=new_access_token,
100
+ admin_refresh=new_refresh_token,
101
+ )
102
+ else:
103
+ save_tokens(
104
+ user_token=new_access_token,
105
+ user_refresh=new_refresh_token,
106
+ )
107
+
108
+ self._token_refreshed = True
109
+ console.print("[dim]✓ Token refreshed[/dim]")
110
+ return True
111
+
112
+ return False
113
+
114
+ except Exception as e:
115
+ console.print(f"[dim]Token refresh failed: {str(e)}[/dim]")
116
+ return False
117
+
118
+ def _get_headers(self) -> dict[str, str]:
119
+ """Get headers including authentication token."""
120
+ headers = {
121
+ "Content-Type": "application/json",
122
+ "Accept": "application/json",
123
+ }
124
+
125
+ token = get_token(self.api_type)
126
+ if token:
127
+ headers["Authorization"] = f"Bearer {token}"
128
+
129
+ return headers
130
+
131
+ def request(
132
+ self,
133
+ method: str,
134
+ endpoint: str,
135
+ data: dict[str, Any] | None = None,
136
+ params: dict[str, Any] | None = None,
137
+ require_auth: bool = True,
138
+ extra_headers: dict[str, str] | None = None,
139
+ ) -> requests.Response:
140
+ """Make an HTTP request to the API.
141
+
142
+ Args:
143
+ method: HTTP method (GET, POST, PUT, DELETE, etc.)
144
+ endpoint: API endpoint (e.g., '/api/v1/users/profile')
145
+ data: JSON data to send in the request body
146
+ params: Query parameters
147
+ require_auth: Whether this endpoint requires authentication
148
+
149
+ Returns:
150
+ requests.Response object
151
+
152
+ Raises:
153
+ Exception if authentication is required but no token is found
154
+ """
155
+ if require_auth:
156
+ token = get_token(self.api_type)
157
+ if not token:
158
+ raise Exception(f"Not authenticated. Please run 'pbd login --api {self.api_type}' first.")
159
+
160
+ # Check if token is expired and try to refresh
161
+ if self._is_token_expired(token):
162
+ if not self._refresh_access_token():
163
+ raise Exception(f"Token expired. Please run 'pbd login --api {self.api_type}' to re-authenticate.")
164
+
165
+ url = f"{self.base_url}{endpoint}"
166
+ headers = self._get_headers()
167
+ if extra_headers:
168
+ headers.update(extra_headers)
169
+
170
+ # Log the request details in verbose mode
171
+ logger.debug(f"→ {method} {url}")
172
+ if params:
173
+ logger.debug(f" Query params: {params}")
174
+ if data:
175
+ logger.debug(f" Request body: {data}")
176
+
177
+ try:
178
+ response = requests.request(
179
+ method=method,
180
+ url=url,
181
+ headers=headers,
182
+ json=data,
183
+ params=params,
184
+ timeout=30,
185
+ )
186
+
187
+ # Log the response in verbose mode
188
+ logger.debug(f"← {response.status_code} {response.reason}")
189
+ if response.status_code >= 400:
190
+ logger.debug(f" Error response: {response.text[:200]}")
191
+
192
+ return response
193
+ except requests.exceptions.ConnectionError:
194
+ logger.error(f"Connection failed to {self.base_url}")
195
+ console.print(f"[red]Error: Could not connect to {self.base_url}[/red]")
196
+ console.print("[yellow]Make sure the API server is running.[/yellow]")
197
+ raise
198
+ except requests.exceptions.Timeout:
199
+ console.print("[red]Error: Request timed out[/red]")
200
+ raise
201
+
202
+ def get(self, endpoint: str, params: dict[str, Any] | None = None, require_auth: bool = True) -> requests.Response:
203
+ """Make a GET request."""
204
+ return self.request("GET", endpoint, params=params, require_auth=require_auth)
205
+
206
+ def post(self, endpoint: str, data: dict[str, Any] | None = None, require_auth: bool = True) -> requests.Response:
207
+ """Make a POST request."""
208
+ return self.request("POST", endpoint, data=data, require_auth=require_auth)
209
+
210
+ def put(self, endpoint: str, data: dict[str, Any] | None = None, require_auth: bool = True) -> requests.Response:
211
+ """Make a PUT request."""
212
+ return self.request("PUT", endpoint, data=data, require_auth=require_auth)
213
+
214
+ def patch(self, endpoint: str, data: dict[str, Any] | None = None, require_auth: bool = True) -> requests.Response:
215
+ """Make a PATCH request."""
216
+ return self.request("PATCH", endpoint, data=data, require_auth=require_auth)
217
+
218
+ def delete(self, endpoint: str, require_auth: bool = True) -> requests.Response:
219
+ """Make a DELETE request."""
220
+ return self.request("DELETE", endpoint, require_auth=require_auth)
221
+
222
+ def upload(
223
+ self,
224
+ endpoint: str,
225
+ files: dict[str, tuple[str, Any, str]],
226
+ data: dict[str, Any] | None = None,
227
+ require_auth: bool = True,
228
+ ) -> requests.Response:
229
+ """Upload files to the API.
230
+
231
+ Args:
232
+ endpoint: API endpoint
233
+ files: Dict of file field names to (filename, file_object, content_type) tuples
234
+ data: Optional additional form data
235
+ require_auth: Whether authentication is required
236
+
237
+ Returns:
238
+ requests.Response object
239
+ """
240
+ if require_auth:
241
+ token = get_token(self.api_type)
242
+ if not token:
243
+ raise Exception(f"Not authenticated. Please run 'pbd login --api {self.api_type}' first.")
244
+
245
+ # Check if token is expired and try to refresh
246
+ if self._is_token_expired(token):
247
+ if not self._refresh_access_token():
248
+ raise Exception(f"Token expired. Please run 'pbd login --api {self.api_type}' to re-authenticate.")
249
+
250
+ url = f"{self.base_url}{endpoint}"
251
+
252
+ # Get auth headers but don't set Content-Type (requests will set it for multipart)
253
+ headers = {}
254
+ token = get_token(self.api_type)
255
+ if token:
256
+ headers["Authorization"] = f"Bearer {token}"
257
+
258
+ try:
259
+ response = requests.post(
260
+ url=url,
261
+ headers=headers,
262
+ files=files,
263
+ data=data,
264
+ timeout=30,
265
+ )
266
+
267
+ logger.debug(f"← {response.status_code} {response.reason}")
268
+ if response.status_code >= 400:
269
+ logger.debug(f" Error response: {response.text[:200]}")
270
+
271
+ return response
272
+ except requests.exceptions.ConnectionError:
273
+ logger.error(f"Connection failed to {self.base_url}")
274
+ console.print(f"[red]Error: Could not connect to {self.base_url}[/red]")
275
+ console.print("[yellow]Make sure the API server is running.[/yellow]")
276
+ raise
277
+ except requests.exceptions.Timeout:
278
+ console.print("[red]Error: Request timed out[/red]")
279
+ raise
280
+
281
+ def login(self, username: str, password: str, otp_code: str | None = None) -> dict[str, Any]:
282
+ """Authenticate and return tokens.
283
+
284
+ Args:
285
+ username: User's email
286
+ password: User's password
287
+
288
+ Returns:
289
+ Dict containing access_token and refresh_token
290
+
291
+ Raises:
292
+ Exception if login fails
293
+ """
294
+ extra: dict[str, str] | None = {"X-OTP": otp_code} if otp_code else None
295
+ response = self.request(
296
+ "POST",
297
+ "/api/v1/auth/login",
298
+ data={"username": username, "password": password},
299
+ require_auth=False,
300
+ extra_headers=extra,
301
+ )
302
+
303
+ if response.status_code == 200:
304
+ data = response.json()
305
+
306
+ # Handle both dict response and string response
307
+ if isinstance(data, dict):
308
+ return data # Return full response with both tokens
309
+ elif isinstance(data, str):
310
+ # API returned a plain token string
311
+ return {"access_token": data, "refresh_token": None} # nosec B105
312
+ else:
313
+ # Unexpected response type
314
+ return {"access_token": None, "refresh_token": None} # nosec B105
315
+ else:
316
+ try:
317
+ error_data = response.json()
318
+ if isinstance(error_data, dict):
319
+ error_detail = error_data.get("detail", "Unknown error")
320
+ else:
321
+ error_detail = str(error_data)
322
+ except Exception:
323
+ error_detail = response.text if response.text else "Unknown error"
324
+ raise Exception(f"Login failed: {error_detail}")
@@ -0,0 +1 @@
1
+ """Command modules for PBD CLI."""
@@ -0,0 +1,151 @@
1
+ """Authentication commands."""
2
+
3
+ import typer
4
+ from rich.console import Console
5
+ from rich.prompt import Prompt
6
+
7
+ from ..client import APIClient
8
+ from ..config import (
9
+ clear_tokens,
10
+ get_current_environment,
11
+ get_default_api_type,
12
+ save_tokens,
13
+ set_default_api_type,
14
+ )
15
+
16
+ app = typer.Typer()
17
+ console = Console()
18
+
19
+
20
+ @app.command()
21
+ def login(
22
+ email: str | None = typer.Option(None, "--email", "-e", help="Email address"),
23
+ password: str | None = typer.Option(None, "--password", "-p", help="Password", hide_input=True),
24
+ api: str = typer.Option("user", "--api", "-a", help="API type (admin or user)"),
25
+ ) -> None:
26
+ """Login to the PBD API.
27
+
28
+ Authenticate and store the access token for future requests.
29
+ """
30
+ if api not in ["admin", "user"]:
31
+ console.print("[red]Error: API type must be 'admin' or 'user'[/red]")
32
+ raise typer.Exit(1)
33
+
34
+ env = get_current_environment()
35
+ console.print(f"Logging in to [cyan]{api}[/cyan] API ([yellow]{env}[/yellow])...")
36
+ console.print()
37
+
38
+ # Prompt for credentials if not provided
39
+ email_str: str = email if email else Prompt.ask("Email")
40
+ password_str: str = password if password else Prompt.ask("Password", password=True)
41
+
42
+ try:
43
+ client = APIClient(api_type=api)
44
+ try:
45
+ result = client.login(email_str, password_str)
46
+ except Exception as e:
47
+ if "OTP required" in str(e) or "X-OTP" in str(e):
48
+ console.print("[yellow]Two-factor authentication required.[/yellow]")
49
+ otp_code = Prompt.ask("OTP code")
50
+ result = client.login(email_str, password_str, otp_code=otp_code)
51
+ else:
52
+ raise
53
+
54
+ # Result contains both access_token and refresh_token
55
+ access_token: str | None = result.get("access_token")
56
+ refresh_token: str | None = result.get("refresh_token")
57
+
58
+ # Save the tokens
59
+ if api == "admin":
60
+ save_tokens(admin_token=access_token, admin_refresh=refresh_token)
61
+ else:
62
+ save_tokens(user_token=access_token, user_refresh=refresh_token)
63
+
64
+ # Set as default API type
65
+ set_default_api_type(api)
66
+
67
+ console.print()
68
+ console.print("[green]✓[/green] Login successful!")
69
+ console.print(f"Authenticated as: [cyan]{email_str}[/cyan]")
70
+ console.print(f"API type: [cyan]{api}[/cyan]")
71
+ console.print(f"Environment: [yellow]{env}[/yellow]")
72
+ if refresh_token:
73
+ console.print("[dim]✓ Auto-refresh enabled[/dim]")
74
+
75
+ except Exception as e:
76
+ console.print(f"[red]✗ Login failed: {str(e)}[/red]")
77
+ raise typer.Exit(1) from None
78
+
79
+
80
+ @app.command()
81
+ def logout() -> None:
82
+ """Logout from the PBD API.
83
+
84
+ Clear stored authentication tokens.
85
+ """
86
+ clear_tokens()
87
+ console.print("[green]✓[/green] Logged out successfully")
88
+
89
+
90
+ @app.command()
91
+ def whoami(
92
+ api: str | None = typer.Option(
93
+ None, "--api", "-a", help="API type (admin or user). Uses default if not specified."
94
+ ),
95
+ ) -> None:
96
+ """Show current user information.
97
+
98
+ Display information about the currently authenticated user.
99
+ """
100
+ if api is None:
101
+ api = get_default_api_type()
102
+
103
+ if api not in ["admin", "user"]:
104
+ console.print("[red]Error: API type must be 'admin' or 'user'[/red]")
105
+ raise typer.Exit(1)
106
+
107
+ try:
108
+ client = APIClient(api_type=api)
109
+ response = client.get("/api/v1/users/profile")
110
+
111
+ if response.status_code == 200:
112
+ user = response.json()
113
+ env = get_current_environment()
114
+
115
+ console.print()
116
+ console.print("[bold]Current User Information[/bold]")
117
+ console.print("─" * 50)
118
+ console.print(f"Name: [cyan]{user.get('first_name', '')} {user.get('last_name', '')}[/cyan]")
119
+ console.print(f"Email: [cyan]{user.get('email', 'N/A')}[/cyan]")
120
+ console.print(f"User ID: [cyan]{user.get('id', 'N/A')}[/cyan]")
121
+ console.print(f"API Type: [cyan]{api}[/cyan]")
122
+ console.print(f"Environment: [yellow]{env}[/yellow]")
123
+
124
+ if user.get("is_admin"):
125
+ console.print("Role: [magenta]Admin[/magenta]")
126
+
127
+ console.print()
128
+ else:
129
+ console.print(f"[red]Error: {response.status_code}[/red]")
130
+ console.print(response.json().get("detail", "Unknown error"))
131
+ raise typer.Exit(1)
132
+
133
+ except Exception as e:
134
+ console.print(f"[red]Error: {str(e)}[/red]")
135
+ raise typer.Exit(1) from None
136
+
137
+
138
+ @app.command()
139
+ def switch(
140
+ api: str = typer.Argument(..., help="API type to switch to (admin or user)"),
141
+ ) -> None:
142
+ """Switch default API type.
143
+
144
+ Change the default API type for subsequent commands.
145
+ """
146
+ if api not in ["admin", "user"]:
147
+ console.print("[red]Error: API type must be 'admin' or 'user'[/red]")
148
+ raise typer.Exit(1)
149
+
150
+ set_default_api_type(api)
151
+ console.print(f"[green]✓[/green] Switched to [bold cyan]{api}[/bold cyan] API")