flask-construct-ui 0.9.5__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.
Files changed (80) hide show
  1. flask_construct_ui/__init__.py +82 -0
  2. flask_construct_ui/auth.py +290 -0
  3. flask_construct_ui/base.py +1259 -0
  4. flask_construct_ui/components.py +812 -0
  5. flask_construct_ui/crud.py +1641 -0
  6. flask_construct_ui/csrf.py +39 -0
  7. flask_construct_ui/data.py +257 -0
  8. flask_construct_ui/data_sqlalchemy.py +304 -0
  9. flask_construct_ui/forms.py +130 -0
  10. flask_construct_ui/headless.py +110 -0
  11. flask_construct_ui/icons.py +158 -0
  12. flask_construct_ui/l10n/en/main.flt +82 -0
  13. flask_construct_ui/l10n/sv/main.flt +82 -0
  14. flask_construct_ui/language.py +100 -0
  15. flask_construct_ui/navbar.py +54 -0
  16. flask_construct_ui/navigation.py +58 -0
  17. flask_construct_ui/orgmode.py +338 -0
  18. flask_construct_ui/pagination.py +39 -0
  19. flask_construct_ui/py.typed +0 -0
  20. flask_construct_ui/sanitize.py +25 -0
  21. flask_construct_ui/schema.py +507 -0
  22. flask_construct_ui/static/css/prosemirror-bundle.min.css +1 -0
  23. flask_construct_ui/static/css/unpoly.min.css +6 -0
  24. flask_construct_ui/static/js/construct-core.min.js +1 -0
  25. flask_construct_ui/static/js/prosemirror-bundle.min.js +34 -0
  26. flask_construct_ui/static/js/unpoly.min.js +1 -0
  27. flask_construct_ui/static/themes/whitelabel/css/whitelabel.css +720 -0
  28. flask_construct_ui/static/themes/whitelabel/designs/adminlte.css +94 -0
  29. flask_construct_ui/static/themes/whitelabel/designs/sandstone.css +64 -0
  30. flask_construct_ui/static/themes/whitelabel/fonts/bootstrap-icons/LICENSE.txt +21 -0
  31. flask_construct_ui/static/themes/whitelabel/fonts/bootstrap-icons/bootstrap-icons.min.css +5 -0
  32. flask_construct_ui/static/themes/whitelabel/fonts/bootstrap-icons/fonts/bootstrap-icons.woff +0 -0
  33. flask_construct_ui/static/themes/whitelabel/fonts/bootstrap-icons/fonts/bootstrap-icons.woff2 +0 -0
  34. flask_construct_ui/static/themes/whitelabel/fonts/material-symbols/LICENSE.txt +202 -0
  35. flask_construct_ui/static/themes/whitelabel/fonts/material-symbols/material-symbols-outlined.woff2 +0 -0
  36. flask_construct_ui/static/themes/whitelabel/fonts/material-symbols/material-symbols.css +26 -0
  37. flask_construct_ui/templates/structure/base.html +5 -0
  38. flask_construct_ui/templates/structure/flashes.html +7 -0
  39. flask_construct_ui/templates/structure/public.html +18 -0
  40. flask_construct_ui/templates/themes/whitelabel/components/_form_field.html +69 -0
  41. flask_construct_ui/templates/themes/whitelabel/components/button.html +16 -0
  42. flask_construct_ui/templates/themes/whitelabel/components/calendar.html +30 -0
  43. flask_construct_ui/templates/themes/whitelabel/components/calendarmini.html +30 -0
  44. flask_construct_ui/templates/themes/whitelabel/components/card.html +25 -0
  45. flask_construct_ui/templates/themes/whitelabel/components/chart.html +5 -0
  46. flask_construct_ui/templates/themes/whitelabel/components/form.html +61 -0
  47. flask_construct_ui/templates/themes/whitelabel/components/grid_layout.html +5 -0
  48. flask_construct_ui/templates/themes/whitelabel/components/horizontal_layout.html +5 -0
  49. flask_construct_ui/templates/themes/whitelabel/components/live.html +40 -0
  50. flask_construct_ui/templates/themes/whitelabel/components/main.html +4 -0
  51. flask_construct_ui/templates/themes/whitelabel/components/markup.html +1 -0
  52. flask_construct_ui/templates/themes/whitelabel/components/rich_text.html +19 -0
  53. flask_construct_ui/templates/themes/whitelabel/components/table.html +30 -0
  54. flask_construct_ui/templates/themes/whitelabel/components/tabs.html +30 -0
  55. flask_construct_ui/templates/themes/whitelabel/components/text.html +26 -0
  56. flask_construct_ui/templates/themes/whitelabel/components/vertical_layout.html +5 -0
  57. flask_construct_ui/templates/themes/whitelabel/crud/_macros.html +962 -0
  58. flask_construct_ui/templates/themes/whitelabel/crud/_many_related_options.html +26 -0
  59. flask_construct_ui/templates/themes/whitelabel/crud/_related_child_form.html +98 -0
  60. flask_construct_ui/templates/themes/whitelabel/crud/_related_child_list.html +136 -0
  61. flask_construct_ui/templates/themes/whitelabel/crud/_related_options.html +15 -0
  62. flask_construct_ui/templates/themes/whitelabel/crud/create.html +45 -0
  63. flask_construct_ui/templates/themes/whitelabel/crud/edit.html +125 -0
  64. flask_construct_ui/templates/themes/whitelabel/crud/listindex.html +238 -0
  65. flask_construct_ui/templates/themes/whitelabel/crud/related_crud_tab_child_view.html +33 -0
  66. flask_construct_ui/templates/themes/whitelabel/crud/related_crud_tab_form.html +125 -0
  67. flask_construct_ui/templates/themes/whitelabel/crud/related_crud_tab_list.html +140 -0
  68. flask_construct_ui/templates/themes/whitelabel/crud/tab_view.html +38 -0
  69. flask_construct_ui/templates/themes/whitelabel/errors/forbidden.html +16 -0
  70. flask_construct_ui/templates/themes/whitelabel/navbar/notifications.html +26 -0
  71. flask_construct_ui/templates/themes/whitelabel/navbar/search_results.html +31 -0
  72. flask_construct_ui/templates/themes/whitelabel/style/_flashes.html +16 -0
  73. flask_construct_ui/templates/themes/whitelabel/style/base_full.html +181 -0
  74. flask_construct_ui/templates/themes/whitelabel/style/base_partial.html +16 -0
  75. flask_construct_ui/validation.py +422 -0
  76. flask_construct_ui-0.9.5.dist-info/METADATA +60 -0
  77. flask_construct_ui-0.9.5.dist-info/RECORD +80 -0
  78. flask_construct_ui-0.9.5.dist-info/WHEEL +5 -0
  79. flask_construct_ui-0.9.5.dist-info/licenses/LICENSE +165 -0
  80. flask_construct_ui-0.9.5.dist-info/top_level.txt +1 -0
