dash-auth-async 1.2.0__tar.gz → 1.2.1__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.
Files changed (23) hide show
  1. {dash_auth_async-1.2.0/dash_auth_async.egg-info → dash_auth_async-1.2.1}/PKG-INFO +1 -5
  2. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/__init__.py +9 -13
  3. dash_auth_async-1.2.1/dash_auth_async/_optional.py +24 -0
  4. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/auth.py +36 -14
  5. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/backends.py +92 -14
  6. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/basic_auth.py +55 -23
  7. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/group_protection.py +46 -28
  8. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/oidc_auth.py +103 -38
  9. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/public_routes.py +26 -11
  10. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/quart_client.py +44 -9
  11. dash_auth_async-1.2.1/dash_auth_async/version.py +3 -0
  12. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async/websocket_auth.py +50 -35
  13. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1/dash_auth_async.egg-info}/PKG-INFO +1 -5
  14. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async.egg-info/SOURCES.txt +1 -0
  15. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async.egg-info/requires.txt +0 -4
  16. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/pyproject.toml +35 -5
  17. dash_auth_async-1.2.0/dash_auth_async/version.py +0 -1
  18. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/LICENSE +0 -0
  19. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/MANIFEST.in +0 -0
  20. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/README.md +0 -0
  21. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async.egg-info/dependency_links.txt +0 -0
  22. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/dash_auth_async.egg-info/top_level.txt +0 -0
  23. {dash_auth_async-1.2.0 → dash_auth_async-1.2.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dash-auth-async
3
- Version: 1.2.0
3
+ Version: 1.2.1
4
4
  Summary: Dash Authorization Package.
5
5
  Author-email: Jonas Schrage <119843859+joschrag@users.noreply.github.com>
6
6
  License: MIT
@@ -24,7 +24,6 @@ Classifier: Programming Language :: Python :: 3.12
24
24
  Classifier: Programming Language :: Python :: 3.13
25
25
  Classifier: Programming Language :: Python :: 3.14
26
26
  Classifier: Topic :: Database :: Front-Ends
27
- Classifier: Topic :: Office/Business :: Financial :: Spreadsheet
28
27
  Classifier: Topic :: Scientific/Engineering :: Visualization
29
28
  Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
30
29
  Classifier: Topic :: Software Development :: Widget Sets
@@ -33,11 +32,8 @@ Description-Content-Type: text/markdown
33
32
  License-File: LICENSE
34
33
  Requires-Dist: authlib>=1.7.2
35
34
  Requires-Dist: flask>=3.1.3
36
- Requires-Dist: requests[security]>=2.34.2
37
35
  Requires-Dist: werkzeug>=3.1.8
38
36
  Requires-Dist: dash>=2
39
- Provides-Extra: oidc
40
- Requires-Dist: authlib; extra == "oidc"
41
37
  Provides-Extra: fastapi
42
38
  Requires-Dist: dash[fastapi]>=4.2.0; extra == "fastapi"
43
39
  Provides-Extra: quart
@@ -1,24 +1,20 @@
1
- from .public_routes import add_public_routes, public_callback
2
- from .basic_auth import BasicAuth
3
- from .group_protection import list_groups, check_groups, protected, protected_callback
1
+ """Authentication and authorization for Dash apps on sync and async backends."""
4
2
 
5
- # oidc auth requires authlib, install with `pip install dash-auth[oidc]`
6
- try:
7
- from .oidc_auth import OIDCAuth, get_oauth
8
- except ModuleNotFoundError:
9
- pass
3
+ from ._optional import OIDCAuth, get_oauth
4
+ from .basic_auth import BasicAuth
5
+ from .group_protection import check_groups, list_groups, protected, protected_callback
6
+ from .public_routes import add_public_routes, public_callback
10
7
  from .version import __version__
11
8
 
12
-
13
9
  __all__ = [
10
+ "BasicAuth",
11
+ "OIDCAuth",
12
+ "__version__",
14
13
  "add_public_routes",
15
14
  "check_groups",
16
- "list_groups",
17
15
  "get_oauth",
16
+ "list_groups",
18
17
  "protected",
19
18
  "protected_callback",
20
19
  "public_callback",
21
- "BasicAuth",
22
- "OIDCAuth",
23
- "__version__",
24
20
  ]
@@ -0,0 +1,24 @@
1
+ """Optional re-exports whose dependencies are not always installed.
2
+
3
+ ``OIDCAuth`` and ``get_oauth`` require authlib
4
+ (``pip install dash-auth-async[oidc]``). When it is missing they resolve to
5
+ ``None`` at runtime so importing the package never fails; attempting to use
6
+ ``OIDCAuth`` without authlib then raises a clear error at the call site.
7
+
8
+ This logic lives here, rather than in ``__init__``, so the package's
9
+ ``__init__`` stays a pure re-export facade. Type-checkers see the real symbols
10
+ (authlib assumed present); the runtime ``None`` fallback is invisible to them.
11
+ """
12
+
13
+ from typing import TYPE_CHECKING
14
+
15
+ if TYPE_CHECKING:
16
+ from .oidc_auth import OIDCAuth, get_oauth
17
+ else:
18
+ try:
19
+ from .oidc_auth import OIDCAuth, get_oauth
20
+ except ModuleNotFoundError:
21
+ OIDCAuth = None
22
+ get_oauth = None
23
+
24
+ __all__ = ["OIDCAuth", "get_oauth"]
@@ -1,10 +1,10 @@
1
- from __future__ import absolute_import
1
+ """Framework-agnostic authentication base class for Dash."""
2
+
2
3
  from abc import ABC, abstractmethod
3
- from typing import Optional
4
4
 
5
5
  from dash import Dash
6
- from .backends import Backend, detect_backend, set_active_backend
7
6
 
7
+ from .backends import Backend, detect_backend, set_active_backend
8
8
  from .public_routes import (
9
9
  add_public_routes,
10
10
  get_public_callbacks,
@@ -15,11 +15,13 @@ from .websocket_auth import enable_ws_auth
15
15
 
16
16
 
17
17
  class Auth(ABC):
18
+ """Base class holding the framework-agnostic auth decision logic."""
19
+
18
20
  def __init__(
19
21
  self,
20
22
  app: Dash,
21
- public_routes: Optional[list] = None,
22
- backend: Optional[Backend] = None,
23
+ public_routes: list | None = None,
24
+ backend: Backend | None = None,
23
25
  **obsolete,
24
26
  ):
25
27
  """Auth base class for authentication in Dash.
@@ -27,8 +29,10 @@ class Auth(ABC):
27
29
  :param app: Dash app
28
30
  :param public_routes: list of public routes, routes should follow the
29
31
  Flask route syntax
30
- """
31
32
 
33
+ Raises:
34
+ TypeError: if any deprecated/unexpected keyword argument is passed.
35
+ """
32
36
  # Deprecated arguments
33
37
  if obsolete:
34
38
  raise TypeError(f"Auth got unexpected keyword arguments: {list(obsolete)}")
@@ -43,14 +47,28 @@ class Auth(ABC):
43
47
 
44
48
  @property
45
49
  def request(self):
50
+ """The active backend's request proxy.
51
+
52
+ Returns:
53
+ The framework-specific request object for the current request.
54
+ """
46
55
  return self.backend.request
47
56
 
48
57
  @property
49
58
  def session(self):
59
+ """The active backend's session proxy.
60
+
61
+ Returns:
62
+ The framework-specific session mapping for the current request.
63
+ """
50
64
  return self.backend.session
51
65
 
52
66
  def _callback_path(self) -> str:
53
- """Path of Dash's callback route, including any URL base prefix."""
67
+ """Path of Dash's callback route, including any URL base prefix.
68
+
69
+ Returns:
70
+ The fully-qualified ``_dash-update-component`` path.
71
+ """
54
72
  url_base = get_url_base(self.app)
55
73
  return f"{url_base.rstrip('/')}/_dash-update-component"
56
74
 
@@ -67,14 +85,16 @@ class Auth(ABC):
67
85
  self._authorize,
68
86
  )
69
87
 
70
- def _authorize(self, path: str, body: Optional[dict]):
88
+ def _authorize(self, path: str, body: dict | None):
71
89
  """Decide whether a request may proceed.
72
90
 
73
91
  Pure decision logic shared by all backends: receives the request
74
92
  path and the parsed JSON body (only provided for the Dash callback
75
- route). Returns None to allow the request, or a login response.
76
- """
93
+ route).
77
94
 
