usso 0.25.0__py3-none-any.whl → 0.25.2__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
@@ -1,13 +1,12 @@
1
+ import json
1
2
  import logging
2
3
  import os
3
4
  import uuid
4
5
  from functools import lru_cache
5
- from typing import Optional, Tuple
6
6
 
7
7
  import cachetools.func
8
8
  import jwt
9
9
  from pydantic import BaseModel, model_validator
10
- from singleton import Singleton
11
10
 
12
11
  from . import b64tools
13
12
  from .exceptions import USSOException
@@ -61,6 +60,7 @@ def get_authorization_scheme_param(
61
60
  def decode_token(key, token: str, algorithms=["RS256"], **kwargs) -> dict:
62
61
  try:
63
62
  decoded = jwt.decode(token, key, algorithms=algorithms)
63
+ decoded["data"] = decoded
64
64
  decoded["token"] = token
65
65
  return UserData(**decoded)
66
66
  except jwt.exceptions.ExpiredSignatureError:
@@ -142,33 +142,60 @@ class JWTConfig(BaseModel):
142
142
  return decode_token(self.secret, token, algorithms=[self.type])
143
143
 
144
144
 
145
- class Usso(metaclass=Singleton):
146
- def __init__(self, jwks_url: str | None = None):
147
- if jwks_url is None:
148
- jwks_url = os.getenv("USSO_JWKS_URL")
149
- self.jwks_url = jwks_url
145
+ class Usso:
146
+
147
+ def __init__(
148
+ self,
149
+ *,
150
+ jwt_config: str | dict | JWTConfig | None = None,
151
+ jwt_configs: list[str] | list[dict] | list[JWTConfig] | None = None,
152
+ ):
153
+ if jwt_config is None and jwt_configs is None:
154
+ jwt_config = os.getenv("USSO_JWT_CONFIG")
155
+
156
+ if jwt_config is None and jwt_configs is None:
157
+ jwk_url = os.getenv("USSO_JWK_URL") or os.getenv("USSO_JWKS_URL")
158
+ if not jwk_url:
159
+ self.jwt_configs = [JWTConfig(jwk_url=jwk_url)]
160
+ return
161
+
162
+ raise ValueError(
163
+ "\n".join(
164
+ [
165
+ "Either jwt_config or jwt_configs must be provided",
166
+ "or set the environment variable USSO_JWT_CONFIG or USSO_JWK_URL",
167
+ ]
168
+ )
169
+ )
170
+
171
+ def _get_config(jwt_config):
172
+ if isinstance(jwt_config, str):
173
+ jwt_config = json.loads(jwt_config)
174
+ if isinstance(jwt_config, dict):
175
+ jwt_config = JWTConfig(**jwt_config)
176
+ return jwt_config
150
177
 
151
- def get_jwk_keys(self):
152
- return get_jwk_keys(self.jwks_url)
178
+ if isinstance(jwt_config, str | dict | JWTConfig):
179
+ jwt_config = [_get_config(jwt_config)]
180
+ elif isinstance(jwt_config, list):
181
+ jwt_config = [_get_config(j) for j in jwt_config]
153
182
 
154
- def get_authorization_scheme_param(
155
- self, authorization_header_value: Optional[str]
156
- ) -> Tuple[str, str]:
157
- return get_authorization_scheme_param(authorization_header_value)
183
+ # self.jwk_url = jwt_config
184
+ self.jwt_configs = jwt_config
158
185
 
159
186
  def user_data_from_token(self, token: str, **kwargs) -> UserData | None:
160
187
  """Return the user associated with a token value."""
161
- user_data = decode_token_jwk(self.jwks_url, token, **kwargs)
162
- if user_data.token_type.lower() != kwargs.get("token_type", "access"):
163
- raise USSOException(status_code=401, error="invalid_token_type")
164
- return user_data
165
-
166
- def user_data_from_token_none(self, token: str, **kwargs) -> UserData | None:
167
- try:
168
- return self.user_data_from_token(token, **kwargs)
169
- except USSOException:
170
- # logger.error(str(e))
171
- return None
172
- except Exception:
173
- # logger.error(str(e))
174
- return None
188
+ exp = None
189
+ for jwk_config in self.jwt_configs:
190
+ try:
191
+ return jwk_config.decode(token)
192
+ except USSOException as e:
193
+ exp = e
194
+
195
+ if kwargs.get("raise_exception", True):
196
+ if exp:
197
+ raise exp
198
+ raise USSOException(
199
+ status_code=401,
200
+ error="unauthorized",
201
+ )
@@ -3,9 +3,10 @@ import logging
3
3
  from fastapi import Request, WebSocket
4
4
  from starlette.status import HTTP_401_UNAUTHORIZED
5
5
 
6
- from usso.core import UserData, Usso
7
6
  from usso.exceptions import USSOException
8
7
 
8
+ from ..core import UserData, Usso
9
+
9
10
  logger = logging.getLogger("usso")
10
11
 
11
12
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: usso
3
- Version: 0.25.0
3
+ Version: 0.25.2
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>
@@ -45,7 +45,7 @@ License-File: LICENSE.txt
45
45
  Requires-Dist: pydantic >=2
46
46
  Requires-Dist: requests >=2.26.0
47
47
  Requires-Dist: pyjwt[crypto]
48
- Requires-Dist: singleton-package
48
+ Requires-Dist: cachetools
49
49
  Provides-Extra: dev
50
50
  Requires-Dist: check-manifest ; extra == 'dev'
51
51
  Provides-Extra: django
@@ -53,7 +53,6 @@ Requires-Dist: Django >=3.2 ; extra == 'django'
53
53
  Provides-Extra: fastapi
54
54
  Requires-Dist: fastapi >=0.65.0 ; extra == 'fastapi'
55
55
  Requires-Dist: uvicorn[standard] >=0.13.0 ; extra == 'fastapi'
56
- Requires-Dist: cachetools ; extra == 'fastapi'
57
56
  Provides-Extra: test
58
57
  Requires-Dist: coverage ; extra == 'test'
59
58
 
@@ -3,18 +3,16 @@ 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=bWegFuGsWMmfz1b0upGPn5E8X3az4IOuJ-WqzRDMngM,5767
6
+ usso/core.py,sha256=7DpJplPX8aWI4wSkd-gS58ss_G_Sgq5uRqbXiKOQgeo,6512
7
7
  usso/exceptions.py,sha256=hawOAuVbvQtjgRfwp1KFZ4SmV7fh720y5Gom9JVA8W8,504
8
- usso/package_data.dat,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
8
  usso/session.py,sha256=Lky2O8FGbOMJFOMxxdE0rhpgwWKThGQfr-X9YQsFpLk,2358
10
9
  usso/django/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
11
10
  usso/django/middleware.py,sha256=EEEpHvMQ6QiWw2HY8zQ2Aec0RCATcLWsCKeyiPWJKio,3245
12
11
  usso/fastapi/__init__.py,sha256=0EcdOzb4f3yu9nILIdGWnlyUz-0VaVX2az1e3f2BusI,201
13
- usso/fastapi/auth_middleware.py,sha256=HfRbdelAQ4URwTA8hEyeq0IYBEZcbRa-utEHf5rRw_s,2710
14
- usso/fastapi/integration.py,sha256=VAUWaa7ChQ1jTtn8A136VgyG6t2kDo5pGK-3RgmNDVs,1669
15
- usso-0.25.0.dist-info/LICENSE.txt,sha256=ceC9ZJOV9H6CtQDcYmHOS46NA3dHJ_WD4J9blH513pc,1081
16
- usso-0.25.0.dist-info/METADATA,sha256=3_BvP1GtgbIGMng5NDF64x3zlcviiD0VHMiuxGGllt8,4248
17
- usso-0.25.0.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
18
- usso-0.25.0.dist-info/entry_points.txt,sha256=4Zgpm5ELaAWPf0jPGJFz1_X69H7un8ycT3WdGoJ0Vvk,35
19
- usso-0.25.0.dist-info/top_level.txt,sha256=g9Jf6h1Oyidh0vPiFni7UHInTJjSvu6cUalpLTIvthg,5
20
- usso-0.25.0.dist-info/RECORD,,
12
+ usso/fastapi/integration.py,sha256=LNKd_KStKr5CBj_CUfwkrgtiY5R8nBL61FVBWcIrhQE,1667
13
+ usso-0.25.2.dist-info/LICENSE.txt,sha256=ceC9ZJOV9H6CtQDcYmHOS46NA3dHJ_WD4J9blH513pc,1081
14
+ usso-0.25.2.dist-info/METADATA,sha256=RgDkN68nTqjXyUjX8LHcC20MFMuM7kyilJqxrI5Oyqw,4194
15
+ usso-0.25.2.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
16
+ usso-0.25.2.dist-info/entry_points.txt,sha256=4Zgpm5ELaAWPf0jPGJFz1_X69H7un8ycT3WdGoJ0Vvk,35
17
+ usso-0.25.2.dist-info/top_level.txt,sha256=g9Jf6h1Oyidh0vPiFni7UHInTJjSvu6cUalpLTIvthg,5
18
+ usso-0.25.2.dist-info/RECORD,,
@@ -1,87 +0,0 @@
1
- import json
2
- import logging
3
- import os
4
-
5
- from fastapi import Request, WebSocket
6
- from starlette.status import HTTP_401_UNAUTHORIZED
7
-
8
- from usso.exceptions import USSOException
9
-
10
- from ..core import JWTConfig, UserData
11
- from .integration import get_request_token
12
-
13
- logger = logging.getLogger("usso")
14
-
15
-
16
- class Usso:
17
-
18
- def __init__(
19
- self,
20
- jwt_config: (
21
- str | dict | JWTConfig | list[str] | list[dict] | list[JWTConfig] | None
22
- ) = None,
23
- ):
24
- if jwt_config is None:
25
- self.jwk_url = os.getenv("USSO_JWK_URL")
26
- self.jwt_configs = [JWTConfig(jwk_url=self.jwk_url)]
27
- return
28
-
29
- def _get_config(jwt_config):
30
- if isinstance(jwt_config, str):
31
- jwt_config = json.loads(jwt_config)
32
- if isinstance(jwt_config, dict):
33
- jwt_config = JWTConfig(**jwt_config)
34
- return jwt_config
35
-
36
- if isinstance(jwt_config, str | dict | JWTConfig):
37
- jwt_config = [_get_config(jwt_config)]
38
- elif isinstance(jwt_config, list):
39
- jwt_config = [_get_config(j) for j in jwt_config]
40
-
41
- # self.jwk_url = jwt_config
42
- self.jwt_configs = jwt_config
43
-
44
- def user_data_from_token(self, token: str, **kwargs) -> UserData | None:
45
- """Return the user associated with a token value."""
46
- exp = None
47
- for jwk_config in self.jwt_configs:
48
- try:
49
- return jwk_config.decode(token)
50
- except USSOException as e:
51
- exp = e
52
-
53
- if kwargs.get("raise_exception", True):
54
- if exp:
55
- raise exp
56
- raise USSOException(
57
- status_code=HTTP_401_UNAUTHORIZED,
58
- error="unauthorized",
59
- )
60
-
61
- async def jwt_access_security(self, request: Request, **kwargs) -> UserData | None:
62
- """Return the user associated with a token value."""
63
- token = get_request_token(request)
64
- if token:
65
- return self.user_data_from_token(token)
66
-
67
- if kwargs.get("raise_exception", True):
68
- raise USSOException(
69
- status_code=HTTP_401_UNAUTHORIZED,
70
- error="unauthorized",
71
- )
72
- return None
73
-
74
- async def jwt_access_security_ws(
75
- self, websocket: WebSocket, **kwargs
76
- ) -> UserData | None:
77
- """Return the user associated with a token value."""
78
- token = get_request_token(websocket)
79
- if token:
80
- return self.user_data_from_token(token)
81
-
82
- if kwargs.get("raise_exception", True):
83
- raise USSOException(
84
- status_code=HTTP_401_UNAUTHORIZED,
85
- error="unauthorized",
86
- )
87
- return None
usso/package_data.dat DELETED
File without changes
File without changes