usso 0.26.1__py3-none-any.whl → 0.27.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.
usso/core.py CHANGED
@@ -2,10 +2,12 @@ import json
2
2
  import logging
3
3
  import os
4
4
  import uuid
5
- from functools import lru_cache
5
+ from urllib.parse import urlparse
6
6
 
7
7
  import cachetools.func
8
8
  import jwt
9
+ import requests
10
+ from cachetools import TTLCache, cached
9
11
  from pydantic import BaseModel, model_validator
10
12
 
11
13
  from . import b64tools
@@ -90,7 +92,7 @@ def decode_token(key, token: str, algorithms=["RS256"], **kwargs) -> dict:
90
92
  logger.error(e)
91
93
 
92
94
 
93
- @lru_cache
95
+ @cached(TTLCache(maxsize=128, ttl=10 * 60))
94
96
  def get_jwk_keys(jwk_url: str) -> jwt.PyJWKClient:
95
97
  return jwt.PyJWKClient(jwk_url, headers={"User-Agent": "usso-python"})
96
98
 
@@ -115,6 +117,15 @@ def decode_token_jwk(jwk_url: str, token: str, **kwargs) -> UserData | None:
115
117
  logger.error(e)
116
118
 
117
119
 
120
+ @cached(TTLCache(maxsize=128, ttl=10 * 60))
121
+ def get_api_key_data(jwk_url: str, api_key: str):
122
+ parsed = urlparse(jwk_url)
123
+ url = f"{parsed.scheme}://{parsed.netloc}/api_key/verify"
124
+ response = requests.post(url, json={"api_key": api_key})
125
+ response.raise_for_status()
126
+ return UserData(**response.json())
127
+
128
+
118
129
  class JWTConfig(BaseModel):
119
130
  jwk_url: str | None = None
120
131
  secret: str | None = None
@@ -147,7 +158,9 @@ class Usso:
147
158
  def __init__(
148
159
  self,
149
160
  *,
150
- jwt_config: str | dict | JWTConfig | list[str] | list[dict] | list[JWTConfig] | None = None,
161
+ jwt_config: (
162
+ str | dict | JWTConfig | list[str] | list[dict] | list[JWTConfig] | None
163
+ ) = None,
151
164
  jwk_url: str | None = None,
152
165
  secret: str | None = None,
153
166
  ):
@@ -160,7 +173,7 @@ class Usso:
160
173
  if jwk_url:
161
174
  self.jwt_configs = [JWTConfig(jwk_url=jwk_url)]
162
175
  return
163
-
176
+
164
177
  if not secret:
165
178
  secret = os.getenv("USSO_SECRET")
166
179
  if secret:
@@ -216,3 +229,31 @@ class Usso:
216
229
  status_code=401,
217
230
  error="unauthorized",
218
231
  )
232
+
233
+ def user_data_api_key(self, api_key: str, **kwargs) -> UserData | None:
234
+ """get user data from auth server by api_key."""
235
+ for jwk_config in self.jwt_configs:
236
+ try:
237
+ user_data = jwk_config.decode(api_key)
238
+ if user_data.token_type.lower() != kwargs.get("token_type", "access"):
239
+ raise USSOException(
240
+ status_code=401,
241
+ error="invalid_token_type",
242
+ message="Token type must be 'access'",
243
+ )
244
+
245
+ return user_data
246
+
247
+ except USSOException as e:
248
+ exp = e
249
+
250
+ if kwargs.get("raise_exception", True):
251
+ if exp:
252
+ raise exp
253
+ raise USSOException(
254
+ status_code=401,
255
+ error="unauthorized",
256
+ )
257
+
258
+ def user_data_from_api_key(self, api_key: str):
259
+ return get_api_key_data(self.jwt_configs[0].jwk_url, api_key)
@@ -27,16 +27,26 @@ def get_request_token(request: Request | WebSocket) -> UserData | None:
27
27
  return token
28
28
 
29
29
 
30
- def jwt_access_security_None(request: Request, jwt_config = None) -> UserData | None:
30
+ def jwt_access_security_None(request: Request, jwt_config=None) -> UserData | None:
31
31
  """Return the user associated with a token value."""