95
+ Returns:
96
+ None to allow the request, or a login response to reject it.
97
+ """
78
98
  public_routes = get_public_routes(self.app)
79
99
  public_callbacks = get_public_callbacks(self.app)
80
100
  if path == self._callback_path():
@@ -109,7 +129,7 @@ class Auth(ABC):
109
129
  # Otherwise, ask the user to log in
110
130
  return self.login_request()
111
131
 
112
- def authorize_ws(self, payload: Optional[dict], user: Optional[dict]) -> bool:
132
+ def authorize_ws(self, payload: dict | None, user: dict | None) -> bool:
113
133
  """Decide whether a WebSocket callback_request may run.
114
134
 
115
135
  Mirrors ``_authorize``'s public checks but, because there is no
@@ -120,7 +140,9 @@ class Auth(ABC):
120
140
  :param payload: the callback payload (same shape as the HTTP
121
141
  ``_dash-update-component`` body: ``output``, ``inputs``, ...)
122
142
  :param user: ``session["user"]`` or ``None``
123
- :return: True to allow the callback, False to reject the connection
143
+
144
+ Returns:
145
+ True to allow the callback, False to reject the connection.
124
146
  """
125
147
  payload = payload or {}
126
148
  public_callbacks = get_public_callbacks(self.app)
@@ -143,8 +165,8 @@ class Auth(ABC):
143
165
 
144
166
  @abstractmethod
145
167
  def is_authorized(self):
146
- pass
168
+ """Return whether the current request is authenticated."""
147
169
 
148
170
  @abstractmethod
149
171
  def login_request(self):
150
- pass
172
+ """Return the response that challenges an unauthenticated client."""
@@ -1,8 +1,11 @@
1
+ """Framework adapters isolating Flask/Quart-specific request and session I/O."""
2
+
1
3
  from __future__ import annotations
2
4
 
3
5
  import inspect
4
6
  from abc import ABC, abstractmethod
5
- from typing import Any, Callable, MutableMapping, Optional
7
+ from collections.abc import Callable, MutableMapping
8
+ from typing import Any
6
9
 
7
10
  import flask
8
11
 
@@ -35,7 +38,7 @@ class Backend(ABC):
35
38
  self,
36
39
  server,
37
40
  needs_body: Callable[[str], bool],
38
- decide: Callable[[str, Optional[dict]], Any],
41
+ decide: Callable[[str, dict | None], Any],
39
42
  ) -> None:
40
43
  """Register a before-request auth hook on the server.
