chdev 1.2.0__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.0
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.0"
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.0"
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,17 +395,18 @@ 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:
217
404
  webbrowser.open(login_url)
218
- if not quiet:
219
- print("Browser opened. Waiting for authentication...")
220
405
  except Exception:
221
- if not quiet:
222
- print("Please open the link above in your browser to sign in.")
223
- elif not quiet:
224
- print("Please open the link above in your browser to sign in.")
406
+ pass
407
+
408
+ if not quiet:
409
+ print("Waiting for authentication...")
225
410
 
226
411
  start_time = time.time()
227
412
  while time.time() - start_time < timeout:
@@ -238,6 +423,8 @@ def login(
238
423
 
239
424
  if poll_res.get("status") == "success" and poll_res.get("completed"):
240
425
  auth_user = _set_globals(poll_res)
426
+ if save_session:
427
+ _save_cache(poll_res.get("user") or {})
241
428
  if not quiet:
242
429
  print(f"Successfully authenticated as {auth_user.email or auth_user.name}!\n")
243
430
  return auth_user
@@ -254,7 +441,9 @@ def google_login(
254
441
  open_browser: bool = True,
255
442
  poll_interval: float = 1.0,
256
443
  timeout: int = 300,
257
- quiet: bool = False
444
+ quiet: bool = False,
445
+ save_session: bool = False,
446
+ qr: bool = False
258
447
  ) -> AuthUser:
259
448
  return login(
260
449
  key=key,
@@ -263,7 +452,9 @@ def google_login(
263
452
  open_browser=open_browser,
264
453
  poll_interval=poll_interval,
265
454
  timeout=timeout,
266
- quiet=quiet
455
+ quiet=quiet,
456
+ save_session=save_session,
457
+ qr=qr
267
458
  )
268
459
 
269
460
 
@@ -273,7 +464,9 @@ def discord_login(
273
464
  open_browser: bool = True,
274
465
  poll_interval: float = 1.0,
275
466
  timeout: int = 300,
276
- quiet: bool = False
467
+ quiet: bool = False,
468
+ save_session: bool = False,
469
+ qr: bool = False
277
470
  ) -> AuthUser:
278
471
  return login(
279
472
  key=key,
@@ -282,7 +475,9 @@ def discord_login(
282
475
  open_browser=open_browser,
283
476
  poll_interval=poll_interval,
284
477
  timeout=timeout,
285
- quiet=quiet
478
+ quiet=quiet,
479
+ save_session=save_session,
480
+ qr=qr
286
481
  )
287
482
 
288
483
 
@@ -292,7 +487,9 @@ def microsoft_login(
292
487
  open_browser: bool = True,
293
488
  poll_interval: float = 1.0,
294
489
  timeout: int = 300,
295
- quiet: bool = False
490
+ quiet: bool = False,
491
+ save_session: bool = False,
492
+ qr: bool = False
296
493
  ) -> AuthUser:
297
494
  return login(
298
495
  key=key,
@@ -301,7 +498,9 @@ def microsoft_login(
301
498
  open_browser=open_browser,
302
499
  poll_interval=poll_interval,
303
500
  timeout=timeout,
304
- quiet=quiet
501
+ quiet=quiet,
502
+ save_session=save_session,
503
+ qr=qr
305
504
  )
306
505
 
307
506
 
@@ -311,7 +510,9 @@ def prompt_login(
311
510
  open_browser: bool = True,
312
511
  poll_interval: float = 1.0,
313
512
  timeout: int = 300,
314
- quiet: bool = False
513
+ quiet: bool = False,
514
+ save_session: bool = False,
515
+ qr: bool = False
315
516
  ) -> AuthUser:
316
517
  """Interactively prompts the user to choose an authentication provider in the terminal."""
317
518
  print("\nSelect Sign-In Provider:")
@@ -337,7 +538,9 @@ def prompt_login(
337
538
  open_browser=open_browser,
338
539
  poll_interval=poll_interval,
339
540
  timeout=timeout,
340
- quiet=quiet
541
+ quiet=quiet,
542
+ save_session=save_session,
543
+ qr=qr
341
544
  )
342
545
 
343
546
 
@@ -370,6 +573,122 @@ def require_auth(
370
573
  login_required = require_auth
371
574
 
372
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
+
373
692
  def create_session(
374
693
  return_url: str,
375
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.0
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