chdev 1.2.1__tar.gz → 1.3.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: chdev
3
- Version: 1.2.1
3
+ Version: 1.3.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
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "chdev"
7
- version = "1.2.1"
7
+ version = "1.3.0"
8
8
  authors = [
9
9
  { name="chdev", email="contact@chdev.co.uk" },
10
10
  ]
@@ -1,5 +1,6 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import asyncio
3
4
  import builtins
4
5
  import functools
5
6
  import json
@@ -7,22 +8,41 @@ import os
7
8
  import sys
8
9
  import time
9
10
  import urllib.error
11
+ import urllib.parse
10
12
  import urllib.request
11
13
  import webbrowser
12
- from typing import Any, Callable, Dict, Optional
14
+ from typing import Any, Callable, Dict, List, Optional, Union
13
15
 
14
- __version__ = "1.2.1"
16
+ __version__ = "1.3.0"
15
17
  __all__ = [
18
+ # Core Synchronous Logins
16
19
  "google_login",
17
20
  "discord_login",
18
21
  "microsoft_login",
19
22
  "login",
20
23
  "prompt_login",
21
24
  "ask_login",
25
+ "cached_login",
26
+ # Async Logins
27
+ "login_async",
28
+ "prompt_login_async",
29
+ "google_login_async",
30
+ "discord_login_async",
31
+ "microsoft_login_async",
32
+ "cached_login_async",
33
+ # Decorators & Guards
22
34
  "require_auth",
23
35
  "login_required",
36
+ "allowed_users",
37
+ "require_user",
38
+ # Session Management
39
+ "get_user",
40
+ "logout",
41
+ "show_qr",
42
+ # Backend Web Helpers
24
43
  "create_session",
25
44
  "verify",
45
+ # Configuration & State
26
46
  "set_key",
27
47
  "api_key",
28
48
  "email",
@@ -32,10 +52,13 @@ __all__ = [
32
52
  "user",
33
53
  "user_id",
34
54
  "authenticated",
55
+ "AuthUser",
35
56
  ]
36
57
 
37
58
  BASE_URL = "https://authentication.chdev.co.uk"
38
59
  AUTH_ENDPOINT = f"{BASE_URL}/api/cli-auth"
60
+ CACHE_DIR = os.path.expanduser("~/.chdev")
61
+ CACHE_FILE = os.path.join(CACHE_DIR, "session.json")
39
62
 
40
63
  api_key: Optional[str] = None
41
64
  email: Optional[str] = None
@@ -48,6 +71,7 @@ authenticated: bool = False
48
71
 
49
72
 
50
73
  class AuthUser(str):
74
+ """String subclass representing an authenticated user, defaulting to their email."""
51
75
  email: str
52
76
  pfp: str
53
77
  picture: str
@@ -116,7 +140,7 @@ def _set_globals(res: Dict[str, Any]) -> AuthUser:
116
140
 
117
141
  try:
118
142
  frame = sys._getframe(1)
119
- while frame and frame.f_globals.get("__name__") in (__name__, "chdev", "chdevauth"):
143
+ while frame and frame.f_globals.get("__name__") in (__name__, "chdev", "chdevauth", "chdev.aio"):
120
144
  frame = frame.f_back
121
145
  if frame:
122
146
  frame.f_globals["email"] = user_email
@@ -151,7 +175,7 @@ def _post_json(
151
175
  ) -> Dict[str, Any]:
152
176
  req_headers = {
153
177
  "Content-Type": "application/json",
154
- "User-Agent": "chdev-python/1.2.0"
178
+ "User-Agent": f"chdev-python/{__version__}"
155
179
  }
156
180
  if headers:
157
181
  req_headers.update(headers)
@@ -177,6 +201,163 @@ def _post_json(
177
201
  sys.exit(f"Connection error: {e.reason}")
178
202
 
179
203
 
204
+ # ==============================================================================
205
+ # 2. LOCAL SESSION CACHING
206
+ # ==============================================================================
207
+
208
+ def _save_cache(user_data: Dict[str, Any]) -> None:
209
+ try:
210
+ os.makedirs(CACHE_DIR, exist_ok=True)
211
+ payload = {
212
+ "saved_at": time.time(),
213
+ "user": user_data
214
+ }
215
+ with open(CACHE_FILE, "w", encoding="utf-8") as f:
216
+ json.dump(payload, f, indent=2)
217
+ except Exception:
218
+ pass
219
+
220
+
221
+ def get_user(max_age_days: int = 7) -> Optional[AuthUser]:
222
+ """Retrieve the locally cached authenticated user if not expired."""
223
+ if not os.path.isfile(CACHE_FILE):
224
+ return None
225
+ try:
226
+ with open(CACHE_FILE, "r", encoding="utf-8") as f:
227
+ data = json.load(f)
228
+ saved_at = float(data.get("saved_at", 0))
229
+ max_age_seconds = max_age_days * 86400
230
+ if time.time() - saved_at > max_age_seconds:
231
+ logout()
232
+ return None
233
+ cached_user = data.get("user")
234
+ if cached_user and isinstance(cached_user, dict):
235
+ return _set_globals({"user": cached_user})
236
+ except Exception:
237
+ pass
238
+ return None
239
+
240
+
241
+ def logout() -> bool:
242
+ """Clear the local session cache and reset authenticated global variables."""
243
+ global email, pfp, picture, name, user, user_id, authenticated
244
+ email = None
245
+ pfp = None
246
+ picture = None
247
+ name = None
248
+ user = None
249
+ user_id = None
250
+ authenticated = False
251
+ try:
252
+ if os.path.exists(CACHE_FILE):
253
+ os.remove(CACHE_FILE)
254
+ return True
255
+ except Exception:
256
+ pass
257
+ return False
258
+
259
+
260
+ def cached_login(
261
+ key: Optional[str] = None,
262
+ provider: str = "google",
263
+ app_name: str = "Python Application",
264
+ max_age_days: int = 7,
265
+ open_browser: bool = True,
266
+ poll_interval: float = 1.0,
267
+ timeout: int = 300,
268
+ quiet: bool = False,
269
+ qr: bool = False
270
+ ) -> AuthUser:
271
+ """Return the cached user if valid; otherwise prompt login and save the session."""
272
+ cached = get_user(max_age_days=max_age_days)
273
+ if cached:
274
+ if not quiet:
275
+ print(f"Loaded cached session for {cached.email or cached.name}!")
276
+ return cached
277
+
278
+ return login(
279
+ key=key,
280
+ provider=provider,
281
+ app_name=app_name,
282
+ open_browser=open_browser,
283
+ poll_interval=poll_interval,
284
+ timeout=timeout,
285
+ quiet=quiet,
286
+ save_session=True,
287
+ qr=qr
288
+ )
289
+
290
+
291
+ # ==============================================================================
292
+ # 3. TERMINAL ASCII QR CODE
293
+ # ==============================================================================
294
+
295
+ def show_qr(url: str) -> None:
296
+ """Render an ASCII QR code for a sign-in URL directly in the terminal."""
297
+ try:
298
+ import qrcode
299
+ qr_obj = qrcode.QRCode()
300
+ qr_obj.add_data(url)
301
+ qr_obj.print_ascii(invert=True)
302
+ return
303
+ except Exception:
304
+ pass
305
+
306
+ try:
307
+ qr_api_url = f"{BASE_URL}/api/qr?url=" + urllib.parse.quote(url)
308
+ req = urllib.request.Request(qr_api_url, headers={"User-Agent": "chdev-python-cli"})
309
+ with urllib.request.urlopen(req, timeout=3) as resp:
310
+ ascii_qr = resp.read().decode("utf-8")
311
+ if ascii_qr:
312
+ print(ascii_qr)
313
+ except Exception:
314
+ pass
315
+
316
+
317
+ # ==============================================================================
318
+ # 4. EMAIL / USER PERMISSION GUARD
319
+ # ==============================================================================
320
+
321
+ def allowed_users(
322
+ users: Union[str, List[str]],
323
+ *,
324
+ key: Optional[str] = None,
325
+ provider: str = "google",
326
+ app_name: str = "Python Application",
327
+ **login_kwargs: Any
328
+ ) -> Callable[..., Any]:
329
+ """Decorator restricting function execution to a specific list of allowed emails or IDs."""
330
+ if isinstance(users, str):
331
+ allowed_list = [users.strip().lower()]
332
+ else:
333
+ allowed_list = [u.strip().lower() for u in users]
334
+
335
+ def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
336
+ @functools.wraps(func)
337
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
338
+ global authenticated
339
+ if not authenticated:
340
+ login(key=key, provider=provider, app_name=app_name, **login_kwargs)
341
+
342
+ user_email = (email or "").lower()
343
+ current_id = str(user_id or "")
344
+ discord_tag = str(user.get("discord_username", "") if user else "").lower()
345
+
346
+ if user_email in allowed_list or current_id in allowed_list or discord_tag in allowed_list:
347
+ return func(*args, **kwargs)
348
+
349
+ sys.exit(f"Access denied: '{user_email or current_id}' is not in the allowed users list.")
350
+ return wrapper
351
+ return decorator
352
+
353
+
354
+ require_user = allowed_users
355
+
356
+
357
+ # ==============================================================================
358
+ # CORE SYNCHRONOUS LOGIN METHODS
359
+ # ==============================================================================
360
+
180
361
  def login(
181
362
  key: Optional[str] = None,
182
363
  provider: str = "google",
@@ -184,7 +365,9 @@ def login(
184
365
  open_browser: bool = True,
185
366
  poll_interval: float = 1.0,
186
367
  timeout: int = 300,
187
- quiet: bool = False
368
+ quiet: bool = False,
369
+ save_session: bool = False,
370
+ qr: bool = False
188
371
  ) -> AuthUser:
189
372
  api_key_str = _get_key(key)
190
373
 
@@ -201,6 +384,7 @@ def login(
201
384
  session_id = init_res["session_id"]
202
385
  app_secret_code = init_res["app_secret_code"]
203
386
  login_url = init_res["login_url"]
387
+
204
388
  if provider == "microsoft":
205
389
  prov_label = "Microsoft"
206
390
  elif provider == "discord":
@@ -211,6 +395,9 @@ def login(
211
395
  if not quiet:
212
396
  print(f"\nSign in with {prov_label}:")
213
397
  print(f"{login_url}\n")
398
+ if qr:
399
+ print("Scan with your phone to sign in:")
400
+ show_qr(login_url)
214
401
 
215
402
  if open_browser:
216
403
  try:
@@ -236,6 +423,8 @@ def login(
236
423
 
237
424
  if poll_res.get("status") == "success" and poll_res.get("completed"):
238
425
  auth_user = _set_globals(poll_res)
426
+ if save_session:
427
+ _save_cache(poll_res.get("user") or {})
239
428
  if not quiet:
240
429
  print(f"Successfully authenticated as {auth_user.email or auth_user.name}!\n")
241
430
  return auth_user
@@ -252,7 +441,9 @@ def google_login(
252
441
  open_browser: bool = True,
253
442
  poll_interval: float = 1.0,
254
443
  timeout: int = 300,
255
- quiet: bool = False
444
+ quiet: bool = False,
445
+ save_session: bool = False,
446
+ qr: bool = False
256
447
  ) -> AuthUser:
257
448
  return login(
258
449
  key=key,
@@ -261,7 +452,9 @@ def google_login(
261
452
  open_browser=open_browser,
262
453
  poll_interval=poll_interval,
263
454
  timeout=timeout,
264
- quiet=quiet
455
+ quiet=quiet,
456
+ save_session=save_session,
457
+ qr=qr
265
458
  )
266
459
 
267
460
 
@@ -271,7 +464,9 @@ def discord_login(
271
464
  open_browser: bool = True,
272
465
  poll_interval: float = 1.0,
273
466
  timeout: int = 300,
274
- quiet: bool = False
467
+ quiet: bool = False,
468
+ save_session: bool = False,
469
+ qr: bool = False
275
470
  ) -> AuthUser:
276
471
  return login(
277
472
  key=key,
@@ -280,7 +475,9 @@ def discord_login(
280
475
  open_browser=open_browser,
281
476
  poll_interval=poll_interval,
282
477
  timeout=timeout,
283
- quiet=quiet
478
+ quiet=quiet,
479
+ save_session=save_session,
480
+ qr=qr
284
481
  )
285
482
 
286
483
 
@@ -290,7 +487,9 @@ def microsoft_login(
290
487
  open_browser: bool = True,
291
488
  poll_interval: float = 1.0,
292
489
  timeout: int = 300,
293
- quiet: bool = False
490
+ quiet: bool = False,
491
+ save_session: bool = False,
492
+ qr: bool = False
294
493
  ) -> AuthUser:
295
494
  return login(
296
495
  key=key,
@@ -299,7 +498,9 @@ def microsoft_login(
299
498
  open_browser=open_browser,
300
499
  poll_interval=poll_interval,
301
500
  timeout=timeout,
302
- quiet=quiet
501
+ quiet=quiet,
502
+ save_session=save_session,
503
+ qr=qr
303
504
  )
304
505
 
305
506
 
@@ -309,7 +510,9 @@ def prompt_login(
309
510
  open_browser: bool = True,
310
511
  poll_interval: float = 1.0,
311
512
  timeout: int = 300,
312
- quiet: bool = False
513
+ quiet: bool = False,
514
+ save_session: bool = False,
515
+ qr: bool = False
313
516
  ) -> AuthUser:
314
517
  """Interactively prompts the user to choose an authentication provider in the terminal."""
315
518
  print("\nSelect Sign-In Provider:")
@@ -335,7 +538,9 @@ def prompt_login(
335
538
  open_browser=open_browser,
336
539
  poll_interval=poll_interval,
337
540
  timeout=timeout,
338
- quiet=quiet
541
+ quiet=quiet,
542
+ save_session=save_session,
543
+ qr=qr
339
544
  )
340
545
 
341
546
 
@@ -368,6 +573,122 @@ def require_auth(
368
573
  login_required = require_auth
369
574
 
370
575
 
576
+ # ==============================================================================
577
+ # 5. ASYNC / ASYNCIO SUPPORT
578
+ # ==============================================================================
579
+
580
+ async def _post_json_async(url: str, payload: Dict[str, Any], timeout: int = 15, headers: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
581
+ loop = asyncio.get_event_loop()
582
+ return await loop.run_in_executor(None, functools.partial(_post_json, url, payload, timeout=timeout, headers=headers))
583
+
584
+
585
+ async def login_async(
586
+ key: Optional[str] = None,
587
+ provider: str = "google",
588
+ app_name: str = "Python Application",
589
+ open_browser: bool = True,
590
+ poll_interval: float = 1.0,
591
+ timeout: int = 300,
592
+ quiet: bool = False,
593
+ save_session: bool = False,
594
+ qr: bool = False
595
+ ) -> AuthUser:
596
+ """Non-blocking async login implementation for asyncio applications."""
597
+ api_key_str = _get_key(key)
598
+
599
+ init_res = await _post_json_async(AUTH_ENDPOINT, {
600
+ "action": "init",
601
+ "provider": provider,
602
+ "app_name": app_name,
603
+ "api_key": api_key_str
604
+ })
605
+
606
+ if init_res.get("status") != "success":
607
+ sys.exit(f"Failed to start authentication: {init_res.get('message', 'Unknown error')}")
608
+
609
+ session_id = init_res["session_id"]
610
+ app_secret_code = init_res["app_secret_code"]
611
+ login_url = init_res["login_url"]
612
+
613
+ if provider == "microsoft":
614
+ prov_label = "Microsoft"
615
+ elif provider == "discord":
616
+ prov_label = "Discord"
617
+ else:
618
+ prov_label = "Google"
619
+
620
+ if not quiet:
621
+ print(f"\nSign in with {prov_label}:")
622
+ print(f"{login_url}\n")
623
+ if qr:
624
+ print("Scan with your phone to sign in:")
625
+ show_qr(login_url)
626
+
627
+ if open_browser:
628
+ try:
629
+ webbrowser.open(login_url)
630
+ except Exception:
631
+ pass
632
+
633
+ if not quiet:
634
+ print("Waiting for authentication...")
635
+
636
+ start_time = time.time()
637
+ while time.time() - start_time < timeout:
638
+ await asyncio.sleep(poll_interval)
639
+ try:
640
+ poll_res = await _post_json_async(AUTH_ENDPOINT, {
641
+ "action": "poll",
642
+ "session_id": session_id,
643
+ "app_secret_code": app_secret_code,
644
+ "api_key": api_key_str
645
+ })
646
+ except Exception:
647
+ continue
648
+
649
+ if poll_res.get("status") == "success" and poll_res.get("completed"):
650
+ auth_user = _set_globals(poll_res)
651
+ if save_session:
652
+ _save_cache(poll_res.get("user") or {})
653
+ if not quiet:
654
+ print(f"Successfully authenticated as {auth_user.email or auth_user.name}!\n")
655
+ return auth_user
656
+
657
+ if poll_res.get("status") == "expired":
658
+ sys.exit("Sign-in session has expired. Please try logging in again.")
659
+
660
+ sys.exit(f"Authentication timed out after {timeout} seconds.")
661
+
662
+
663
+ async def google_login_async(**kwargs: Any) -> AuthUser:
664
+ return await login_async(provider="google", **kwargs)
665
+
666
+
667
+ async def discord_login_async(**kwargs: Any) -> AuthUser:
668
+ return await login_async(provider="discord", **kwargs)
669
+
670
+
671
+ async def microsoft_login_async(**kwargs: Any) -> AuthUser:
672
+ return await login_async(provider="microsoft", **kwargs)
673
+
674
+
675
+ async def prompt_login_async(**kwargs: Any) -> AuthUser:
676
+ """Async prompt login (runs input on thread)."""
677
+ loop = asyncio.get_event_loop()
678
+ return await loop.run_in_executor(None, functools.partial(prompt_login, **kwargs))
679
+
680
+
681
+ async def cached_login_async(max_age_days: int = 7, **kwargs: Any) -> AuthUser:
682
+ cached = get_user(max_age_days=max_age_days)
683
+ if cached:
684
+ return cached
685
+ return await login_async(save_session=True, **kwargs)
686
+
687
+
688
+ # ==============================================================================
689
+ # BACKEND WEB HELPERS
690
+ # ==============================================================================
691
+
371
692
  def create_session(
372
693
  return_url: str,
373
694
  app_secret_code: str,
@@ -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.2.1
3
+ Version: 1.3.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,6 +1,7 @@
1
1
  README.md
2
2
  pyproject.toml
3
3
  src/chdev/__init__.py
4
+ src/chdev/aio.py
4
5
  src/chdev.egg-info/PKG-INFO
5
6
  src/chdev.egg-info/SOURCES.txt
6
7
  src/chdev.egg-info/dependency_links.txt
File without changes
File without changes
File without changes