32
+ api_key = request.headers.get("x-api-key")
33
+ if api_key:
34
+ return Usso(jwt_config=jwt_config).user_data_from_api_key(api_key)
35
+
32
36
  token = get_request_token(request)
33
37
  if not token:
34
38
  return None
35
- return Usso(jwt_config=jwt_config).user_data_from_token(token, raise_exception=False)
39
+ return Usso(jwt_config=jwt_config).user_data_from_token(
40
+ token, raise_exception=False
41
+ )
36
42
 
37
43
 
38
44
  def jwt_access_security(request: Request, jwt_config=None) -> UserData | None:
39
45
  """Return the user associated with a token value."""
46
+ api_key = request.headers.get("x-api-key")
47
+ if api_key:
48
+ return Usso(jwt_config=jwt_config).user_data_from_api_key(api_key)
49
+
40
50
  token = get_request_token(request)
41
51
  if not token:
42
52
  raise USSOException(
@@ -50,6 +60,10 @@ def jwt_access_security(request: Request, jwt_config=None) -> UserData | None:
50
60
 
51
61
  def jwt_access_security_ws(websocket: WebSocket, jwt_config=None) -> UserData | None:
52
62
  """Return the user associated with a token value."""
63
+ api_key = websocket.headers.get("x-api-key")
64
+ if api_key:
65
+ return Usso(jwt_config=jwt_config).user_data_from_api_key(api_key)
66
+
53
67
  token = get_request_token(websocket)
54
68
  if not token:
55
69
  raise USSOException(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: usso
3
- Version: 0.26.1
3
+ Version: 0.27.0
4
4
  Summary: A plug-and-play client for integrating universal single sign-on (SSO) with Python frameworks, enabling secure and seamless authentication across microservices.
5
5
  Author-email: Mahdi Kiani <mahdikiany@gmail.com>
6
6
  Maintainer-email: Mahdi Kiani <mahdikiany@gmail.com>
@@ -42,28 +42,28 @@ Classifier: Programming Language :: Python :: 3 :: Only
42
42
  Requires-Python: >=3.9
43
43
  Description-Content-Type: text/markdown
44
44
  License-File: LICENSE.txt
45
- Requires-Dist: pydantic >=2
46
- Requires-Dist: requests >=2.26.0
45
+ Requires-Dist: pydantic>=2
46
+ Requires-Dist: requests>=2.26.0
47
47
  Requires-Dist: pyjwt[crypto]
48
48
  Requires-Dist: cachetools
49
- Provides-Extra: all
50
- Requires-Dist: fastapi ; extra == 'all'
51
- Requires-Dist: uvicorn ; extra == 'all'
52
- Requires-Dist: django ; extra == 'all'
53
- Requires-Dist: httpx ; extra == 'all'
54
- Requires-Dist: dev ; extra == 'all'
55
- Requires-Dist: test ; extra == 'all'
56
- Provides-Extra: dev
57
- Requires-Dist: check-manifest ; extra == 'dev'
58
- Provides-Extra: django
59
- Requires-Dist: Django >=3.2 ; extra == 'django'
60
49
  Provides-Extra: fastapi
61
- Requires-Dist: fastapi >=0.65.0 ; extra == 'fastapi'
62
- Requires-Dist: uvicorn[standard] >=0.13.0 ; extra == 'fastapi'
50
+ Requires-Dist: fastapi>=0.65.0; extra == "fastapi"
51
+ Requires-Dist: uvicorn[standard]>=0.13.0; extra == "fastapi"
52
+ Provides-Extra: django
53
+ Requires-Dist: Django>=3.2; extra == "django"
63
54
  Provides-Extra: httpx
64
- Requires-Dist: httpx ; extra == 'httpx'
55
+ Requires-Dist: httpx; extra == "httpx"
56
+ Provides-Extra: dev
57
+ Requires-Dist: check-manifest; extra == "dev"
65
58
  Provides-Extra: test
66
- Requires-Dist: coverage ; extra == 'test'
59
+ Requires-Dist: coverage; extra == "test"
60
+ Provides-Extra: all
61
+ Requires-Dist: fastapi; extra == "all"
62
+ Requires-Dist: uvicorn; extra == "all"
63
+ Requires-Dist: django; extra == "all"
64
+ Requires-Dist: httpx; extra == "all"
65
+ Requires-Dist: dev; extra == "all"
66
+ Requires-Dist: test; extra == "all"
67
67
 
68
68
  # USSO-Client
69
69
 
@@ -3,17 +3,17 @@ usso/api.py,sha256=xlDq2nZNpq3mhAvqIbGEfANHNjJpPquSeULBfS7iMJw,5094
3
3
  usso/async_api.py,sha256=rb-Xh5oudmZrPYM_iH_B75b5Z0Fvi1V1uurdcKE51w0,5551
4
4
  usso/async_session.py,sha256=nFIrtV3Tp0H-s2ZkMLU9_fVSeVGq1EtY1bGT_XOS5Vw,4336
5
5
  usso/b64tools.py,sha256=HGQ0E59vzjrQo2-4jrcY03ebtTaYwTtCZ7KgJaEmxO0,610
6
- usso/core.py,sha256=tZzoh_t7HYr-HIual4hN7K1ZVk_nGZdKpaItq5VvkJQ,7087
6
+ usso/core.py,sha256=n5Ffb4vASS6kTOyGCj9AVE4zXf9NNO0X0UbM6VjLUvg,8501
7
7
  usso/exceptions.py,sha256=hawOAuVbvQtjgRfwp1KFZ4SmV7fh720y5Gom9JVA8W8,504
8
8
  usso/httpx_session.py,sha256=jp52thSbve4gpJuVVxnKEgH5o7LbYIZ5owf3Y-7ZDbY,3067
9
9
  usso/session.py,sha256=E8qx96IWfLWp0CTo1qwb6VUWn0giUnKQIQo-ZRnneEY,2508
10
10
  usso/django/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
11
  usso/django/middleware.py,sha256=EEEpHvMQ6QiWw2HY8zQ2Aec0RCATcLWsCKeyiPWJKio,3245
12
12
  usso/fastapi/__init__.py,sha256=0EcdOzb4f3yu9nILIdGWnlyUz-0VaVX2az1e3f2BusI,201
13
- usso/fastapi/integration.py,sha256=-8MTeqGokvmUO0lxZpEWXdTMYg6n065qtnaJHOwCrzQ,1890
14
- usso-0.26.1.dist-info/LICENSE.txt,sha256=ceC9ZJOV9H6CtQDcYmHOS46NA3dHJ_WD4J9blH513pc,1081
15
- usso-0.26.1.dist-info/METADATA,sha256=GOWjHISSSaoWSO_Y5iVVrcNovcqxexM7CSpViujFz_0,4506
16
- usso-0.26.1.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
17
- usso-0.26.1.dist-info/entry_points.txt,sha256=4Zgpm5ELaAWPf0jPGJFz1_X69H7un8ycT3WdGoJ0Vvk,35
18
- usso-0.26.1.dist-info/top_level.txt,sha256=g9Jf6h1Oyidh0vPiFni7UHInTJjSvu6cUalpLTIvthg,5
19
- usso-0.26.1.dist-info/RECORD,,
13
+ usso/fastapi/integration.py,sha256=O788Pkvyv3ncTs4ObUwL_iDvzvL83MT2qnp4Al0sxXo,2321
14
+ usso-0.27.0.dist-info/LICENSE.txt,sha256=ceC9ZJOV9H6CtQDcYmHOS46NA3dHJ_WD4J9blH513pc,1081
15
+ usso-0.27.0.dist-info/METADATA,sha256=O9uJ0SPMSnFn_AXy53gDhCQ_2rOkMf_JQR3r0qr9yAY,4489
16
+ usso-0.27.0.dist-info/WHEEL,sha256=PZUExdf71Ui_so67QXpySuHtCi3-J3wvF4ORK6k_S8U,91
17
+ usso-0.27.0.dist-info/entry_points.txt,sha256=4Zgpm5ELaAWPf0jPGJFz1_X69H7un8ycT3WdGoJ0Vvk,35
18
+ usso-0.27.0.dist-info/top_level.txt,sha256=g9Jf6h1Oyidh0vPiFni7UHInTJjSvu6cUalpLTIvthg,5
19
+ usso-0.27.0.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.2.0)
2
+ Generator: setuptools (75.6.0)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5