chdev 1.2.1__tar.gz → 1.4.0__tar.gz
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.
- {chdev-1.2.1 → chdev-1.4.0}/PKG-INFO +1 -1
- {chdev-1.2.1 → chdev-1.4.0}/pyproject.toml +1 -1
- chdev-1.4.0/src/chdev/__init__.py +880 -0
- chdev-1.4.0/src/chdev/aio.py +10 -0
- {chdev-1.2.1 → chdev-1.4.0}/src/chdev.egg-info/PKG-INFO +1 -1
- {chdev-1.2.1 → chdev-1.4.0}/src/chdev.egg-info/SOURCES.txt +1 -0
- chdev-1.2.1/src/chdev/__init__.py +0 -428
- {chdev-1.2.1 → chdev-1.4.0}/README.md +0 -0
- {chdev-1.2.1 → chdev-1.4.0}/setup.cfg +0 -0
- {chdev-1.2.1 → chdev-1.4.0}/src/chdev.egg-info/dependency_links.txt +0 -0
- {chdev-1.2.1 → chdev-1.4.0}/src/chdev.egg-info/top_level.txt +0 -0
- {chdev-1.2.1 → chdev-1.4.0}/src/chdevauth/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: chdev
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.0
|
|
4
4
|
Summary: Official Python client library for chdev Authentication (SSO for Google, Discord, Microsoft)
|
|
5
5
|
Author-email: chdev <contact@chdev.co.uk>
|
|
6
6
|
Project-URL: Homepage, https://authentication.chdev.co.uk
|
|
@@ -0,0 +1,880 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import builtins
|
|
5
|
+
import functools
|
|
6
|
+
import http.server
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import secrets
|
|
10
|
+
import socketserver
|
|
11
|
+
import sys
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.parse
|
|
16
|
+
import urllib.request
|
|
17
|
+
import webbrowser
|
|
18
|
+
from typing import Any, Callable, Dict, List, Optional, Union
|
|
19
|
+
|
|
20
|
+
__version__ = "1.4.0"
|
|
21
|
+
__all__ = [
|
|
22
|
+
# Core Synchronous Logins
|
|
23
|
+
"google_login",
|
|
24
|
+
"discord_login",
|
|
25
|
+
"microsoft_login",
|
|
26
|
+
"login",
|
|
27
|
+
"prompt_login",
|
|
28
|
+
"ask_login",
|
|
29
|
+
"cached_login",
|
|
30
|
+
# Async Logins
|
|
31
|
+
"login_async",
|
|
32
|
+
"prompt_login_async",
|
|
33
|
+
"google_login_async",
|
|
34
|
+
"discord_login_async",
|
|
35
|
+
"microsoft_login_async",
|
|
36
|
+
"cached_login_async",
|
|
37
|
+
# Decorators & Guards
|
|
38
|
+
"require_auth",
|
|
39
|
+
"login_required",
|
|
40
|
+
"allowed_users",
|
|
41
|
+
"require_user",
|
|
42
|
+
# Session Management
|
|
43
|
+
"get_user",
|
|
44
|
+
"logout",
|
|
45
|
+
"show_qr",
|
|
46
|
+
# Backend Web Helpers
|
|
47
|
+
"create_session",
|
|
48
|
+
"verify",
|
|
49
|
+
# Configuration & State
|
|
50
|
+
"set_key",
|
|
51
|
+
"api_key",
|
|
52
|
+
"email",
|
|
53
|
+
"pfp",
|
|
54
|
+
"picture",
|
|
55
|
+
"name",
|
|
56
|
+
"user",
|
|
57
|
+
"user_id",
|
|
58
|
+
"authenticated",
|
|
59
|
+
"AuthUser",
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
BASE_URL = "https://authentication.chdev.co.uk"
|
|
63
|
+
AUTH_ENDPOINT = f"{BASE_URL}/api/cli-auth"
|
|
64
|
+
CACHE_DIR = os.path.expanduser("~/.chdev")
|
|
65
|
+
CACHE_FILE = os.path.join(CACHE_DIR, "session.json")
|
|
66
|
+
|
|
67
|
+
api_key: Optional[str] = None
|
|
68
|
+
email: Optional[str] = None
|
|
69
|
+
pfp: Optional[str] = None
|
|
70
|
+
picture: Optional[str] = None
|
|
71
|
+
name: Optional[str] = None
|
|
72
|
+
user_id: Optional[str] = None
|
|
73
|
+
user: Optional[Dict[str, Any]] = None
|
|
74
|
+
authenticated: bool = False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class AuthUser(str):
|
|
78
|
+
"""String subclass representing an authenticated user, defaulting to their email."""
|
|
79
|
+
email: str
|
|
80
|
+
pfp: str
|
|
81
|
+
picture: str
|
|
82
|
+
name: str
|
|
83
|
+
id: str
|
|
84
|
+
user_id: str
|
|
85
|
+
provider: str
|
|
86
|
+
user: Dict[str, Any]
|
|
87
|
+
|
|
88
|
+
def __new__(cls, user_data: Dict[str, Any]):
|
|
89
|
+
user_email = user_data.get("email") or ""
|
|
90
|
+
obj = super().__new__(cls, user_email)
|
|
91
|
+
obj.email = user_email
|
|
92
|
+
obj.pfp = user_data.get("pfp") or user_data.get("picture") or ""
|
|
93
|
+
obj.picture = obj.pfp
|
|
94
|
+
obj.name = user_data.get("name") or ""
|
|
95
|
+
obj.id = str(user_data.get("id") or "")
|
|
96
|
+
obj.user_id = obj.id
|
|
97
|
+
obj.provider = user_data.get("provider") or "google"
|
|
98
|
+
obj.user = user_data
|
|
99
|
+
return obj
|
|
100
|
+
|
|
101
|
+
def __getitem__(self, item: Any) -> Any:
|
|
102
|
+
if isinstance(item, str):
|
|
103
|
+
return self.user.get(item)
|
|
104
|
+
return super().__getitem__(item)
|
|
105
|
+
|
|
106
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
107
|
+
return self.user.get(key, default)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def set_key(key: str) -> None:
|
|
111
|
+
"""Set the global API key used for all chdev authentication requests."""
|
|
112
|
+
global api_key
|
|
113
|
+
k = (key or "").strip()
|
|
114
|
+
api_key = k
|
|
115
|
+
if k:
|
|
116
|
+
os.environ["CHDEV_AUTH_SECRET_KEY"] = k
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _get_key(key: Optional[str] = None) -> str:
|
|
120
|
+
k = (key or api_key or os.environ.get("CHDEV_AUTH_SECRET_KEY") or "").strip()
|
|
121
|
+
if not k:
|
|
122
|
+
sys.exit("Invalid key.")
|
|
123
|
+
return k
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _set_globals(res: Dict[str, Any]) -> AuthUser:
|
|
127
|
+
global email, pfp, picture, name, user, user_id, authenticated
|
|
128
|
+
|
|
129
|
+
user_data = res.get("user") or {}
|
|
130
|
+
auth_user = AuthUser(user_data)
|
|
131
|
+
|
|
132
|
+
user_email = auth_user.email
|
|
133
|
+
user_pfp = auth_user.pfp
|
|
134
|
+
user_name = auth_user.name
|
|
135
|
+
user_raw_id = auth_user.id
|
|
136
|
+
|
|
137
|
+
email = user_email
|
|
138
|
+
pfp = user_pfp
|
|
139
|
+
picture = user_pfp
|
|
140
|
+
name = user_name
|
|
141
|
+
user_id = user_raw_id
|
|
142
|
+
user = user_data
|
|
143
|
+
authenticated = True
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
frame = sys._getframe(1)
|
|
147
|
+
while frame and frame.f_globals.get("__name__") in (__name__, "chdev", "chdevauth", "chdev.aio"):
|
|
148
|
+
frame = frame.f_back
|
|
149
|
+
if frame:
|
|
150
|
+
frame.f_globals["email"] = user_email
|
|
151
|
+
frame.f_globals["pfp"] = user_pfp
|
|
152
|
+
frame.f_globals["picture"] = user_pfp
|
|
153
|
+
frame.f_globals["name"] = user_name
|
|
154
|
+
frame.f_globals["user_id"] = user_raw_id
|
|
155
|
+
frame.f_globals["user"] = user_data
|
|
156
|
+
frame.f_globals["authenticated"] = True
|
|
157
|
+
except Exception:
|
|
158
|
+
pass
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
builtins.email = user_email
|
|
162
|
+
builtins.pfp = user_pfp
|
|
163
|
+
builtins.picture = user_pfp
|
|
164
|
+
builtins.name = user_name
|
|
165
|
+
builtins.user_id = user_raw_id
|
|
166
|
+
builtins.user = user_data
|
|
167
|
+
builtins.authenticated = True
|
|
168
|
+
except Exception:
|
|
169
|
+
pass
|
|
170
|
+
|
|
171
|
+
return auth_user
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _post_json(
|
|
175
|
+
url: str,
|
|
176
|
+
payload: Dict[str, Any],
|
|
177
|
+
timeout: int = 15,
|
|
178
|
+
headers: Optional[Dict[str, str]] = None
|
|
179
|
+
) -> Dict[str, Any]:
|
|
180
|
+
req_headers = {
|
|
181
|
+
"Content-Type": "application/json",
|
|
182
|
+
"User-Agent": f"chdev-python/{__version__}"
|
|
183
|
+
}
|
|
184
|
+
if headers:
|
|
185
|
+
req_headers.update(headers)
|
|
186
|
+
|
|
187
|
+
req = urllib.request.Request(
|
|
188
|
+
url,
|
|
189
|
+
data=json.dumps(payload).encode("utf-8"),
|
|
190
|
+
headers=req_headers
|
|
191
|
+
)
|
|
192
|
+
try:
|
|
193
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
194
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
195
|
+
except urllib.error.HTTPError as e:
|
|
196
|
+
if e.code in (401, 403):
|
|
197
|
+
sys.exit("Invalid key.")
|
|
198
|
+
try:
|
|
199
|
+
err_body = json.loads(e.read().decode("utf-8"))
|
|
200
|
+
msg = err_body.get("message") or err_body.get("error") or f"HTTP {e.code}"
|
|
201
|
+
sys.exit(f"Request failed: {msg}")
|
|
202
|
+
except Exception:
|
|
203
|
+
sys.exit(f"Request failed ({e.code}).")
|
|
204
|
+
except urllib.error.URLError as e:
|
|
205
|
+
sys.exit(f"Connection error: {e.reason}")
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# ==============================================================================
|
|
209
|
+
# LOCAL SESSION CACHING
|
|
210
|
+
# ==============================================================================
|
|
211
|
+
|
|
212
|
+
def _save_cache(user_data: Dict[str, Any]) -> None:
|
|
213
|
+
try:
|
|
214
|
+
os.makedirs(CACHE_DIR, exist_ok=True)
|
|
215
|
+
payload = {
|
|
216
|
+
"saved_at": time.time(),
|
|
217
|
+
"user": user_data
|
|
218
|
+
}
|
|
219
|
+
with open(CACHE_FILE, "w", encoding="utf-8") as f:
|
|
220
|
+
json.dump(payload, f, indent=2)
|
|
221
|
+
except Exception:
|
|
222
|
+
pass
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def get_user(max_age_days: int = 7) -> Optional[AuthUser]:
|
|
226
|
+
"""Retrieve the locally cached authenticated user if not expired."""
|
|
227
|
+
if not os.path.isfile(CACHE_FILE):
|
|
228
|
+
return None
|
|
229
|
+
try:
|
|
230
|
+
with open(CACHE_FILE, "r", encoding="utf-8") as f:
|
|
231
|
+
data = json.load(f)
|
|
232
|
+
saved_at = float(data.get("saved_at", 0))
|
|
233
|
+
max_age_seconds = max_age_days * 86400
|
|
234
|
+
if time.time() - saved_at > max_age_seconds:
|
|
235
|
+
logout()
|
|
236
|
+
return None
|
|
237
|
+
cached_user = data.get("user")
|
|
238
|
+
if cached_user and isinstance(cached_user, dict):
|
|
239
|
+
return _set_globals({"user": cached_user})
|
|
240
|
+
except Exception:
|
|
241
|
+
pass
|
|
242
|
+
return None
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def logout() -> bool:
|
|
246
|
+
"""Clear the local session cache and reset authenticated global variables."""
|
|
247
|
+
global email, pfp, picture, name, user, user_id, authenticated
|
|
248
|
+
email = None
|
|
249
|
+
pfp = None
|
|
250
|
+
picture = None
|
|
251
|
+
name = None
|
|
252
|
+
user = None
|
|
253
|
+
user_id = None
|
|
254
|
+
authenticated = False
|
|
255
|
+
try:
|
|
256
|
+
if os.path.exists(CACHE_FILE):
|
|
257
|
+
os.remove(CACHE_FILE)
|
|
258
|
+
return True
|
|
259
|
+
except Exception:
|
|
260
|
+
pass
|
|
261
|
+
return False
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def cached_login(
|
|
265
|
+
key: Optional[str] = None,
|
|
266
|
+
provider: str = "google",
|
|
267
|
+
app_name: str = "Python Application",
|
|
268
|
+
max_age_days: int = 7,
|
|
269
|
+
open_browser: bool = True,
|
|
270
|
+
poll_interval: float = 1.0,
|
|
271
|
+
timeout: int = 300,
|
|
272
|
+
quiet: bool = False,
|
|
273
|
+
qr: bool = False,
|
|
274
|
+
loopback: bool = True
|
|
275
|
+
) -> AuthUser:
|
|
276
|
+
"""Return the cached user if valid; otherwise prompt login and save the session."""
|
|
277
|
+
cached = get_user(max_age_days=max_age_days)
|
|
278
|
+
if cached:
|
|
279
|
+
if not quiet:
|
|
280
|
+
print(f"Loaded cached session for {cached.email or cached.name}!")
|
|
281
|
+
return cached
|
|
282
|
+
|
|
283
|
+
return login(
|
|
284
|
+
key=key,
|
|
285
|
+
provider=provider,
|
|
286
|
+
app_name=app_name,
|
|
287
|
+
open_browser=open_browser,
|
|
288
|
+
poll_interval=poll_interval,
|
|
289
|
+
timeout=timeout,
|
|
290
|
+
quiet=quiet,
|
|
291
|
+
save_session=True,
|
|
292
|
+
qr=qr,
|
|
293
|
+
loopback=loopback
|
|
294
|
+
)
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
# ==============================================================================
|
|
298
|
+
# TERMINAL ASCII QR CODE
|
|
299
|
+
# ==============================================================================
|
|
300
|
+
|
|
301
|
+
def show_qr(url: str) -> None:
|
|
302
|
+
"""Render an ASCII QR code for a sign-in URL directly in the terminal."""
|
|
303
|
+
try:
|
|
304
|
+
import qrcode
|
|
305
|
+
qr_obj = qrcode.QRCode()
|
|
306
|
+
qr_obj.add_data(url)
|
|
307
|
+
qr_obj.print_ascii(invert=True)
|
|
308
|
+
return
|
|
309
|
+
except Exception:
|
|
310
|
+
pass
|
|
311
|
+
|
|
312
|
+
try:
|
|
313
|
+
qr_api_url = f"{BASE_URL}/api/qr?url=" + urllib.parse.quote(url)
|
|
314
|
+
req = urllib.request.Request(qr_api_url, headers={"User-Agent": "chdev-python-cli"})
|
|
315
|
+
with urllib.request.urlopen(req, timeout=3) as resp:
|
|
316
|
+
ascii_qr = resp.read().decode("utf-8")
|
|
317
|
+
if ascii_qr:
|
|
318
|
+
print(ascii_qr)
|
|
319
|
+
except Exception:
|
|
320
|
+
pass
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
# ==============================================================================
|
|
324
|
+
# EMAIL / USER PERMISSION GUARD
|
|
325
|
+
# ==============================================================================
|
|
326
|
+
|
|
327
|
+
def allowed_users(
|
|
328
|
+
users: Union[str, List[str]],
|
|
329
|
+
*,
|
|
330
|
+
key: Optional[str] = None,
|
|
331
|
+
provider: str = "google",
|
|
332
|
+
app_name: str = "Python Application",
|
|
333
|
+
**login_kwargs: Any
|
|
334
|
+
) -> Callable[..., Any]:
|
|
335
|
+
"""Decorator restricting function execution to a specific list of allowed emails or IDs."""
|
|
336
|
+
if isinstance(users, str):
|
|
337
|
+
allowed_list = [users.strip().lower()]
|
|
338
|
+
else:
|
|
339
|
+
allowed_list = [u.strip().lower() for u in users]
|
|
340
|
+
|
|
341
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
342
|
+
@functools.wraps(func)
|
|
343
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
344
|
+
global authenticated
|
|
345
|
+
if not authenticated:
|
|
346
|
+
login(key=key, provider=provider, app_name=app_name, **login_kwargs)
|
|
347
|
+
|
|
348
|
+
user_email = (email or "").lower()
|
|
349
|
+
current_id = str(user_id or "")
|
|
350
|
+
discord_tag = str(user.get("discord_username", "") if user else "").lower()
|
|
351
|
+
|
|
352
|
+
if user_email in allowed_list or current_id in allowed_list or discord_tag in allowed_list:
|
|
353
|
+
return func(*args, **kwargs)
|
|
354
|
+
|
|
355
|
+
sys.exit(f"Access denied: '{user_email or current_id}' is not in the allowed users list.")
|
|
356
|
+
return wrapper
|
|
357
|
+
return decorator
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
require_user = allowed_users
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
# ==============================================================================
|
|
364
|
+
# ZERO-PING LOCAL EPHEMERAL LOOPBACK RECEIVER
|
|
365
|
+
# ==============================================================================
|
|
366
|
+
|
|
367
|
+
class _LoopbackHandler(http.server.BaseHTTPRequestHandler):
|
|
368
|
+
def log_message(self, format: str, *args: Any) -> None:
|
|
369
|
+
pass # Suppress HTTP server output in terminal
|
|
370
|
+
|
|
371
|
+
def do_GET(self) -> None:
|
|
372
|
+
parsed = urllib.parse.urlparse(self.path)
|
|
373
|
+
qs = urllib.parse.parse_qs(parsed.query)
|
|
374
|
+
|
|
375
|
+
token = qs.get("auth_token", [None])[0]
|
|
376
|
+
secret = qs.get("app_secret_code", [None])[0]
|
|
377
|
+
err = qs.get("error", [None])[0] or qs.get("message", [None])[0]
|
|
378
|
+
|
|
379
|
+
if token and secret:
|
|
380
|
+
self.server.auth_token = token # type: ignore[attr-defined]
|
|
381
|
+
self.server.app_secret_code = secret # type: ignore[attr-defined]
|
|
382
|
+
self.send_response(200)
|
|
383
|
+
self.send_header("Content-Type", "text/html; charset=utf-8")
|
|
384
|
+
self.end_headers()
|
|
385
|
+
html = """<!DOCTYPE html>
|
|
386
|
+
<html>
|
|
387
|
+
<head>
|
|
388
|
+
<meta charset="utf-8">
|
|
389
|
+
<title>chdev Authentication</title>
|
|
390
|
+
<style>
|
|
391
|
+
body { background: #090d16; color: #f1f5f9; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; display: flex; align-items: center; justify-content: center; height: 100vh; margin: 0; }
|
|
392
|
+
.card { background: #0f1523; border: 1px solid #1e293b; padding: 2.5rem 2rem; border-radius: 14px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.5); max-width: 420px; width: 90%; }
|
|
393
|
+
h2 { color: #10b981; margin-top: 0; font-size: 1.5rem; }
|
|
394
|
+
p { color: #94a3b8; font-size: 0.95rem; line-height: 1.5; margin-bottom: 0.5rem; }
|
|
395
|
+
.sub { font-size: 0.8rem; color: #64748b; margin-top: 1.5rem; }
|
|
396
|
+
</style>
|
|
397
|
+
</head>
|
|
398
|
+
<body>
|
|
399
|
+
<div class="card">
|
|
400
|
+
<h2>✓ Authentication Successful</h2>
|
|
401
|
+
<p>You have signed in successfully.</p>
|
|
402
|
+
<p>You can now close this tab and return to your terminal.</p>
|
|
403
|
+
<p class="sub">This tab will close automatically in a few seconds...</p>
|
|
404
|
+
</div>
|
|
405
|
+
<script>setTimeout(function() { window.close(); }, 3500);</script>
|
|
406
|
+
</body>
|
|
407
|
+
</html>"""
|
|
408
|
+
self.wfile.write(html.encode("utf-8"))
|
|
409
|
+
else:
|
|
410
|
+
self.server.error = err or "Missing callback parameters" # type: ignore[attr-defined]
|
|
411
|
+
self.send_response(400)
|
|
412
|
+
self.send_header("Content-Type", "text/plain; charset=utf-8")
|
|
413
|
+
self.end_headers()
|
|
414
|
+
self.wfile.write(b"Authentication failed.")
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
class _LoopbackServer(socketserver.TCPServer):
|
|
418
|
+
allow_reuse_address = True
|
|
419
|
+
auth_token: Optional[str] = None
|
|
420
|
+
app_secret_code: Optional[str] = None
|
|
421
|
+
error: Optional[str] = None
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _run_loopback_login(
|
|
425
|
+
api_key_str: str,
|
|
426
|
+
provider: str,
|
|
427
|
+
app_name: str,
|
|
428
|
+
open_browser: bool,
|
|
429
|
+
timeout: int,
|
|
430
|
+
quiet: bool,
|
|
431
|
+
save_session: bool
|
|
432
|
+
) -> Optional[AuthUser]:
|
|
433
|
+
"""Attempts zero-ping local ephemeral loopback authentication."""
|
|
434
|
+
try:
|
|
435
|
+
httpd = _LoopbackServer(("127.0.0.1", 0), _LoopbackHandler)
|
|
436
|
+
port = httpd.server_address[1]
|
|
437
|
+
httpd.timeout = 1.0
|
|
438
|
+
except Exception:
|
|
439
|
+
return None # Port binding failed; fall back to polling
|
|
440
|
+
|
|
441
|
+
try:
|
|
442
|
+
nonce = secrets.token_hex(24)
|
|
443
|
+
callback_url = f"http://127.0.0.1:{port}/callback"
|
|
444
|
+
|
|
445
|
+
init_res = create_session(
|
|
446
|
+
return_url=callback_url,
|
|
447
|
+
app_secret_code=nonce,
|
|
448
|
+
provider=provider,
|
|
449
|
+
app_name=app_name,
|
|
450
|
+
key=api_key_str,
|
|
451
|
+
timeout=10
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
if init_res.get("status") != "success":
|
|
455
|
+
httpd.server_close()
|
|
456
|
+
return None
|
|
457
|
+
|
|
458
|
+
login_url = init_res["login_url"]
|
|
459
|
+
prov_label = "Microsoft" if provider == "microsoft" else ("Discord" if provider == "discord" else "Google")
|
|
460
|
+
|
|
461
|
+
if not quiet:
|
|
462
|
+
print(f"\nSign in with {prov_label}:")
|
|
463
|
+
print(f"{login_url}\n")
|
|
464
|
+
|
|
465
|
+
if open_browser:
|
|
466
|
+
try:
|
|
467
|
+
webbrowser.open(login_url)
|
|
468
|
+
except Exception:
|
|
469
|
+
pass
|
|
470
|
+
|
|
471
|
+
if not quiet:
|
|
472
|
+
print("Waiting for authentication (instant loopback)...")
|
|
473
|
+
|
|
474
|
+
start_time = time.time()
|
|
475
|
+
while time.time() - start_time < timeout:
|
|
476
|
+
httpd.handle_request()
|
|
477
|
+
if httpd.auth_token and httpd.app_secret_code:
|
|
478
|
+
break
|
|
479
|
+
if httpd.error:
|
|
480
|
+
sys.exit(f"Authentication failed: {httpd.error}")
|
|
481
|
+
|
|
482
|
+
httpd.server_close()
|
|
483
|
+
|
|
484
|
+
if not httpd.auth_token or not httpd.app_secret_code:
|
|
485
|
+
sys.exit(f"Authentication timed out after {timeout} seconds.")
|
|
486
|
+
|
|
487
|
+
# Exactly Request #2: Verify token
|
|
488
|
+
verify_res = verify(
|
|
489
|
+
auth_token=httpd.auth_token,
|
|
490
|
+
app_secret_code=httpd.app_secret_code,
|
|
491
|
+
key=api_key_str
|
|
492
|
+
)
|
|
493
|
+
|
|
494
|
+
if verify_res.get("status") == "success" and verify_res.get("valid"):
|
|
495
|
+
auth_user = _set_globals(verify_res)
|
|
496
|
+
if save_session:
|
|
497
|
+
_save_cache(verify_res.get("user") or {})
|
|
498
|
+
if not quiet:
|
|
499
|
+
print(f"Successfully authenticated as {auth_user.email or auth_user.name}!\n")
|
|
500
|
+
return auth_user
|
|
501
|
+
|
|
502
|
+
sys.exit("Token verification failed.")
|
|
503
|
+
except Exception:
|
|
504
|
+
try:
|
|
505
|
+
httpd.server_close()
|
|
506
|
+
except Exception:
|
|
507
|
+
pass
|
|
508
|
+
return None
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
# ==============================================================================
|
|
512
|
+
# CORE SYNCHRONOUS LOGIN METHODS
|
|
513
|
+
# ==============================================================================
|
|
514
|
+
|
|
515
|
+
def login(
|
|
516
|
+
key: Optional[str] = None,
|
|
517
|
+
provider: str = "google",
|
|
518
|
+
app_name: str = "Python Application",
|
|
519
|
+
open_browser: bool = True,
|
|
520
|
+
poll_interval: float = 1.0,
|
|
521
|
+
timeout: int = 300,
|
|
522
|
+
quiet: bool = False,
|
|
523
|
+
save_session: bool = False,
|
|
524
|
+
qr: bool = False,
|
|
525
|
+
loopback: bool = True
|
|
526
|
+
) -> AuthUser:
|
|
527
|
+
api_key_str = _get_key(key)
|
|
528
|
+
|
|
529
|
+
# 1. Zero-ping local loopback receiver (Preferred for interactive desktop CLI)
|
|
530
|
+
if loopback and open_browser and not qr:
|
|
531
|
+
loopback_user = _run_loopback_login(
|
|
532
|
+
api_key_str=api_key_str,
|
|
533
|
+
provider=provider,
|
|
534
|
+
app_name=app_name,
|
|
535
|
+
open_browser=open_browser,
|
|
536
|
+
timeout=timeout,
|
|
537
|
+
quiet=quiet,
|
|
538
|
+
save_session=save_session
|
|
539
|
+
)
|
|
540
|
+
if loopback_user:
|
|
541
|
+
return loopback_user
|
|
542
|
+
|
|
543
|
+
# 2. Polling Fallback (For headless SSH, qr=True, or restricted environments)
|
|
544
|
+
init_res = _post_json(AUTH_ENDPOINT, {
|
|
545
|
+
"action": "init",
|
|
546
|
+
"provider": provider,
|
|
547
|
+
"app_name": app_name,
|
|
548
|
+
"api_key": api_key_str
|
|
549
|
+
})
|
|
550
|
+
|
|
551
|
+
if init_res.get("status") != "success":
|
|
552
|
+
sys.exit(f"Failed to start authentication: {init_res.get('message', 'Unknown error')}")
|
|
553
|
+
|
|
554
|
+
session_id = init_res["session_id"]
|
|
555
|
+
app_secret_code = init_res["app_secret_code"]
|
|
556
|
+
login_url = init_res["login_url"]
|
|
557
|
+
|
|
558
|
+
if provider == "microsoft":
|
|
559
|
+
prov_label = "Microsoft"
|
|
560
|
+
elif provider == "discord":
|
|
561
|
+
prov_label = "Discord"
|
|
562
|
+
else:
|
|
563
|
+
prov_label = "Google"
|
|
564
|
+
|
|
565
|
+
if not quiet:
|
|
566
|
+
print(f"\nSign in with {prov_label}:")
|
|
567
|
+
print(f"{login_url}\n")
|
|
568
|
+
if qr:
|
|
569
|
+
print("Scan with your phone to sign in:")
|
|
570
|
+
show_qr(login_url)
|
|
571
|
+
|
|
572
|
+
if open_browser:
|
|
573
|
+
try:
|
|
574
|
+
webbrowser.open(login_url)
|
|
575
|
+
except Exception:
|
|
576
|
+
pass
|
|
577
|
+
|
|
578
|
+
if not quiet:
|
|
579
|
+
print("Waiting for authentication...")
|
|
580
|
+
|
|
581
|
+
start_time = time.time()
|
|
582
|
+
while time.time() - start_time < timeout:
|
|
583
|
+
time.sleep(poll_interval)
|
|
584
|
+
try:
|
|
585
|
+
poll_res = _post_json(AUTH_ENDPOINT, {
|
|
586
|
+
"action": "poll",
|
|
587
|
+
"session_id": session_id,
|
|
588
|
+
"app_secret_code": app_secret_code,
|
|
589
|
+
"api_key": api_key_str
|
|
590
|
+
})
|
|
591
|
+
except Exception:
|
|
592
|
+
continue
|
|
593
|
+
|
|
594
|
+
if poll_res.get("status") == "success" and poll_res.get("completed"):
|
|
595
|
+
auth_user = _set_globals(poll_res)
|
|
596
|
+
if save_session:
|
|
597
|
+
_save_cache(poll_res.get("user") or {})
|
|
598
|
+
if not quiet:
|
|
599
|
+
print(f"Successfully authenticated as {auth_user.email or auth_user.name}!\n")
|
|
600
|
+
return auth_user
|
|
601
|
+
|
|
602
|
+
if poll_res.get("status") == "expired":
|
|
603
|
+
sys.exit("Sign-in session has expired. Please try logging in again.")
|
|
604
|
+
|
|
605
|
+
sys.exit(f"Authentication timed out after {timeout} seconds.")
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def google_login(
|
|
609
|
+
key: Optional[str] = None,
|
|
610
|
+
app_name: str = "Python Application",
|
|
611
|
+
open_browser: bool = True,
|
|
612
|
+
poll_interval: float = 1.0,
|
|
613
|
+
timeout: int = 300,
|
|
614
|
+
quiet: bool = False,
|
|
615
|
+
save_session: bool = False,
|
|
616
|
+
qr: bool = False,
|
|
617
|
+
loopback: bool = True
|
|
618
|
+
) -> AuthUser:
|
|
619
|
+
return login(
|
|
620
|
+
key=key,
|
|
621
|
+
provider="google",
|
|
622
|
+
app_name=app_name,
|
|
623
|
+
open_browser=open_browser,
|
|
624
|
+
poll_interval=poll_interval,
|
|
625
|
+
timeout=timeout,
|
|
626
|
+
quiet=quiet,
|
|
627
|
+
save_session=save_session,
|
|
628
|
+
qr=qr,
|
|
629
|
+
loopback=loopback
|
|
630
|
+
)
|
|
631
|
+
|
|
632
|
+
|
|
633
|
+
def discord_login(
|
|
634
|
+
key: Optional[str] = None,
|
|
635
|
+
app_name: str = "Python Application",
|
|
636
|
+
open_browser: bool = True,
|
|
637
|
+
poll_interval: float = 1.0,
|
|
638
|
+
timeout: int = 300,
|
|
639
|
+
quiet: bool = False,
|
|
640
|
+
save_session: bool = False,
|
|
641
|
+
qr: bool = False,
|
|
642
|
+
loopback: bool = True
|
|
643
|
+
) -> AuthUser:
|
|
644
|
+
return login(
|
|
645
|
+
key=key,
|
|
646
|
+
provider="discord",
|
|
647
|
+
app_name=app_name,
|
|
648
|
+
open_browser=open_browser,
|
|
649
|
+
poll_interval=poll_interval,
|
|
650
|
+
timeout=timeout,
|
|
651
|
+
quiet=quiet,
|
|
652
|
+
save_session=save_session,
|
|
653
|
+
qr=qr,
|
|
654
|
+
loopback=loopback
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def microsoft_login(
|
|
659
|
+
key: Optional[str] = None,
|
|
660
|
+
app_name: str = "Python Application",
|
|
661
|
+
open_browser: bool = True,
|
|
662
|
+
poll_interval: float = 1.0,
|
|
663
|
+
timeout: int = 300,
|
|
664
|
+
quiet: bool = False,
|
|
665
|
+
save_session: bool = False,
|
|
666
|
+
qr: bool = False,
|
|
667
|
+
loopback: bool = True
|
|
668
|
+
) -> AuthUser:
|
|
669
|
+
return login(
|
|
670
|
+
key=key,
|
|
671
|
+
provider="microsoft",
|
|
672
|
+
app_name=app_name,
|
|
673
|
+
open_browser=open_browser,
|
|
674
|
+
poll_interval=poll_interval,
|
|
675
|
+
timeout=timeout,
|
|
676
|
+
quiet=quiet,
|
|
677
|
+
save_session=save_session,
|
|
678
|
+
qr=qr,
|
|
679
|
+
loopback=loopback
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
def prompt_login(
|
|
684
|
+
key: Optional[str] = None,
|
|
685
|
+
app_name: str = "Python Application",
|
|
686
|
+
open_browser: bool = True,
|
|
687
|
+
poll_interval: float = 1.0,
|
|
688
|
+
timeout: int = 300,
|
|
689
|
+
quiet: bool = False,
|
|
690
|
+
save_session: bool = False,
|
|
691
|
+
qr: bool = False,
|
|
692
|
+
loopback: bool = True
|
|
693
|
+
) -> AuthUser:
|
|
694
|
+
"""Interactively prompts the user to choose an authentication provider in the terminal."""
|
|
695
|
+
print("\nSelect Sign-In Provider:")
|
|
696
|
+
print(" [1] Google")
|
|
697
|
+
print(" [2] Discord")
|
|
698
|
+
print(" [3] Microsoft")
|
|
699
|
+
try:
|
|
700
|
+
raw_choice = input("Enter choice [1-3] (default: 1): ").strip().lower()
|
|
701
|
+
except (EOFError, KeyboardInterrupt):
|
|
702
|
+
sys.exit("\nAuthentication cancelled.")
|
|
703
|
+
|
|
704
|
+
if raw_choice in ("2", "discord"):
|
|
705
|
+
provider = "discord"
|
|
706
|
+
elif raw_choice in ("3", "microsoft", "ms"):
|
|
707
|
+
provider = "microsoft"
|
|
708
|
+
else:
|
|
709
|
+
provider = "google"
|
|
710
|
+
|
|
711
|
+
return login(
|
|
712
|
+
key=key,
|
|
713
|
+
provider=provider,
|
|
714
|
+
app_name=app_name,
|
|
715
|
+
open_browser=open_browser,
|
|
716
|
+
poll_interval=poll_interval,
|
|
717
|
+
timeout=timeout,
|
|
718
|
+
quiet=quiet,
|
|
719
|
+
save_session=save_session,
|
|
720
|
+
qr=qr,
|
|
721
|
+
loopback=loopback
|
|
722
|
+
)
|
|
723
|
+
|
|
724
|
+
|
|
725
|
+
ask_login = prompt_login
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def require_auth(
|
|
729
|
+
fn: Optional[Callable[..., Any]] = None,
|
|
730
|
+
*,
|
|
731
|
+
provider: str = "google",
|
|
732
|
+
app_name: str = "Python Application",
|
|
733
|
+
key: Optional[str] = None,
|
|
734
|
+
**login_kwargs: Any
|
|
735
|
+
) -> Callable[..., Any]:
|
|
736
|
+
"""Decorator ensuring that a function is only executed after successful authentication."""
|
|
737
|
+
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
738
|
+
@functools.wraps(func)
|
|
739
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
740
|
+
global authenticated
|
|
741
|
+
if not authenticated:
|
|
742
|
+
login(key=key, provider=provider, app_name=app_name, **login_kwargs)
|
|
743
|
+
return func(*args, **kwargs)
|
|
744
|
+
return wrapper
|
|
745
|
+
|
|
746
|
+
if fn is not None and callable(fn):
|
|
747
|
+
return decorator(fn)
|
|
748
|
+
return decorator
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
login_required = require_auth
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
# ==============================================================================
|
|
755
|
+
# ASYNC / ASYNCIO SUPPORT
|
|
756
|
+
# ==============================================================================
|
|
757
|
+
|
|
758
|
+
async def _post_json_async(url: str, payload: Dict[str, Any], timeout: int = 15, headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
|
|
759
|
+
loop = asyncio.get_event_loop()
|
|
760
|
+
return await loop.run_in_executor(None, functools.partial(_post_json, url, payload, timeout=timeout, headers=headers))
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
async def login_async(
|
|
764
|
+
key: Optional[str] = None,
|
|
765
|
+
provider: str = "google",
|
|
766
|
+
app_name: str = "Python Application",
|
|
767
|
+
open_browser: bool = True,
|
|
768
|
+
poll_interval: float = 1.0,
|
|
769
|
+
timeout: int = 300,
|
|
770
|
+
quiet: bool = False,
|
|
771
|
+
save_session: bool = False,
|
|
772
|
+
qr: bool = False,
|
|
773
|
+
loopback: bool = True
|
|
774
|
+
) -> AuthUser:
|
|
775
|
+
"""Non-blocking async login implementation for asyncio applications."""
|
|
776
|
+
loop = asyncio.get_event_loop()
|
|
777
|
+
return await loop.run_in_executor(
|
|
778
|
+
None,
|
|
779
|
+
functools.partial(
|
|
780
|
+
login,
|
|
781
|
+
key=key,
|
|
782
|
+
provider=provider,
|
|
783
|
+
app_name=app_name,
|
|
784
|
+
open_browser=open_browser,
|
|
785
|
+
poll_interval=poll_interval,
|
|
786
|
+
timeout=timeout,
|
|
787
|
+
quiet=quiet,
|
|
788
|
+
save_session=save_session,
|
|
789
|
+
qr=qr,
|
|
790
|
+
loopback=loopback
|
|
791
|
+
)
|
|
792
|
+
)
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
async def google_login_async(**kwargs: Any) -> AuthUser:
|
|
796
|
+
return await login_async(provider="google", **kwargs)
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
async def discord_login_async(**kwargs: Any) -> AuthUser:
|
|
800
|
+
return await login_async(provider="discord", **kwargs)
|
|
801
|
+
|
|
802
|
+
|
|
803
|
+
async def microsoft_login_async(**kwargs: Any) -> AuthUser:
|
|
804
|
+
return await login_async(provider="microsoft", **kwargs)
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
async def prompt_login_async(**kwargs: Any) -> AuthUser:
|
|
808
|
+
loop = asyncio.get_event_loop()
|
|
809
|
+
return await loop.run_in_executor(None, functools.partial(prompt_login, **kwargs))
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
async def cached_login_async(max_age_days: int = 7, **kwargs: Any) -> AuthUser:
|
|
813
|
+
cached = get_user(max_age_days=max_age_days)
|
|
814
|
+
if cached:
|
|
815
|
+
return cached
|
|
816
|
+
return await login_async(save_session=True, **kwargs)
|
|
817
|
+
|
|
818
|
+
|
|
819
|
+
# ==============================================================================
|
|
820
|
+
# BACKEND WEB HELPERS
|
|
821
|
+
# ==============================================================================
|
|
822
|
+
|
|
823
|
+
def create_session(
|
|
824
|
+
return_url: str,
|
|
825
|
+
app_secret_code: str,
|
|
826
|
+
back_url: Optional[str] = None,
|
|
827
|
+
provider: str = "google",
|
|
828
|
+
app_name: Optional[str] = None,
|
|
829
|
+
app_icon: Optional[str] = None,
|
|
830
|
+
brand_color: Optional[str] = None,
|
|
831
|
+
app_id: Optional[str] = None,
|
|
832
|
+
key: Optional[str] = None,
|
|
833
|
+
timeout: int = 15
|
|
834
|
+
) -> Dict[str, Any]:
|
|
835
|
+
"""Backend helper to create an SSO session via POST /api/create-session."""
|
|
836
|
+
k = _get_key(key)
|
|
837
|
+
payload: Dict[str, Any] = {
|
|
838
|
+
"return_url": return_url,
|
|
839
|
+
"app_secret_code": app_secret_code,
|
|
840
|
+
"provider": provider,
|
|
841
|
+
"api_key": k
|
|
842
|
+
}
|
|
843
|
+
if back_url:
|
|
844
|
+
payload["back_url"] = back_url
|
|
845
|
+
if app_name:
|
|
846
|
+
payload["app_name"] = app_name
|
|
847
|
+
if app_icon:
|
|
848
|
+
payload["app_icon"] = app_icon
|
|
849
|
+
if brand_color:
|
|
850
|
+
payload["brand_color"] = brand_color
|
|
851
|
+
if app_id:
|
|
852
|
+
payload["app_id"] = app_id
|
|
853
|
+
|
|
854
|
+
return _post_json(
|
|
855
|
+
f"{BASE_URL}/api/create-session",
|
|
856
|
+
payload,
|
|
857
|
+
timeout=timeout,
|
|
858
|
+
headers={"X-API-Key": k}
|
|
859
|
+
)
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
def verify(
|
|
863
|
+
auth_token: str,
|
|
864
|
+
app_secret_code: str,
|
|
865
|
+
key: Optional[str] = None,
|
|
866
|
+
timeout: int = 15
|
|
867
|
+
) -> Dict[str, Any]:
|
|
868
|
+
"""Backend helper to verify an auth_token via POST /api/verify."""
|
|
869
|
+
k = _get_key(key)
|
|
870
|
+
payload = {
|
|
871
|
+
"auth_token": auth_token,
|
|
872
|
+
"app_secret_code": app_secret_code,
|
|
873
|
+
"api_key": k
|
|
874
|
+
}
|
|
875
|
+
return _post_json(
|
|
876
|
+
f"{BASE_URL}/api/verify",
|
|
877
|
+
payload,
|
|
878
|
+
timeout=timeout,
|
|
879
|
+
headers={"X-API-Key": k}
|
|
880
|
+
)
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Asyncio-first interface for the chdev authentication library."""
|
|
2
|
+
from chdev import *
|
|
3
|
+
from chdev import (
|
|
4
|
+
login_async as login,
|
|
5
|
+
prompt_login_async as prompt_login,
|
|
6
|
+
google_login_async as google_login,
|
|
7
|
+
discord_login_async as discord_login,
|
|
8
|
+
microsoft_login_async as microsoft_login,
|
|
9
|
+
cached_login_async as cached_login,
|
|
10
|
+
)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: chdev
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.0
|
|
4
4
|
Summary: Official Python client library for chdev Authentication (SSO for Google, Discord, Microsoft)
|
|
5
5
|
Author-email: chdev <contact@chdev.co.uk>
|
|
6
6
|
Project-URL: Homepage, https://authentication.chdev.co.uk
|
|
@@ -1,428 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import builtins
|
|
4
|
-
import functools
|
|
5
|
-
import json
|
|
6
|
-
import os
|
|
7
|
-
import sys
|
|
8
|
-
import time
|
|
9
|
-
import urllib.error
|
|
10
|
-
import urllib.request
|
|
11
|
-
import webbrowser
|
|
12
|
-
from typing import Any, Callable, Dict, Optional
|
|
13
|
-
|
|
14
|
-
__version__ = "1.2.1"
|
|
15
|
-
__all__ = [
|
|
16
|
-
"google_login",
|
|
17
|
-
"discord_login",
|
|
18
|
-
"microsoft_login",
|
|
19
|
-
"login",
|
|
20
|
-
"prompt_login",
|
|
21
|
-
"ask_login",
|
|
22
|
-
"require_auth",
|
|
23
|
-
"login_required",
|
|
24
|
-
"create_session",
|
|
25
|
-
"verify",
|
|
26
|
-
"set_key",
|
|
27
|
-
"api_key",
|
|
28
|
-
"email",
|
|
29
|
-
"pfp",
|
|
30
|
-
"picture",
|
|
31
|
-
"name",
|
|
32
|
-
"user",
|
|
33
|
-
"user_id",
|
|
34
|
-
"authenticated",
|
|
35
|
-
]
|
|
36
|
-
|
|
37
|
-
BASE_URL = "https://authentication.chdev.co.uk"
|
|
38
|
-
AUTH_ENDPOINT = f"{BASE_URL}/api/cli-auth"
|
|
39
|
-
|
|
40
|
-
api_key: Optional[str] = None
|
|
41
|
-
email: Optional[str] = None
|
|
42
|
-
pfp: Optional[str] = None
|
|
43
|
-
picture: Optional[str] = None
|
|
44
|
-
name: Optional[str] = None
|
|
45
|
-
user_id: Optional[str] = None
|
|
46
|
-
user: Optional[Dict[str, Any]] = None
|
|
47
|
-
authenticated: bool = False
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
class AuthUser(str):
|
|
51
|
-
email: str
|
|
52
|
-
pfp: str
|
|
53
|
-
picture: str
|
|
54
|
-
name: str
|
|
55
|
-
id: str
|
|
56
|
-
user_id: str
|
|
57
|
-
provider: str
|
|
58
|
-
user: Dict[str, Any]
|
|
59
|
-
|
|
60
|
-
def __new__(cls, user_data: Dict[str, Any]):
|
|
61
|
-
user_email = user_data.get("email") or ""
|
|
62
|
-
obj = super().__new__(cls, user_email)
|
|
63
|
-
obj.email = user_email
|
|
64
|
-
obj.pfp = user_data.get("pfp") or user_data.get("picture") or ""
|
|
65
|
-
obj.picture = obj.pfp
|
|
66
|
-
obj.name = user_data.get("name") or ""
|
|
67
|
-
obj.id = str(user_data.get("id") or "")
|
|
68
|
-
obj.user_id = obj.id
|
|
69
|
-
obj.provider = user_data.get("provider") or "google"
|
|
70
|
-
obj.user = user_data
|
|
71
|
-
return obj
|
|
72
|
-
|
|
73
|
-
def __getitem__(self, item: Any) -> Any:
|
|
74
|
-
if isinstance(item, str):
|
|
75
|
-
return self.user.get(item)
|
|
76
|
-
return super().__getitem__(item)
|
|
77
|
-
|
|
78
|
-
def get(self, key: str, default: Any = None) -> Any:
|
|
79
|
-
return self.user.get(key, default)
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
def set_key(key: str) -> None:
|
|
83
|
-
"""Set the global API key used for all chdev authentication requests."""
|
|
84
|
-
global api_key
|
|
85
|
-
k = (key or "").strip()
|
|
86
|
-
api_key = k
|
|
87
|
-
if k:
|
|
88
|
-
os.environ["CHDEV_AUTH_SECRET_KEY"] = k
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
def _get_key(key: Optional[str] = None) -> str:
|
|
92
|
-
k = (key or api_key or os.environ.get("CHDEV_AUTH_SECRET_KEY") or "").strip()
|
|
93
|
-
if not k:
|
|
94
|
-
sys.exit("Invalid key.")
|
|
95
|
-
return k
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def _set_globals(res: Dict[str, Any]) -> AuthUser:
|
|
99
|
-
global email, pfp, picture, name, user, user_id, authenticated
|
|
100
|
-
|
|
101
|
-
user_data = res.get("user") or {}
|
|
102
|
-
auth_user = AuthUser(user_data)
|
|
103
|
-
|
|
104
|
-
user_email = auth_user.email
|
|
105
|
-
user_pfp = auth_user.pfp
|
|
106
|
-
user_name = auth_user.name
|
|
107
|
-
user_raw_id = auth_user.id
|
|
108
|
-
|
|
109
|
-
email = user_email
|
|
110
|
-
pfp = user_pfp
|
|
111
|
-
picture = user_pfp
|
|
112
|
-
name = user_name
|
|
113
|
-
user_id = user_raw_id
|
|
114
|
-
user = user_data
|
|
115
|
-
authenticated = True
|
|
116
|
-
|
|
117
|
-
try:
|
|
118
|
-
frame = sys._getframe(1)
|
|
119
|
-
while frame and frame.f_globals.get("__name__") in (__name__, "chdev", "chdevauth"):
|
|
120
|
-
frame = frame.f_back
|
|
121
|
-
if frame:
|
|
122
|
-
frame.f_globals["email"] = user_email
|
|
123
|
-
frame.f_globals["pfp"] = user_pfp
|
|
124
|
-
frame.f_globals["picture"] = user_pfp
|
|
125
|
-
frame.f_globals["name"] = user_name
|
|
126
|
-
frame.f_globals["user_id"] = user_raw_id
|
|
127
|
-
frame.f_globals["user"] = user_data
|
|
128
|
-
frame.f_globals["authenticated"] = True
|
|
129
|
-
except Exception:
|
|
130
|
-
pass
|
|
131
|
-
|
|
132
|
-
try:
|
|
133
|
-
builtins.email = user_email
|
|
134
|
-
builtins.pfp = user_pfp
|
|
135
|
-
builtins.picture = user_pfp
|
|
136
|
-
builtins.name = user_name
|
|
137
|
-
builtins.user_id = user_raw_id
|
|
138
|
-
builtins.user = user_data
|
|
139
|
-
builtins.authenticated = True
|
|
140
|
-
except Exception:
|
|
141
|
-
pass
|
|
142
|
-
|
|
143
|
-
return auth_user
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
def _post_json(
|
|
147
|
-
url: str,
|
|
148
|
-
payload: Dict[str, Any],
|
|
149
|
-
timeout: int = 15,
|
|
150
|
-
headers: Optional[Dict[str, str]] = None
|
|
151
|
-
) -> Dict[str, Any]:
|
|
152
|
-
req_headers = {
|
|
153
|
-
"Content-Type": "application/json",
|
|
154
|
-
"User-Agent": "chdev-python/1.2.0"
|
|
155
|
-
}
|
|
156
|
-
if headers:
|
|
157
|
-
req_headers.update(headers)
|
|
158
|
-
|
|
159
|
-
req = urllib.request.Request(
|
|
160
|
-
url,
|
|
161
|
-
data=json.dumps(payload).encode("utf-8"),
|
|
162
|
-
headers=req_headers
|
|
163
|
-
)
|
|
164
|
-
try:
|
|
165
|
-
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
166
|
-
return json.loads(resp.read().decode("utf-8"))
|
|
167
|
-
except urllib.error.HTTPError as e:
|
|
168
|
-
if e.code in (401, 403):
|
|
169
|
-
sys.exit("Invalid key.")
|
|
170
|
-
try:
|
|
171
|
-
err_body = json.loads(e.read().decode("utf-8"))
|
|
172
|
-
msg = err_body.get("message") or err_body.get("error") or f"HTTP {e.code}"
|
|
173
|
-
sys.exit(f"Request failed: {msg}")
|
|
174
|
-
except Exception:
|
|
175
|
-
sys.exit(f"Request failed ({e.code}).")
|
|
176
|
-
except urllib.error.URLError as e:
|
|
177
|
-
sys.exit(f"Connection error: {e.reason}")
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
def login(
|
|
181
|
-
key: Optional[str] = None,
|
|
182
|
-
provider: str = "google",
|
|
183
|
-
app_name: str = "Python Application",
|
|
184
|
-
open_browser: bool = True,
|
|
185
|
-
poll_interval: float = 1.0,
|
|
186
|
-
timeout: int = 300,
|
|
187
|
-
quiet: bool = False
|
|
188
|
-
) -> AuthUser:
|
|
189
|
-
api_key_str = _get_key(key)
|
|
190
|
-
|
|
191
|
-
init_res = _post_json(AUTH_ENDPOINT, {
|
|
192
|
-
"action": "init",
|
|
193
|
-
"provider": provider,
|
|
194
|
-
"app_name": app_name,
|
|
195
|
-
"api_key": api_key_str
|
|
196
|
-
})
|
|
197
|
-
|
|
198
|
-
if init_res.get("status") != "success":
|
|
199
|
-
sys.exit(f"Failed to start authentication: {init_res.get('message', 'Unknown error')}")
|
|
200
|
-
|
|
201
|
-
session_id = init_res["session_id"]
|
|
202
|
-
app_secret_code = init_res["app_secret_code"]
|
|
203
|
-
login_url = init_res["login_url"]
|
|
204
|
-
if provider == "microsoft":
|
|
205
|
-
prov_label = "Microsoft"
|
|
206
|
-
elif provider == "discord":
|
|
207
|
-
prov_label = "Discord"
|
|
208
|
-
else:
|
|
209
|
-
prov_label = "Google"
|
|
210
|
-
|
|
211
|
-
if not quiet:
|
|
212
|
-
print(f"\nSign in with {prov_label}:")
|
|
213
|
-
print(f"{login_url}\n")
|
|
214
|
-
|
|
215
|
-
if open_browser:
|
|
216
|
-
try:
|
|
217
|
-
webbrowser.open(login_url)
|
|
218
|
-
except Exception:
|
|
219
|
-
pass
|
|
220
|
-
|
|
221
|
-
if not quiet:
|
|
222
|
-
print("Waiting for authentication...")
|
|
223
|
-
|
|
224
|
-
start_time = time.time()
|
|
225
|
-
while time.time() - start_time < timeout:
|
|
226
|
-
time.sleep(poll_interval)
|
|
227
|
-
try:
|
|
228
|
-
poll_res = _post_json(AUTH_ENDPOINT, {
|
|
229
|
-
"action": "poll",
|
|
230
|
-
"session_id": session_id,
|
|
231
|
-
"app_secret_code": app_secret_code,
|
|
232
|
-
"api_key": api_key_str
|
|
233
|
-
})
|
|
234
|
-
except Exception:
|
|
235
|
-
continue
|
|
236
|
-
|
|
237
|
-
if poll_res.get("status") == "success" and poll_res.get("completed"):
|
|
238
|
-
auth_user = _set_globals(poll_res)
|
|
239
|
-
if not quiet:
|
|
240
|
-
print(f"Successfully authenticated as {auth_user.email or auth_user.name}!\n")
|
|
241
|
-
return auth_user
|
|
242
|
-
|
|
243
|
-
if poll_res.get("status") == "expired":
|
|
244
|
-
sys.exit("Sign-in session has expired. Please try logging in again.")
|
|
245
|
-
|
|
246
|
-
sys.exit(f"Authentication timed out after {timeout} seconds.")
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
def google_login(
|
|
250
|
-
key: Optional[str] = None,
|
|
251
|
-
app_name: str = "Python Application",
|
|
252
|
-
open_browser: bool = True,
|
|
253
|
-
poll_interval: float = 1.0,
|
|
254
|
-
timeout: int = 300,
|
|
255
|
-
quiet: bool = False
|
|
256
|
-
) -> AuthUser:
|
|
257
|
-
return login(
|
|
258
|
-
key=key,
|
|
259
|
-
provider="google",
|
|
260
|
-
app_name=app_name,
|
|
261
|
-
open_browser=open_browser,
|
|
262
|
-
poll_interval=poll_interval,
|
|
263
|
-
timeout=timeout,
|
|
264
|
-
quiet=quiet
|
|
265
|
-
)
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
def discord_login(
|
|
269
|
-
key: Optional[str] = None,
|
|
270
|
-
app_name: str = "Python Application",
|
|
271
|
-
open_browser: bool = True,
|
|
272
|
-
poll_interval: float = 1.0,
|
|
273
|
-
timeout: int = 300,
|
|
274
|
-
quiet: bool = False
|
|
275
|
-
) -> AuthUser:
|
|
276
|
-
return login(
|
|
277
|
-
key=key,
|
|
278
|
-
provider="discord",
|
|
279
|
-
app_name=app_name,
|
|
280
|
-
open_browser=open_browser,
|
|
281
|
-
poll_interval=poll_interval,
|
|
282
|
-
timeout=timeout,
|
|
283
|
-
quiet=quiet
|
|
284
|
-
)
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
def microsoft_login(
|
|
288
|
-
key: Optional[str] = None,
|
|
289
|
-
app_name: str = "Python Application",
|
|
290
|
-
open_browser: bool = True,
|
|
291
|
-
poll_interval: float = 1.0,
|
|
292
|
-
timeout: int = 300,
|
|
293
|
-
quiet: bool = False
|
|
294
|
-
) -> AuthUser:
|
|
295
|
-
return login(
|
|
296
|
-
key=key,
|
|
297
|
-
provider="microsoft",
|
|
298
|
-
app_name=app_name,
|
|
299
|
-
open_browser=open_browser,
|
|
300
|
-
poll_interval=poll_interval,
|
|
301
|
-
timeout=timeout,
|
|
302
|
-
quiet=quiet
|
|
303
|
-
)
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
def prompt_login(
|
|
307
|
-
key: Optional[str] = None,
|
|
308
|
-
app_name: str = "Python Application",
|
|
309
|
-
open_browser: bool = True,
|
|
310
|
-
poll_interval: float = 1.0,
|
|
311
|
-
timeout: int = 300,
|
|
312
|
-
quiet: bool = False
|
|
313
|
-
) -> AuthUser:
|
|
314
|
-
"""Interactively prompts the user to choose an authentication provider in the terminal."""
|
|
315
|
-
print("\nSelect Sign-In Provider:")
|
|
316
|
-
print(" [1] Google")
|
|
317
|
-
print(" [2] Discord")
|
|
318
|
-
print(" [3] Microsoft")
|
|
319
|
-
try:
|
|
320
|
-
raw_choice = input("Enter choice [1-3] (default: 1): ").strip().lower()
|
|
321
|
-
except (EOFError, KeyboardInterrupt):
|
|
322
|
-
sys.exit("\nAuthentication cancelled.")
|
|
323
|
-
|
|
324
|
-
if raw_choice in ("2", "discord"):
|
|
325
|
-
provider = "discord"
|
|
326
|
-
elif raw_choice in ("3", "microsoft", "ms"):
|
|
327
|
-
provider = "microsoft"
|
|
328
|
-
else:
|
|
329
|
-
provider = "google"
|
|
330
|
-
|
|
331
|
-
return login(
|
|
332
|
-
key=key,
|
|
333
|
-
provider=provider,
|
|
334
|
-
app_name=app_name,
|
|
335
|
-
open_browser=open_browser,
|
|
336
|
-
poll_interval=poll_interval,
|
|
337
|
-
timeout=timeout,
|
|
338
|
-
quiet=quiet
|
|
339
|
-
)
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
ask_login = prompt_login
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
def require_auth(
|
|
346
|
-
fn: Optional[Callable[..., Any]] = None,
|
|
347
|
-
*,
|
|
348
|
-
provider: str = "google",
|
|
349
|
-
app_name: str = "Python Application",
|
|
350
|
-
key: Optional[str] = None,
|
|
351
|
-
**login_kwargs: Any
|
|
352
|
-
) -> Callable[..., Any]:
|
|
353
|
-
"""Decorator ensuring that a function is only executed after successful authentication."""
|
|
354
|
-
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
|
355
|
-
@functools.wraps(func)
|
|
356
|
-
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
357
|
-
global authenticated
|
|
358
|
-
if not authenticated:
|
|
359
|
-
login(key=key, provider=provider, app_name=app_name, **login_kwargs)
|
|
360
|
-
return func(*args, **kwargs)
|
|
361
|
-
return wrapper
|
|
362
|
-
|
|
363
|
-
if fn is not None and callable(fn):
|
|
364
|
-
return decorator(fn)
|
|
365
|
-
return decorator
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
login_required = require_auth
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
def create_session(
|
|
372
|
-
return_url: str,
|
|
373
|
-
app_secret_code: str,
|
|
374
|
-
back_url: Optional[str] = None,
|
|
375
|
-
provider: str = "google",
|
|
376
|
-
app_name: Optional[str] = None,
|
|
377
|
-
app_icon: Optional[str] = None,
|
|
378
|
-
brand_color: Optional[str] = None,
|
|
379
|
-
app_id: Optional[str] = None,
|
|
380
|
-
key: Optional[str] = None,
|
|
381
|
-
timeout: int = 15
|
|
382
|
-
) -> Dict[str, Any]:
|
|
383
|
-
"""Backend helper to create an SSO session via POST /api/create-session."""
|
|
384
|
-
k = _get_key(key)
|
|
385
|
-
payload: Dict[str, Any] = {
|
|
386
|
-
"return_url": return_url,
|
|
387
|
-
"app_secret_code": app_secret_code,
|
|
388
|
-
"provider": provider,
|
|
389
|
-
"api_key": k
|
|
390
|
-
}
|
|
391
|
-
if back_url:
|
|
392
|
-
payload["back_url"] = back_url
|
|
393
|
-
if app_name:
|
|
394
|
-
payload["app_name"] = app_name
|
|
395
|
-
if app_icon:
|
|
396
|
-
payload["app_icon"] = app_icon
|
|
397
|
-
if brand_color:
|
|
398
|
-
payload["brand_color"] = brand_color
|
|
399
|
-
if app_id:
|
|
400
|
-
payload["app_id"] = app_id
|
|
401
|
-
|
|
402
|
-
return _post_json(
|
|
403
|
-
f"{BASE_URL}/api/create-session",
|
|
404
|
-
payload,
|
|
405
|
-
timeout=timeout,
|
|
406
|
-
headers={"X-API-Key": k}
|
|
407
|
-
)
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
def verify(
|
|
411
|
-
auth_token: str,
|
|
412
|
-
app_secret_code: str,
|
|
413
|
-
key: Optional[str] = None,
|
|
414
|
-
timeout: int = 15
|
|
415
|
-
) -> Dict[str, Any]:
|
|
416
|
-
"""Backend helper to verify an auth_token via POST /api/verify."""
|
|
417
|
-
k = _get_key(key)
|
|
418
|
-
payload = {
|
|
419
|
-
"auth_token": auth_token,
|
|
420
|
-
"app_secret_code": app_secret_code,
|
|
421
|
-
"api_key": k
|
|
422
|
-
}
|
|
423
|
-
return _post_json(
|
|
424
|
-
f"{BASE_URL}/api/verify",
|
|
425
|
-
payload,
|
|
426
|
-
timeout=timeout,
|
|
427
|
-
headers={"X-API-Key": k}
|
|
428
|
-
)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|