41
44
 
@@ -48,28 +51,52 @@ class Backend(ABC):
48
51
  """
49
52
 
50
53
  @abstractmethod
51
- def url_for(self, endpoint: str, **values) -> str: ...
54
+ def url_for(self, endpoint: str, **values) -> str:
55
+ """Build a URL for the given endpoint on this backend."""
52
56
 
53
57
  @abstractmethod
54
- def redirect(self, location: str) -> Any: ...
58
+ def redirect(self, location: str) -> Any:
59
+ """Return a redirect response to the given location."""
55
60
 
56
61
 
57
62
  class FlaskBackend(Backend):
63
+ """Backend adapter for a Flask server."""
64
+
58
65
  # Properties, not class attributes: ABCMeta probes every namespace
59
66
  # value for __isabstractmethod__ at class creation, which unwraps
60
67
  # the context-local proxies outside any request and raises.
61
68
  @property
62
69
  def request(self) -> Any:
70
+ """Flask's request context-local proxy.
71
+
72
+ Returns:
73
+ The Flask request proxy.
74
+ """
63
75
  return flask.request
64
76
 
65
77
  @property
66
78
  def session(self) -> MutableMapping:
79
+ """Flask's session mapping.
80
+
81
+ Returns:
82
+ The Flask session proxy.
83
+ """
67
84
  return flask.session
68
85
 
69
- def has_request_context(self) -> bool:
86
+ # The methods below are thin adapters over module-level framework
87
+ # functions; they must stay instance methods to satisfy the Backend
88
+ # interface, so PLR6301 (no-self-use) is suppressed on each.
89
+ def has_request_context(self) -> bool: # noqa: PLR6301
90
+ """Whether a Flask request context is currently active.
91
+
92
+ Returns:
93
+ True if a request context is active.
94
+ """
70
95
  return flask.has_request_context()
71
96
 
72
- def register_auth_hook(self, server, needs_body, decide) -> None:
97
+ def register_auth_hook(self, server, needs_body, decide) -> None: # noqa: PLR6301
98
+ """Register the before-request auth hook on a Flask server."""
99
+
73
100
  @server.before_request
74
101
  def before_request_auth():
75
102
  body = (
@@ -79,15 +106,32 @@ class FlaskBackend(Backend):
79
106
  )
80
107
  return decide(flask.request.path, body)
81
108
 
82
- def url_for(self, endpoint: str, **values) -> str:
109
+ def url_for(self, endpoint: str, **values) -> str: # noqa: PLR6301
110
+ """Build a URL for a Flask endpoint.
111
+
112
+ Returns:
113
+ The URL string for ``endpoint``.
114
+ """
83
115
  return flask.url_for(endpoint, **values)
84
116
 
85
- def redirect(self, location: str) -> Any:
117
+ def redirect(self, location: str) -> Any: # noqa: PLR6301
118
+ """Build a Flask redirect response to ``location``.
119
+
120
+ Returns:
121
+ A Flask redirect response.
122
+ """
86
123
  return flask.redirect(location)
87
124
 
88
125
 
89
126
  class QuartBackend(Backend):
127
+ """Backend adapter for a Quart (async) server."""
128
+
90
129
  def __init__(self) -> None:
130
+ """Create the Quart backend, requiring the optional ``quart`` extra.
131
+
132
+ Raises:
133
+ ImportError: if Quart is not installed.
134
+ """
91
135
  if quart is None:
92
136
  raise ImportError(
93
137
  "Quart is not installed. Please install it with `pip install quart` "
@@ -96,16 +140,40 @@ class QuartBackend(Backend):
96
140
 
97
141
  @property
98
142
  def request(self) -> Any:
143
+ """Quart's request context-local proxy.
144
+
145
+ Returns:
146
+ The Quart request proxy.
147
+ """
99
148
  return quart.request
100
149
 
101
150
  @property
102
151
  def session(self) -> MutableMapping:
152
+ """Quart's session mapping.
153
+
154
+ Returns:
155
+ The Quart session proxy.
156
+ """
103
157
  return quart.session
104
158
 
105
- def has_request_context(self) -> bool:
159
+ # The methods below are thin adapters over module-level framework
160
+ # functions; they must stay instance methods to satisfy the Backend
161
+ # interface, so PLR6301 (no-self-use) is suppressed on each.
162
+ def has_request_context(self) -> bool: # noqa: PLR6301
163
+ """Whether a Quart request context is currently active.
164
+
165
+ Returns:
166
+ True if a request context is active.
167
+ """
106
168
  return quart.has_request_context()
107
169
 
108
- def register_auth_hook(self, server, needs_body, decide) -> None:
170
+ def register_auth_hook(self, server, needs_body, decide) -> None: # noqa: PLR6301
171
+ """Register the before-request auth hook on a Quart server.
172
+
173
+ Awaits both the request body and the (possibly coroutine) decision so
174
+ async auth logic is preserved.
175
+ """
176
+
109
177
  @server.before_request
110
178
  async def before_request_auth():
111
179
  body = (
@@ -118,10 +186,20 @@ class QuartBackend(Backend):
118
186
  return await result
119
187
  return result
120
188
 
121
- def url_for(self, endpoint: str, **values) -> str:
189
+ def url_for(self, endpoint: str, **values) -> str: # noqa: PLR6301
190
+ """Build a URL for a Quart endpoint.
191
+
192
+ Returns:
193
+ The URL string for ``endpoint``.
194
+ """
122
195
  return quart.url_for(endpoint, **values)
123
196
 
124
- def redirect(self, location: str) -> Any:
197
+ def redirect(self, location: str) -> Any: # noqa: PLR6301
198
+ """Build a Quart redirect response to ``location``.
199
+
200
+ Returns:
201
+ A Quart redirect response.
202
+ """
125
203
  return quart.redirect(location)
126
204
 
127
205
 
@@ -141,7 +219,7 @@ def detect_backend(server: Any) -> Backend:
141
219
 
142
220
 
143
221
  # One backend per process, matching how Dash apps are deployed.
144
- _active_backend: Optional[Backend] = None
222
+ _active_backend: Backend | None = None
145
223
  _DEFAULT_BACKEND = FlaskBackend()
146
224
 
147
225
 
@@ -151,7 +229,7 @@ def set_active_backend(backend: Backend) -> None:
151
229
  Called by Auth.__init__; group_protection functions run inside Dash
152
230
  callbacks with no auth instance in scope and look the backend up here.
153
231
  """