@@ -0,0 +1,82 @@
1
+ from .base import FlaskConstructUI as FlaskConstructUI
2
+ from .base import PageBase as PageBase
3
+ from .crud import CrudPageBase as CrudPageBase, RelatedCrudTab as RelatedCrudTab
4
+ from .base import BaseIndexView as BaseIndexView
5
+ from .base import expose as expose
6
+ from .base import list_action as list_action
7
+ from .base import tab_action as tab_action
8
+ from .base import edit_action as edit_action
9
+ from .base import datasource as datasource
10
+ from .base import livesource as livesource
11
+ from .base import SSE_DONE as SSE_DONE
12
+
13
+ # Component-based pages and the component library. Exposed at the package root
14
+ # so ComponentPageBase apps and companion/extension authors can build UI from
15
+ # component trees without reaching into submodules. The `components` namespace
16
+ # (e.g. ``components.Card(...)``) is the idiomatic accessor; the individual
17
+ # classes are exported too for explicit imports and type hints.
18
+ from .base import ComponentPageBase as ComponentPageBase
19
+ from .components import (
20
+ components as components,
21
+ Component as Component,
22
+ Field as Field,
23
+ ChartType as ChartType,
24
+ find_component as find_component,
25
+ find_component_by_id as find_component_by_id,
26
+ LiveComponent as LiveComponent,
27
+ VerticalLayoutComponent as VerticalLayoutComponent,
28
+ HorizontalLayoutComponent as HorizontalLayoutComponent,
29
+ GridLayoutComponent as GridLayoutComponent,
30
+ CardComponent as CardComponent,
31
+ TabsComponent as TabsComponent,
32
+ FormComponent as FormComponent,
33
+ ChartComponent as ChartComponent,
34
+ TextComponent as TextComponent,
35
+ MarkupComponent as MarkupComponent,
36
+ RichTextComponent as RichTextComponent,
37
+ ButtonComponent as ButtonComponent,
38
+ TableComponent as TableComponent,
39
+ CalendarComponent as CalendarComponent,
40
+ )
41
+
42
+ # Authentication & authorization
43
+ from .auth import (
44
+ AuthProvider as AuthProvider,
45
+ FlaskSecurityAuth as FlaskSecurityAuth,
46
+ FlaskOIDCAuth as FlaskOIDCAuth,
47
+ public as public,
48
+ require_groups as require_groups,
49
+ )
50
+
51
+ # Navbar features
52
+ from .navbar import (
53
+ NavbarFeature as NavbarFeature,
54
+ GlobalSearch as GlobalSearch,
55
+ Notifications as Notifications,
56
+ Notice as Notice,
57
+ SearchResult as SearchResult,
58
+ )
59
+
60
+ # from .data_sqlalchemy import DataSQLAlchemy
61
+ from .schema import dataschema as dataschema
62
+ from .schema import schema as schema
63
+ from .schema import SchemaField as SchemaField
64
+
65
+ # Icon registry (for extension/companion libraries)
66
+ from .icons import (
67
+ register_icons as register_icons,
68
+ render_icon as render_icon,
69
+ ICONS as ICONS,
70
+ )
71
+
72
+ # Headless sub-library helpers
73
+ from .headless import (
74
+ sse_event as sse_event,
75
+ sse_response as sse_response,
76
+ live_attributes as live_attributes,
77
+ live_container as live_container,
78
+ )
79
+
80
+ # HTML sanitizer (allowlist-based; for trusted-HTML surfaces such as
81
+ # LiveComponent format="raw" and TextComponent format="html")
82
+ from .sanitize import sanitize_html as sanitize_html
@@ -0,0 +1,290 @@
1
+ from __future__ import annotations
2
+
3
+ from flask import (
4
+ abort,
5
+ current_app,
6
+ g,
7
+ redirect,
8
+ render_template,
9
+ request,
10
+ url_for,
11
+ )
12
+
13
+ # --- Authentication & authorization ---------------------------------------
14
+ # Construct routes are guarded fail-closed: once an ``AuthProvider`` is passed
15
+ # to ``FlaskConstructUI(auth=...)`` every construct-owned route requires login
16
+ # by default. Routes opt out with ``@public`` (or a page-wide
17
+ # ``login_required = False``) and opt up with ``@require_groups(...)`` (or a
18
+ # page-wide ``required_groups``). The enforcement point is a blueprint-scoped
19
+ # ``before_request`` in ``base.py`` (see ``auth_protect``), which is why this
20
+ # covers the dynamically-registered RCRUD nested routes too.
21
+ #
22
+ # The boundary is server-side, so it behaves identically with JavaScript on or
23
+ # off: an unauthenticated request gets a plain 302 to the login endpoint (a
24
+ # browser follows it without JS; Unpoly follows it too) and an authenticated
25
+ # request lacking the required group gets a server-rendered themed 403 page.
26
+
27
+
28
+ def public(f):
29
+ """Mark a view as not login-protected (reachable while unauthenticated)."""
30
+ f._construct_auth = {"public": True}
31
+ return f
32
+
33
+
34
+ def require_groups(*groups, mode="any"):
35
+ """Require the current user to belong to the given group(s).
36
+
37
+ ``mode="any"`` (default) passes if the user is in at least one of
38
+ ``groups``; ``mode="all"`` requires membership in every one. Implies login.
39
+ """
40
+
41
+ def wrap(f):
42
+ f._construct_auth = {"groups": tuple(groups), "mode": mode}
43
+ return f
44
+
45
+ return wrap
46
+
47
+
48
+ class AuthProvider:
49
+ """Adapter between Construct's route guard and a host auth stack.
50
+
51
+ Subclasses only need to answer two questions — ``is_authenticated`` and
52
+ ``current_groups``. The response helpers below are concrete and Unpoly-aware
53
+ and are rarely overridden. Ship-with adapters: :class:`FlaskSecurityAuth`,
54
+ :class:`FlaskOIDCAuth`. Write a custom one by subclassing this.
55
+ """
56
+
57
+ #: Flask endpoint name (or literal path) to send unauthenticated users to.
58
+ #: Overridden by the ``CONSTRUCT_LOGIN_ENDPOINT`` config when set.
59
+ login_endpoint = None
60
+
61
+ def is_authenticated(self) -> bool:
62
+ raise NotImplementedError
63
+
64
+ def current_groups(self) -> set[str]:
65
+ """Return the set of group/role names the current user belongs to."""
66
+ return set()
67
+
68
+ def has_groups(self, required, mode="any") -> bool:
69
+ have = self.current_groups()
70
+ if mode == "all":
71
+ return all(g in have for g in required)
72
+ return any(g in have for g in required)
73
+
74
+ def current_user_name(self) -> str | None:
75
+ """Display name for the logged-in user, or None if unavailable."""
76
+ return None
77
+
78
+ def current_user(self) -> dict | None:
79
+ """Normalized view of the logged-in user, or None if unauthenticated.
80
+
81
+ Returns a dict with at least ``name`` (display name) and ``groups``
82
+ (a ``set`` of group/role names) keys. Adapters override this to fold in
83
+ provider-specific claims (e.g. ``email``, ``sub``). Application code
84
+ should prefer this -- or the conveniences built on it,
85
+ ``PageBase.current_user`` and the ``current_user`` template global --
86
+ over reaching into a provider's native session, so it stays portable
87
+ across auth stacks.
88
+ """
89
+ if not self.is_authenticated():
90
+ return None
91
+ return {
92
+ "name": self.current_user_name(),
93
+ "groups": self.current_groups(),
94
+ }
95
+
96
+ def user_menu_items(self) -> list[dict]:
97
+ """Items for the user dropdown menu.
98
+
99
+ Each dict must have ``label`` and ``url`` keys; ``icon`` is optional
100
+ and may be a semantic icon name (see ``icons.ICONS``) or a raw glyph;
101
+ it is rendered in the active icon mode (Material Symbols by default,
102
+ Bootstrap Icons under the ``adminlte`` design).
103
+ """
104
+ return []
105
+
106
+ # -- response helpers ---------------------------------------------------
107
+
108
+ def login_url(self):
109
+ """Resolve the login URL, carrying ``next`` back to this request."""
110
+ target = (
111
+ current_app.config.get("CONSTRUCT_LOGIN_ENDPOINT") or self.login_endpoint
112
+ )
113
+ nxt = request.full_path.rstrip("?")
114
+ if not target:
115
+ # No login endpoint configured: fall back to a bare 401.
116
+ return None
117
+ try:
118
+ return url_for(target, next=nxt)
119
+ except Exception:
120
+ # Not a known endpoint — treat it as a literal path.
121
+ sep = "&" if "?" in target else "?"
122
+ return f"{target}{sep}next={nxt}"
123
+
124
+ def on_unauthenticated(self):
125
+ """Default: 302 redirect to the login URL (401 if none configured)."""
126
+ url = self.login_url()
127
+ if url is None:
128
+ abort(401)
129
+ return redirect(url)
130
+
131
+ def on_forbidden(self):
132
+ """Default: render the themed access-denied page with HTTP 403."""
133
+ construct = getattr(g, "construct", None)
134
+ theme = getattr(construct, "theme", None) or "whitelabel"
135
+ return render_template(
136
+ f"themes/{theme}/errors/forbidden.html", construct=construct
137
+ ), 403
138
+
139
+
140
+ class FlaskSecurityAuth(AuthProvider):
141
+ """Adapter for Flask-Security(-Too): ``current_user`` + role relationship."""
142
+
143
+ login_endpoint = "security.login"
144
+
145
+ def is_authenticated(self) -> bool:
146
+ from flask_security import current_user # lazy: optional dependency
147
+
148
+ return bool(current_user.is_authenticated)
149
+
150
+ def current_groups(self) -> set[str]:
151
+ from flask_security import current_user
152
+
153
+ if not current_user.is_authenticated:
154
+ return set()
155
+ return {role.name for role in current_user.roles}
156
+
157
+ def current_user_name(self) -> str | None:
158
+ from flask_security import current_user
159
+
160
+ if not current_user.is_authenticated:
161
+ return None
162
+ return getattr(current_user, "username", None) or getattr(
163
+ current_user, "email", None
164
+ )
165
+
166
+ def current_user(self) -> dict | None:
167
+ from flask_security import current_user
168
+
169
+ if not current_user.is_authenticated:
170
+ return None
171
+ return {
172
+ "name": self.current_user_name(),
173
+ "groups": self.current_groups(),
174
+ "id": getattr(current_user, "id", None),
175
+ "username": getattr(current_user, "username", None),
176
+ "email": getattr(current_user, "email", None),
177
+ }
178
+
179
+ def user_menu_items(self) -> list[dict]:
180
+ try:
181
+ from flask import url_for
182
+
183
+ return [
184
+ {
185
+ "label": "Sign out",
186
+ "url": url_for("security.logout"),
187
+ "icon": "logout",
188
+ }
189
+ ]
190
+ except Exception:
191
+ return []
192
+
193
+
194
+ class FlaskOIDCAuth(AuthProvider):
195
+ """Adapter for Flask-OIDC: login state + group/role claims from the token.
196
+
197
+ ``oidc`` is the application's ``OpenIDConnect`` instance. ``groups_claim`` is
198
+ the claim carrying the user's groups/roles — on Flask-OIDC 2.x this is read
199
+ from the userinfo response (so the IdP must include it there, with
200
+ ``OIDC_USER_INFO_ENABLED`` on), on older builds from the decoded id-token.
201
+ Flask-OIDC's claim API differs across major versions, so claim access is
202
+ isolated in :meth:`current_groups` to make it easy to adapt. The default
203
+ ``login_endpoint`` matches Flask-OIDC 2.x, which registers its routes under
204
+ the ``oidc_auth`` blueprint.
205
+ """
206
+
207
+ def __init__(
208
+ self,
209
+ oidc,
210
+ groups_claim="groups",
211
+ login_endpoint="oidc_auth.login",
212
+ logout_endpoint="oidc_auth.logout",
213
+ ):
214
+ self.oidc = oidc
215
+ self.groups_claim = groups_claim
216
+ self.login_endpoint = login_endpoint
217
+ self.logout_endpoint = logout_endpoint
218
+
219
+ def is_authenticated(self) -> bool:
220
+ return bool(getattr(self.oidc, "user_loggedin", False))
221
+
222
+ def _claims(self) -> dict:
223
+ """Best-effort full claim set for the current user.
224
+
225
+ Flask-OIDC 2.x stores the userinfo response in the session under
226
+ ``oidc_auth_profile``; older builds keep the decoded id-token on
227
+ ``flask.g``. Returns ``{}`` when neither is present (or when called
228
+ outside a request context).
229
+ """
230
+ try:
231
+ from flask import session
232
+
233
+ profile = session.get("oidc_auth_profile")
234
+ if isinstance(profile, dict):
235
+ return profile
236
+ token = g.get("oidc_id_token", None)
237
+ if isinstance(token, dict):
238
+ return token
239
+ except RuntimeError:
240
+ pass
241
+ return {}
242
+
243
+ def current_groups(self) -> set[str]:
244
+ if not self.is_authenticated():
245
+ return set()
246
+ # Newer Flask-OIDC exposes claims via user_getfield; older builds keep
247
+ # the decoded id-token on flask.g. Prefer the accessor when present.
248
+ getter = getattr(self.oidc, "user_getfield", None)
249
+ if getter is not None:
250
+ return set(getter(self.groups_claim) or [])
251
+ token = g.get("oidc_id_token", None)
252
+ if isinstance(token, dict):
253
+ return set(token.get(self.groups_claim) or [])
254
+ return set()
255
+
256
+ def current_user_name(self) -> str | None:
257
+ if not self.is_authenticated():
258
+ return None
259
+ getter = getattr(self.oidc, "user_getfield", None)
260
+ if getter is not None:
261
+ return getter("name") or getter("email")
262
+ token = g.get("oidc_id_token", None)
263
+ if isinstance(token, dict):
264
+ return token.get("name") or token.get("email")
265
+ return None
266
+
267
+ def current_user(self) -> dict | None:
268
+ if not self.is_authenticated():
269
+ return None
270
+ # Start from the full claim set so callers get email/sub/custom claims
271
+ # without reaching into Flask-OIDC's session, then overlay the
272
+ # normalized name/groups so the shape matches other adapters.
273
+ user = dict(self._claims())
274
+ user["name"] = self.current_user_name()
275
+ user["groups"] = self.current_groups()
276
+ return user
277
+
278
+ def user_menu_items(self) -> list[dict]:
279
+ try:
280
+ from flask import url_for
281
+
282
+ return [
283
+ {
284
+ "label": "Sign out",
285
+ "url": url_for(self.logout_endpoint),
286
+ "icon": "logout",
287
+ }
288
+ ]
289
+ except Exception:
290
+ return []