154
- global _active_backend
232
+ global _active_backend # noqa: PLW0603 — one backend per process, by design
155
233
  _active_backend = backend
156
234
 
157
235
 
@@ -1,21 +1,29 @@
1
+ """Basic (username/password) HTTP authentication for Dash apps."""
2
+
1
3
  import base64
4
+ import binascii
5
+ import hmac
2
6
  import logging
3
- from typing import Dict, List, Optional, Union, Callable, cast
7
+ from collections.abc import Callable
8
+ from typing import cast
9
+
4
10
  from dash import Dash
5
11
 
6
12
  from .auth import Auth
7
13
 
8
- UserGroups = Dict[str, List[str]]
14
+ UserGroups = dict[str, list[str]]
9
15
 
10
16
 
11
17
  class BasicAuth(Auth):
12
- def __init__(
18
+ """Protect a Dash app with HTTP Basic authentication."""
19
+
20
+ def __init__( # noqa: PLR0913, PLR0917 — configuration constructor
13
21
  self,
14
22
  app: Dash,
15
- username_password_list: Union[list, dict] | None = None,
23
+ username_password_list: list | dict | None = None,
16
24
  auth_func: Callable | None = None,
17
- public_routes: Optional[list] = None,
18
- user_groups: Optional[Union[UserGroups, Callable[[str], UserGroups]]] = None,
25
+ public_routes: list | None = None,
26
+ user_groups: UserGroups | Callable[[str], UserGroups] | None = None,
19
27
  secret_key: str | None = None,
20
28
  ):
21
29
  """Add basic authentication to Dash.
@@ -43,8 +51,11 @@ class BasicAuth(Auth):
43
51
  Note that you should not do this dynamically:
44
52
  you should create a key and then assign the value of
45
53
  that key in your code.
54
+
55
+ Raises:
56
+ ValueError: if both ``auth_func`` and ``username_password_list``
57
+ are supplied, or if neither is.
46
58
  """
47
- super().__init__(app, public_routes=public_routes)
48
59
  self._auth_func = auth_func
49
60
  if isinstance(user_groups, dict):
50
61
  self._user_groups_dict: UserGroups | None = cast(UserGroups, user_groups)
@@ -62,26 +73,39 @@ class BasicAuth(Auth):
62
73
  "(auth_func kwarg) or username_password_list, "
63
74
  "it cannot use both."
64
75
  )
76
+ elif username_password_list is None:
77
+ raise ValueError(
78
+ "BasicAuth requires username/password map "
79
+ "or user-defined authorization function."
80
+ )
65
81
  else:
66
- if username_password_list is None:
67
- raise ValueError(
68
- "BasicAuth requires username/password map "
69
- "or user-defined authorization function."
70
- )
71
- else:
72
- self._users = (
73
- username_password_list
74
- if isinstance(username_password_list, dict)
75
- else {k: v for k, v in username_password_list}
76
- )
82
+ self._users = (
83
+ username_password_list
84
+ if isinstance(username_password_list, dict)
85
+ else {k: v for k, v in username_password_list}
86
+ )
87
+ super().__init__(app, public_routes=public_routes)
77
88
 
78
89
  def is_authorized(self):
90
+ """Return whether the request carries valid Basic credentials.
91
+
92
+ Parses the ``Authorization`` header; a missing or malformed header
93
+ returns ``False`` (surfacing as a 401 rather than a 500). On success
94
+ the authenticated user is stored in the session.
95
+
96
+ :return: True if the credentials are valid, otherwise False.
97
+ """
79
98
  header = self.request.headers.get("Authorization", None)
80
99
  if not header:
81
100
  return False
82
- username_password = base64.b64decode(header.split("Basic ")[1])
83
- username_password_utf8 = username_password.decode("utf-8")
84
- username, password = username_password_utf8.split(":", 1)
101
+ try:
102
+ username_password = base64.b64decode(
103
+ header.split("Basic ")[1], validate=True
104
+ )
105
+ username_password_utf8 = username_password.decode("utf-8")
106
+ username, password = username_password_utf8.split(":", 1)
107
+ except (binascii.Error, UnicodeEncodeError, ValueError, IndexError):
108
+ return False
85
109
  authorized = False
86
110
  if self._auth_func is not None:
87
111
  try:
@@ -90,7 +114,10 @@ class BasicAuth(Auth):
90
114
  logging.exception("Error in authorization function.")
91
115
  return False
92
116
  else:
93
- authorized = self._users.get(username) == password
117
+ stored_password = self._users.get(username)
118
+ if stored_password is None:
119
+ return authorized
120
+ authorized = hmac.compare_digest(stored_password, password)
94
121
  if authorized:
95
122
  try:
96
123
  self.session["user"] = {"email": username, "groups": []}
@@ -104,7 +131,12 @@ class BasicAuth(Auth):
104
131
  logging.warning("Session is not available. Have you set a secret key?")
105
132
  return authorized
106
133
 
107
- def login_request(self):
134
+ def login_request(self): # noqa: PLR6301 — overrides Auth.login_request
135
+ """Return a 401 response prompting the browser for credentials.
136
+
137
+ :return: a ``(body, status, headers)`` tuple challenging the client
138
+ with HTTP Basic authentication.
139
+ """
108
140
  return (
109
141
  "Login Required",
110
142
  401,