hyper-admin 1.0.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.
- hyper_admin-1.0.0.dist-info/METADATA +366 -0
- hyper_admin-1.0.0.dist-info/RECORD +442 -0
- hyper_admin-1.0.0.dist-info/WHEEL +4 -0
- hyper_admin-1.0.0.dist-info/entry_points.txt +2 -0
- hyper_admin-1.0.0.dist-info/licenses/LICENSE +21 -0
- hyperadmin/__init__.py +52 -0
- hyperadmin/__main__.py +21 -0
- hyperadmin/adapters/__init__.py +28 -0
- hyperadmin/adapters/_estimate.py +33 -0
- hyperadmin/adapters/_filter_clause.py +9 -0
- hyperadmin/adapters/_occ.py +44 -0
- hyperadmin/adapters/_relation_loading.py +23 -0
- hyperadmin/adapters/_search.py +84 -0
- hyperadmin/adapters/filtering.py +86 -0
- hyperadmin/adapters/introspection.py +239 -0
- hyperadmin/adapters/registry.py +37 -0
- hyperadmin/adapters/schema.py +239 -0
- hyperadmin/adapters/sqlalchemy.py +423 -0
- hyperadmin/adapters/sqlmodel.py +650 -0
- hyperadmin/auth/__init__.py +156 -0
- hyperadmin/auth/_types.py +52 -0
- hyperadmin/auth/backend.py +37 -0
- hyperadmin/auth/bridge.py +351 -0
- hyperadmin/auth/exceptions.py +124 -0
- hyperadmin/auth/middleware.py +287 -0
- hyperadmin/auth/models.py +245 -0
- hyperadmin/auth/oauth/__init__.py +81 -0
- hyperadmin/auth/oauth/backend.py +611 -0
- hyperadmin/auth/oauth/providers.py +214 -0
- hyperadmin/auth/oauth/refresh.py +126 -0
- hyperadmin/auth/oauth/session.py +96 -0
- hyperadmin/auth/oauth/tokens.py +114 -0
- hyperadmin/auth/oauth/views.py +306 -0
- hyperadmin/auth/oauth/wiring.py +131 -0
- hyperadmin/auth/otp.py +189 -0
- hyperadmin/auth/permissions.py +232 -0
- hyperadmin/auth/session.py +81 -0
- hyperadmin/auth/session_middleware.py +164 -0
- hyperadmin/auth/token_handoff.py +452 -0
- hyperadmin/auth/user_cache.py +222 -0
- hyperadmin/auth/views.py +581 -0
- hyperadmin/core/__init__.py +76 -0
- hyperadmin/core/actions.py +151 -0
- hyperadmin/core/adapters.py +883 -0
- hyperadmin/core/app.py +1437 -0
- hyperadmin/core/auth.py +97 -0
- hyperadmin/core/bulk_results.py +28 -0
- hyperadmin/core/cache.py +68 -0
- hyperadmin/core/choices.py +38 -0
- hyperadmin/core/concurrency.py +107 -0
- hyperadmin/core/csrf.py +108 -0
- hyperadmin/core/discovery.py +161 -0
- hyperadmin/core/display.py +172 -0
- hyperadmin/core/fields.py +158 -0
- hyperadmin/core/fieldsets.py +22 -0
- hyperadmin/core/filtering.py +403 -0
- hyperadmin/core/filters_compat.py +78 -0
- hyperadmin/core/inlines.py +64 -0
- hyperadmin/core/introspection.py +280 -0
- hyperadmin/core/layouts.py +17 -0
- hyperadmin/core/lifecycle.py +278 -0
- hyperadmin/core/model.py +189 -0
- hyperadmin/core/navigation.py +354 -0
- hyperadmin/core/options.py +391 -0
- hyperadmin/core/palette.py +94 -0
- hyperadmin/core/panels.py +227 -0
- hyperadmin/core/plugin_wiring.py +205 -0
- hyperadmin/core/plugins.py +588 -0
- hyperadmin/core/primary_key.py +118 -0
- hyperadmin/core/rate_limit.py +90 -0
- hyperadmin/core/registry.py +129 -0
- hyperadmin/core/relation_loading.py +25 -0
- hyperadmin/core/schema.py +83 -0
- hyperadmin/core/sensitive.py +134 -0
- hyperadmin/core/settings.py +377 -0
- hyperadmin/core/storage_paths.py +54 -0
- hyperadmin/core/timezones.py +137 -0
- hyperadmin/core/uploads.py +16 -0
- hyperadmin/db.py +160 -0
- hyperadmin/discover.py +54 -0
- hyperadmin/filters/__init__.py +39 -0
- hyperadmin/filters/base.py +246 -0
- hyperadmin/filters/boolean.py +105 -0
- hyperadmin/filters/choice.py +74 -0
- hyperadmin/filters/date.py +265 -0
- hyperadmin/filters/relation.py +69 -0
- hyperadmin/filters/saved_views.py +203 -0
- hyperadmin/i18n/__init__.py +50 -0
- hyperadmin/i18n/loader.py +150 -0
- hyperadmin/i18n/middleware.py +159 -0
- hyperadmin/i18n/validation_messages.py +264 -0
- hyperadmin/loadtest/__init__.py +28 -0
- hyperadmin/loadtest/batch.py +263 -0
- hyperadmin/loadtest/checkpoint.py +168 -0
- hyperadmin/loadtest/generators/__init__.py +29 -0
- hyperadmin/loadtest/generators/auth.py +86 -0
- hyperadmin/loadtest/generators/erp.py +177 -0
- hyperadmin/loadtest/plan.py +189 -0
- hyperadmin/loadtest/pool.py +113 -0
- hyperadmin/loadtest/progress.py +150 -0
- hyperadmin/locale/ar/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/ar/LC_MESSAGES/messages.po +2139 -0
- hyperadmin/locale/de/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/de/LC_MESSAGES/messages.po +2114 -0
- hyperadmin/locale/en/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/en/LC_MESSAGES/messages.po +1780 -0
- hyperadmin/locale/es/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/es/LC_MESSAGES/messages.po +2094 -0
- hyperadmin/locale/fr/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/fr/LC_MESSAGES/messages.po +2100 -0
- hyperadmin/locale/he/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/he/LC_MESSAGES/messages.po +2076 -0
- hyperadmin/locale/hi/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/hi/LC_MESSAGES/messages.po +2084 -0
- hyperadmin/locale/id/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/id/LC_MESSAGES/messages.po +2071 -0
- hyperadmin/locale/it/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/it/LC_MESSAGES/messages.po +2098 -0
- hyperadmin/locale/ja/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/ja/LC_MESSAGES/messages.po +2049 -0
- hyperadmin/locale/ko/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/ko/LC_MESSAGES/messages.po +2049 -0
- hyperadmin/locale/nl/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/nl/LC_MESSAGES/messages.po +2100 -0
- hyperadmin/locale/pl/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/pl/LC_MESSAGES/messages.po +2112 -0
- hyperadmin/locale/pt_BR/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/pt_BR/LC_MESSAGES/messages.po +2098 -0
- hyperadmin/locale/ru/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/ru/LC_MESSAGES/messages.po +2112 -0
- hyperadmin/locale/th/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/th/LC_MESSAGES/messages.po +2065 -0
- hyperadmin/locale/tr/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/tr/LC_MESSAGES/messages.po +2084 -0
- hyperadmin/locale/uk/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/uk/LC_MESSAGES/messages.po +1889 -0
- hyperadmin/locale/vi/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/vi/LC_MESSAGES/messages.po +2063 -0
- hyperadmin/locale/zh_CN/LC_MESSAGES/messages.mo +0 -0
- hyperadmin/locale/zh_CN/LC_MESSAGES/messages.po +2049 -0
- hyperadmin/main.py +3 -0
- hyperadmin/management/__init__.py +0 -0
- hyperadmin/management/commands/__init__.py +0 -0
- hyperadmin/management/commands/createsuperuser.py +114 -0
- hyperadmin/management/commands/initdb.py +76 -0
- hyperadmin/management/commands/plugins.py +31 -0
- hyperadmin/management/commands/seed.py +125 -0
- hyperadmin/navigation/__init__.py +9 -0
- hyperadmin/navigation/pins.py +153 -0
- hyperadmin/panels/__init__.py +10 -0
- hyperadmin/panels/pdf.py +151 -0
- hyperadmin/permissions/__init__.py +59 -0
- hyperadmin/permissions/audit.py +109 -0
- hyperadmin/permissions/matrix.py +343 -0
- hyperadmin/permissions/object_rules.py +143 -0
- hyperadmin/realtime/__init__.py +51 -0
- hyperadmin/realtime/_debug.py +77 -0
- hyperadmin/realtime/config.py +124 -0
- hyperadmin/realtime/emitting.py +143 -0
- hyperadmin/realtime/events.py +107 -0
- hyperadmin/realtime/presence.py +193 -0
- hyperadmin/realtime/presence_redis.py +142 -0
- hyperadmin/realtime/pubsub.py +129 -0
- hyperadmin/realtime/pubsub_redis.py +159 -0
- hyperadmin/realtime/registry.py +102 -0
- hyperadmin/realtime/sse.py +82 -0
- hyperadmin/realtime/ws.py +477 -0
- hyperadmin/routing.py +680 -0
- hyperadmin/static/css/_accessibility.css +149 -0
- hyperadmin/static/css/_alerts.css +147 -0
- hyperadmin/static/css/_autocomplete.css +39 -0
- hyperadmin/static/css/_banner.css +118 -0
- hyperadmin/static/css/_buttons.css +241 -0
- hyperadmin/static/css/_card.css +86 -0
- hyperadmin/static/css/_dark-mode.css +232 -0
- hyperadmin/static/css/_fieldsets.css +71 -0
- hyperadmin/static/css/_filter.css +203 -0
- hyperadmin/static/css/_fonts.css +25 -0
- hyperadmin/static/css/_forms.css +862 -0
- hyperadmin/static/css/_inline-cell.css +222 -0
- hyperadmin/static/css/_inlines.css +160 -0
- hyperadmin/static/css/_layout.css +62 -0
- hyperadmin/static/css/_login.css +112 -0
- hyperadmin/static/css/_menu.css +156 -0
- hyperadmin/static/css/_navbar.css +299 -0
- hyperadmin/static/css/_page-header.css +139 -0
- hyperadmin/static/css/_pagination.css +125 -0
- hyperadmin/static/css/_palette.css +304 -0
- hyperadmin/static/css/_panels.css +174 -0
- hyperadmin/static/css/_permissions.css +547 -0
- hyperadmin/static/css/_pill.css +123 -0
- hyperadmin/static/css/_popover.css +170 -0
- hyperadmin/static/css/_popup.css +65 -0
- hyperadmin/static/css/_progress.css +161 -0
- hyperadmin/static/css/_realtime.css +78 -0
- hyperadmin/static/css/_reset.css +48 -0
- hyperadmin/static/css/_responsive.css +51 -0
- hyperadmin/static/css/_rtl.css +23 -0
- hyperadmin/static/css/_search.css +67 -0
- hyperadmin/static/css/_seg.css +95 -0
- hyperadmin/static/css/_sidebar.css +446 -0
- hyperadmin/static/css/_sticky.css +54 -0
- hyperadmin/static/css/_table.css +776 -0
- hyperadmin/static/css/_theme-terminal-type.css +92 -0
- hyperadmin/static/css/_theme-terminal.css +330 -0
- hyperadmin/static/css/_theme-toggle.css +46 -0
- hyperadmin/static/css/_tokens.css +232 -0
- hyperadmin/static/css/_utilities.css +133 -0
- hyperadmin/static/css/hyperadmin.css +58 -0
- hyperadmin/static/fonts/Inter-OFL.txt +93 -0
- hyperadmin/static/fonts/InterVariable.woff2 +0 -0
- hyperadmin/static/fonts/JetBrainsMono-OFL.txt +93 -0
- hyperadmin/static/fonts/JetBrainsMonoVariable.woff2 +0 -0
- hyperadmin/static/icons/arrow-down.svg +1 -0
- hyperadmin/static/icons/arrow-up.svg +1 -0
- hyperadmin/static/icons/bar-chart-3.svg +1 -0
- hyperadmin/static/icons/bell.svg +1 -0
- hyperadmin/static/icons/bookmark.svg +1 -0
- hyperadmin/static/icons/briefcase.svg +1 -0
- hyperadmin/static/icons/building-2.svg +1 -0
- hyperadmin/static/icons/calendar.svg +1 -0
- hyperadmin/static/icons/check.svg +1 -0
- hyperadmin/static/icons/chevron-down.svg +1 -0
- hyperadmin/static/icons/chevron-left.svg +1 -0
- hyperadmin/static/icons/chevron-right.svg +1 -0
- hyperadmin/static/icons/circle-check.svg +1 -0
- hyperadmin/static/icons/circle-help.svg +1 -0
- hyperadmin/static/icons/circle-x.svg +1 -0
- hyperadmin/static/icons/clock.svg +1 -0
- hyperadmin/static/icons/columns-3.svg +1 -0
- hyperadmin/static/icons/command.svg +1 -0
- hyperadmin/static/icons/copy.svg +1 -0
- hyperadmin/static/icons/credit-card.svg +1 -0
- hyperadmin/static/icons/database.svg +1 -0
- hyperadmin/static/icons/download.svg +1 -0
- hyperadmin/static/icons/ellipsis.svg +1 -0
- hyperadmin/static/icons/external-link.svg +1 -0
- hyperadmin/static/icons/eye.svg +1 -0
- hyperadmin/static/icons/file-text.svg +1 -0
- hyperadmin/static/icons/filter.svg +1 -0
- hyperadmin/static/icons/folder.svg +1 -0
- hyperadmin/static/icons/globe.svg +1 -0
- hyperadmin/static/icons/history.svg +1 -0
- hyperadmin/static/icons/home.svg +1 -0
- hyperadmin/static/icons/image.svg +1 -0
- hyperadmin/static/icons/info.svg +1 -0
- hyperadmin/static/icons/key-round.svg +1 -0
- hyperadmin/static/icons/layers.svg +1 -0
- hyperadmin/static/icons/layout-grid.svg +1 -0
- hyperadmin/static/icons/list-checks.svg +1 -0
- hyperadmin/static/icons/lock.svg +1 -0
- hyperadmin/static/icons/log-out.svg +1 -0
- hyperadmin/static/icons/mail.svg +1 -0
- hyperadmin/static/icons/map-pin.svg +1 -0
- hyperadmin/static/icons/menu.svg +1 -0
- hyperadmin/static/icons/moon.svg +1 -0
- hyperadmin/static/icons/package.svg +1 -0
- hyperadmin/static/icons/panel-left-close.svg +1 -0
- hyperadmin/static/icons/panel-left-open.svg +1 -0
- hyperadmin/static/icons/pencil.svg +1 -0
- hyperadmin/static/icons/pin-off.svg +1 -0
- hyperadmin/static/icons/pin.svg +1 -0
- hyperadmin/static/icons/plus.svg +1 -0
- hyperadmin/static/icons/receipt.svg +1 -0
- hyperadmin/static/icons/refresh-cw.svg +1 -0
- hyperadmin/static/icons/rotate-ccw.svg +1 -0
- hyperadmin/static/icons/search.svg +1 -0
- hyperadmin/static/icons/settings.svg +1 -0
- hyperadmin/static/icons/shield-check.svg +1 -0
- hyperadmin/static/icons/shopping-cart.svg +1 -0
- hyperadmin/static/icons/sliders-horizontal.svg +1 -0
- hyperadmin/static/icons/sparkles.svg +1 -0
- hyperadmin/static/icons/store.svg +1 -0
- hyperadmin/static/icons/sun.svg +1 -0
- hyperadmin/static/icons/tag.svg +1 -0
- hyperadmin/static/icons/trash-2.svg +1 -0
- hyperadmin/static/icons/triangle-alert.svg +1 -0
- hyperadmin/static/icons/truck.svg +1 -0
- hyperadmin/static/icons/upload.svg +1 -0
- hyperadmin/static/icons/user.svg +1 -0
- hyperadmin/static/icons/users.svg +1 -0
- hyperadmin/static/icons/wallet.svg +1 -0
- hyperadmin/static/icons/x.svg +1 -0
- hyperadmin/static/img/hyperadmin-favicon.svg +1 -0
- hyperadmin/static/img/hyperadmin-mark-mono.svg +1 -0
- hyperadmin/static/img/hyperadmin-mark.svg +1 -0
- hyperadmin/static/img/hyperadmin-wordmark-dark.svg +1 -0
- hyperadmin/static/img/hyperadmin-wordmark.svg +1 -0
- hyperadmin/static/img/terminal/hyperadmin-favicon-16.svg +1 -0
- hyperadmin/static/img/terminal/hyperadmin-favicon.svg +1 -0
- hyperadmin/static/img/terminal/hyperadmin-mark.svg +1 -0
- hyperadmin/static/img/terminal/hyperadmin-wordmark-dark.svg +1 -0
- hyperadmin/static/img/terminal/hyperadmin-wordmark.svg +1 -0
- hyperadmin/static/js/autocomplete.js +475 -0
- hyperadmin/static/js/confirm_delete.js +113 -0
- hyperadmin/static/js/error_summary.js +37 -0
- hyperadmin/static/js/form_guard.js +77 -0
- hyperadmin/static/js/inline_edit.js +97 -0
- hyperadmin/static/js/palette.js +292 -0
- hyperadmin/static/js/primitives.js +205 -0
- hyperadmin/static/js/realtime-status.js +515 -0
- hyperadmin/static/js/request_errors.js +85 -0
- hyperadmin/static/js/shortcuts.js +175 -0
- hyperadmin/static/js/sidebar.js +83 -0
- hyperadmin/static/js/vendor/LICENSE-alpinejs.txt +21 -0
- hyperadmin/static/js/vendor/LICENSE-htmx.txt +25 -0
- hyperadmin/static/js/vendor/alpinejs-3.17.4.min.js +21 -0
- hyperadmin/static/js/vendor/alpinejs-focus-3.17.4.min.js +18 -0
- hyperadmin/static/js/vendor/htmx-1.9.10.min.js +1 -0
- hyperadmin/templates/_base.html +161 -0
- hyperadmin/templates/_messages.html +11 -0
- hyperadmin/templates/_navbar.html +126 -0
- hyperadmin/templates/_sidebar.html +80 -0
- hyperadmin/templates/auth/mfa_challenge.html +75 -0
- hyperadmin/templates/auth/mfa_settings.html +110 -0
- hyperadmin/templates/auth/oauth_link_required.html +24 -0
- hyperadmin/templates/auth/oauth_settings.html +55 -0
- hyperadmin/templates/base.html +16 -0
- hyperadmin/templates/bulk_form.html +18 -0
- hyperadmin/templates/bulk_result.html +20 -0
- hyperadmin/templates/components/_icons.html +86 -0
- hyperadmin/templates/components/_macros.html +27 -0
- hyperadmin/templates/components/_nav.html +55 -0
- hyperadmin/templates/components/_row_access.html +26 -0
- hyperadmin/templates/components/banner.html +77 -0
- hyperadmin/templates/components/bulk_form.html +81 -0
- hyperadmin/templates/components/bulk_result.html +133 -0
- hyperadmin/templates/components/bulk_toolbar.html +63 -0
- hyperadmin/templates/components/command_palette.html +59 -0
- hyperadmin/templates/components/confirm_delete_dialog.html +26 -0
- hyperadmin/templates/components/conflict_dialog.html +42 -0
- hyperadmin/templates/components/csrf_reload_banner.html +20 -0
- hyperadmin/templates/components/error_summary.html +39 -0
- hyperadmin/templates/components/error_toast.html +18 -0
- hyperadmin/templates/components/fieldset.html +38 -0
- hyperadmin/templates/components/filter_bar.html +50 -0
- hyperadmin/templates/components/filter_sidebar.html +31 -0
- hyperadmin/templates/components/filters/boolean.html +10 -0
- hyperadmin/templates/components/filters/current_period.html +8 -0
- hyperadmin/templates/components/filters/date_range.html +26 -0
- hyperadmin/templates/components/filters/is_owner.html +8 -0
- hyperadmin/templates/components/filters/multi_choice.html +10 -0
- hyperadmin/templates/components/filters/multi_relation.html +20 -0
- hyperadmin/templates/components/filters/select.html +11 -0
- hyperadmin/templates/components/inline_cell.html +23 -0
- hyperadmin/templates/components/inline_cell_error.html +51 -0
- hyperadmin/templates/components/inline_cell_stale.html +20 -0
- hyperadmin/templates/components/inline_editor.html +85 -0
- hyperadmin/templates/components/inline_formset.html +34 -0
- hyperadmin/templates/components/inline_row.html +49 -0
- hyperadmin/templates/components/list_error.html +12 -0
- hyperadmin/templates/components/menu.html +74 -0
- hyperadmin/templates/components/nav_pinned.html +24 -0
- hyperadmin/templates/components/pagination.html +87 -0
- hyperadmin/templates/components/panel_document.html +19 -0
- hyperadmin/templates/components/panel_states.html +35 -0
- hyperadmin/templates/components/panel_tab_strip.html +31 -0
- hyperadmin/templates/components/pill.html +15 -0
- hyperadmin/templates/components/popover.html +59 -0
- hyperadmin/templates/components/presence_banner.html +28 -0
- hyperadmin/templates/components/progress.html +72 -0
- hyperadmin/templates/components/saved_views.html +61 -0
- hyperadmin/templates/components/search_input.html +19 -0
- hyperadmin/templates/components/seg.html +38 -0
- hyperadmin/templates/components/shortcuts_overlay.html +45 -0
- hyperadmin/templates/components/sortable_header.html +23 -0
- hyperadmin/templates/components/table.html +45 -0
- hyperadmin/templates/components/table_body.html +86 -0
- hyperadmin/templates/components/thumbnail.html +8 -0
- hyperadmin/templates/components/toast.html +36 -0
- hyperadmin/templates/components/tooltip.html +20 -0
- hyperadmin/templates/create.html +43 -0
- hyperadmin/templates/dashboard.html +8 -0
- hyperadmin/templates/detail.html +120 -0
- hyperadmin/templates/detail_layout.html +15 -0
- hyperadmin/templates/error.html +24 -0
- hyperadmin/templates/form_layout.html +26 -0
- hyperadmin/templates/list.html +5 -0
- hyperadmin/templates/list_layout.html +105 -0
- hyperadmin/templates/login.html +79 -0
- hyperadmin/templates/permissions/_banner.html +55 -0
- hyperadmin/templates/permissions/_diff_row.html +6 -0
- hyperadmin/templates/permissions/_group_gone.html +16 -0
- hyperadmin/templates/permissions/_macros.html +22 -0
- hyperadmin/templates/permissions/matrix.html +408 -0
- hyperadmin/templates/permissions/object_popover.html +95 -0
- hyperadmin/templates/update.html +69 -0
- hyperadmin/templates/widgets/autocomplete.html +100 -0
- hyperadmin/templates/widgets/checkbox_input.html +20 -0
- hyperadmin/templates/widgets/choices_options.html +3 -0
- hyperadmin/templates/widgets/date_input.html +13 -0
- hyperadmin/templates/widgets/datetime_input.html +18 -0
- hyperadmin/templates/widgets/encoded_textarea.html +4 -0
- hyperadmin/templates/widgets/file_input.html +15 -0
- hyperadmin/templates/widgets/float_input.html +12 -0
- hyperadmin/templates/widgets/image_input.html +108 -0
- hyperadmin/templates/widgets/multiselect_input.html +13 -0
- hyperadmin/templates/widgets/number_input.html +11 -0
- hyperadmin/templates/widgets/popup_form.html +64 -0
- hyperadmin/templates/widgets/relation_multiselect_input.html +36 -0
- hyperadmin/templates/widgets/relation_select_input.html +38 -0
- hyperadmin/templates/widgets/select_input.html +17 -0
- hyperadmin/templates/widgets/text_input.html +13 -0
- hyperadmin/templates/widgets/textarea.html +4 -0
- hyperadmin/uploads/__init__.py +44 -0
- hyperadmin/uploads/images.py +272 -0
- hyperadmin/uploads/storage.py +265 -0
- hyperadmin/uploads/validation.py +37 -0
- hyperadmin/views/__init__.py +3 -0
- hyperadmin/views/csrf.py +316 -0
- hyperadmin/views/dynamic/__init__.py +35 -0
- hyperadmin/views/dynamic/actions.py +264 -0
- hyperadmin/views/dynamic/base.py +576 -0
- hyperadmin/views/dynamic/concurrency.py +138 -0
- hyperadmin/views/dynamic/core.py +33 -0
- hyperadmin/views/dynamic/create.py +189 -0
- hyperadmin/views/dynamic/detail.py +231 -0
- hyperadmin/views/dynamic/files.py +233 -0
- hyperadmin/views/dynamic/form_data.py +162 -0
- hyperadmin/views/dynamic/helpers.py +151 -0
- hyperadmin/views/dynamic/inline.py +348 -0
- hyperadmin/views/dynamic/list_view.py +612 -0
- hyperadmin/views/dynamic/model_view.py +17 -0
- hyperadmin/views/dynamic/palette_search.py +78 -0
- hyperadmin/views/dynamic/relations.py +544 -0
- hyperadmin/views/dynamic/saved_views.py +159 -0
- hyperadmin/views/dynamic/update.py +313 -0
- hyperadmin/views/error_pages.py +46 -0
- hyperadmin/views/forms.py +1294 -0
- hyperadmin/views/htmx.py +53 -0
- hyperadmin/views/locale.py +113 -0
- hyperadmin/views/nav_pins.py +149 -0
- hyperadmin/views/navigation.py +143 -0
- hyperadmin/views/palette_context.py +91 -0
- hyperadmin/views/palette_search.py +103 -0
- hyperadmin/views/permissions_matrix.py +490 -0
- hyperadmin/views/rate_limit.py +87 -0
- hyperadmin/views/route.py +316 -0
- hyperadmin/views/static.py +138 -0
- hyperadmin/views/template_filters.py +305 -0
- hyperadmin/views/uploads.py +92 -0
- hyperadmin/views/urls.py +180 -0
hyperadmin/core/app.py
ADDED
|
@@ -0,0 +1,1437 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import sys
|
|
4
|
+
import warnings
|
|
5
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
6
|
+
|
|
7
|
+
from fastapi import APIRouter, Depends, FastAPI
|
|
8
|
+
from fastapi.staticfiles import StaticFiles
|
|
9
|
+
from fastapi.templating import Jinja2Templates
|
|
10
|
+
|
|
11
|
+
from hyperadmin.core.cache import InMemoryTTLCache
|
|
12
|
+
from hyperadmin.core.introspection import (
|
|
13
|
+
discover_sqlmodel_models,
|
|
14
|
+
infer_list_display,
|
|
15
|
+
infer_list_filter,
|
|
16
|
+
infer_search_fields,
|
|
17
|
+
)
|
|
18
|
+
from hyperadmin.core.lifecycle import Lifecycle, StartupGuardMiddleware
|
|
19
|
+
from hyperadmin.core.navigation import ModelNavSource, NavGroup, build_nav_tree
|
|
20
|
+
from hyperadmin.core.plugin_wiring import (
|
|
21
|
+
build_plugin_routes,
|
|
22
|
+
extend_template_loader,
|
|
23
|
+
mount_plugin_static,
|
|
24
|
+
plugin_nav_sections,
|
|
25
|
+
plugin_permission_rows,
|
|
26
|
+
resolve_plugin_nav_entries,
|
|
27
|
+
)
|
|
28
|
+
from hyperadmin.core.plugins import PluginRegistry
|
|
29
|
+
from hyperadmin.core.settings import HyperAdminSettings
|
|
30
|
+
from hyperadmin.core.storage_paths import storage_root
|
|
31
|
+
from hyperadmin.discover import discover_admin_modules
|
|
32
|
+
from hyperadmin.realtime import ConnectionRegistry, RealtimeEvent, RealtimeSettings
|
|
33
|
+
from hyperadmin.realtime.emitting import RealtimeEmitter
|
|
34
|
+
from hyperadmin.realtime.sse import make_sse_handler
|
|
35
|
+
from hyperadmin.realtime.ws import make_ws_handler, ws_http_fallback
|
|
36
|
+
|
|
37
|
+
if TYPE_CHECKING:
|
|
38
|
+
from collections.abc import Iterable, Mapping
|
|
39
|
+
from contextlib import AbstractAsyncContextManager
|
|
40
|
+
|
|
41
|
+
from fastapi import params
|
|
42
|
+
from fastapi.routing import APIRoute
|
|
43
|
+
|
|
44
|
+
from hyperadmin.auth.bridge import ExternalAuth
|
|
45
|
+
from hyperadmin.auth.oauth.backend import OAuthBackend
|
|
46
|
+
from hyperadmin.core.adapters import SessionFactory
|
|
47
|
+
from hyperadmin.core.csrf import EffectiveCsrfMode
|
|
48
|
+
from hyperadmin.core.rate_limit import RateLimiter
|
|
49
|
+
from hyperadmin.db import TableScope
|
|
50
|
+
from hyperadmin.views.csrf import CsrfGuard
|
|
51
|
+
from hyperadmin.views.nav_pins import NavPins
|
|
52
|
+
|
|
53
|
+
logger = logging.getLogger("hyperadmin")
|
|
54
|
+
|
|
55
|
+
#: HyperAdmin's own CSS, JS, fonts and icons, served under ``{prefix}/static``.
|
|
56
|
+
_STATIC_DIR = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static")
|
|
57
|
+
|
|
58
|
+
#: ``"builtin"`` with ``auth_backend=``, ``"external"`` with ``auth=`` (SDD B.3).
|
|
59
|
+
AuthMode = Literal["builtin", "external"]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class Admin:
|
|
63
|
+
"""The main entry point for HyperAdmin.
|
|
64
|
+
|
|
65
|
+
Mounts static files, wires the database engine, optionally discovers admin
|
|
66
|
+
modules, and registers all model routes on the FastAPI application.
|
|
67
|
+
|
|
68
|
+
All scalar configuration lives in ``HyperAdminSettings`` — pass a settings
|
|
69
|
+
object or let HyperAdmin auto-instantiate one (which reads from environment
|
|
70
|
+
variables and a ``.env`` file).
|
|
71
|
+
|
|
72
|
+
Example::
|
|
73
|
+
|
|
74
|
+
from fastapi import FastAPI
|
|
75
|
+
from hyperadmin import Admin, HyperAdminSettings
|
|
76
|
+
|
|
77
|
+
app = FastAPI()
|
|
78
|
+
settings = HyperAdminSettings(secret_key="my-secret", theme="dark")
|
|
79
|
+
admin = Admin(app, engine=engine, settings=settings)
|
|
80
|
+
admin.mount("/admin")
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__( # noqa: PLR0917 - public signature; keyword-only would break callers
|
|
84
|
+
self,
|
|
85
|
+
app: FastAPI,
|
|
86
|
+
engine: Any = None,
|
|
87
|
+
settings: HyperAdminSettings | None = None,
|
|
88
|
+
auth_backend: Any = None,
|
|
89
|
+
permission_checker: Any = None,
|
|
90
|
+
permission_registry: Any = None,
|
|
91
|
+
storage: Any = None,
|
|
92
|
+
otp_service: Any = None,
|
|
93
|
+
realtime: RealtimeSettings | None = None,
|
|
94
|
+
*,
|
|
95
|
+
session_factory: "SessionFactory | None" = None,
|
|
96
|
+
auth: "ExternalAuth | None" = None,
|
|
97
|
+
disabled_plugins: "Iterable[str]" = (),
|
|
98
|
+
plugin_settings: "Mapping[str, Mapping[str, Any]] | None" = None,
|
|
99
|
+
nav_groups: "Iterable[NavGroup]" = (),
|
|
100
|
+
rate_limiter: "RateLimiter | None" = None,
|
|
101
|
+
oauth_backend: "OAuthBackend | None" = None,
|
|
102
|
+
) -> None:
|
|
103
|
+
"""Initialise HyperAdmin and attach it to a FastAPI application.
|
|
104
|
+
|
|
105
|
+
Args:
|
|
106
|
+
app: The FastAPI application instance to attach the admin to.
|
|
107
|
+
engine: An async SQLAlchemy engine. When both ``engine`` and
|
|
108
|
+
``session_factory`` are ``None`` (demo mode), an engine is built
|
|
109
|
+
lazily from ``settings.database_url`` by
|
|
110
|
+
``hyperadmin.db.get_default_engine``.
|
|
111
|
+
settings: A ``HyperAdminSettings`` instance. When ``None``, one is
|
|
112
|
+
auto-instantiated (reads ``HYPERADMIN_*`` env vars and ``.env``).
|
|
113
|
+
auth_backend: An optional authentication backend implementing the
|
|
114
|
+
``AuthBackend`` protocol. When ``None``, auth is disabled.
|
|
115
|
+
permission_checker: An optional ``PermissionChecker`` implementation.
|
|
116
|
+
permission_registry: An optional ``PermissionRegistry`` implementation.
|
|
117
|
+
storage: An optional ``FileSystemStorage`` or ``S3StorageBackend``
|
|
118
|
+
instance for file uploads. When ``None``, ``settings.storage_backend``
|
|
119
|
+
decides: ``"s3"`` builds an ``S3StorageBackend`` from the ``aws_*``
|
|
120
|
+
settings, ``"local"`` (default) disables file upload support.
|
|
121
|
+
otp_service: An optional MFA OTP service (e.g. ``EmailOTPService``).
|
|
122
|
+
When ``None``, the MFA endpoints (``/mfa/challenge`` etc) are
|
|
123
|
+
NOT registered and ``login_view`` skips the MFA branch — apps
|
|
124
|
+
without MFA are entirely unaffected (C3-A, #487).
|
|
125
|
+
realtime: Opt-in ``RealtimeSettings``. When ``None`` (default),
|
|
126
|
+
no SSE / WebSocket endpoints are registered and the status
|
|
127
|
+
widget is not injected — fully backward compatible. See
|
|
128
|
+
``docs/specs/realtime-connection-foundation.md``.
|
|
129
|
+
session_factory: A host-provided session factory (e.g.
|
|
130
|
+
``async_sessionmaker(engine)``), forwarded to every adapter and
|
|
131
|
+
auth service instead of ``engine``. Bring-your-own-app hosts
|
|
132
|
+
that manage their own engine and session lifecycle pass this
|
|
133
|
+
instead of ``engine=``. See SDD C.3.
|
|
134
|
+
auth: Bring-your-own-auth (``ExternalAuth``): the host's own
|
|
135
|
+
``get_user`` dependency guards every admin route, and no
|
|
136
|
+
built-in session, login or ``hyperadmin_*`` table is used.
|
|
137
|
+
Mutually exclusive with ``auth_backend`` and ``otp_service``.
|
|
138
|
+
See SDD B.3.
|
|
139
|
+
disabled_plugins: Names of ``hyperadmin.plugins`` entry points not to
|
|
140
|
+
load; unioned with ``HYPERADMIN_DISABLED_PLUGINS``.
|
|
141
|
+
plugin_settings: Raw settings per plugin name, validated into each
|
|
142
|
+
plugin's ``settings_model`` before its ``on_register``. See
|
|
143
|
+
``docs/specs/plugin-registry.md``.
|
|
144
|
+
nav_groups: Sidebar groups (``NavGroup``): their order, icon and default
|
|
145
|
+
collapse state. Models join a group through ``nav_group`` on their
|
|
146
|
+
admin class; undeclared groups still appear, after these. See
|
|
147
|
+
``docs/specs/navigation-and-list-ux.md``.
|
|
148
|
+
rate_limiter: A ``RateLimiter`` applied per client to every admin request
|
|
149
|
+
except static assets; over the limit gets ``429`` with ``Retry-After``.
|
|
150
|
+
When ``None``, ``settings.rate_limit_requests`` builds an in-memory one
|
|
151
|
+
(and no limit applies if that is unset either). Pass a shared
|
|
152
|
+
implementation to enforce one limit across several workers.
|
|
153
|
+
oauth_backend: Opt-in OAuth2/OIDC sign-in (``OAuthBackend``) for the
|
|
154
|
+
built-in users, next to ``auth_backend``. Needs the ``oauth`` extra
|
|
155
|
+
and ``settings.oauth_token_secret``. See ``docs/specs/oauth-sso.md``.
|
|
156
|
+
|
|
157
|
+
Raises:
|
|
158
|
+
ValueError: ``auth`` is combined with ``auth_backend`` or
|
|
159
|
+
``otp_service``, or with a ``ModelPermissionChecker`` while
|
|
160
|
+
``settings.register_auth_models`` is not ``True``; or
|
|
161
|
+
``oauth_backend`` is misconfigured (``OAuthConfigError``).
|
|
162
|
+
"""
|
|
163
|
+
self.settings = settings or HyperAdminSettings()
|
|
164
|
+
self.app = app
|
|
165
|
+
self.router = APIRouter()
|
|
166
|
+
#: Admin routes outside the auth guard (SDD B.3): the bridge login form, and
|
|
167
|
+
#: the token handoff, which carries its own guard. Included without the
|
|
168
|
+
#: protected router's dependencies.
|
|
169
|
+
self.public_router = APIRouter()
|
|
170
|
+
demo_mode = engine is None and session_factory is None
|
|
171
|
+
self.engine = engine if not demo_mode else self._default_engine()
|
|
172
|
+
self.session_factory = session_factory
|
|
173
|
+
self.auth_backend = auth_backend
|
|
174
|
+
self.permission_checker = permission_checker
|
|
175
|
+
self.permission_registry = permission_registry
|
|
176
|
+
self.storage = storage if storage is not None else self._default_storage()
|
|
177
|
+
self.otp_service = otp_service
|
|
178
|
+
self.auth = auth
|
|
179
|
+
self._auth_mode: AuthMode | None = None
|
|
180
|
+
if auth is not None:
|
|
181
|
+
self._auth_mode = "external"
|
|
182
|
+
self._validate_external_auth()
|
|
183
|
+
self.permission_checker = self._resolve_bridge_permission_checker(auth)
|
|
184
|
+
elif auth_backend is not None:
|
|
185
|
+
self._auth_mode = "builtin"
|
|
186
|
+
self.realtime = realtime
|
|
187
|
+
self._realtime_registry: ConnectionRegistry | None = (
|
|
188
|
+
ConnectionRegistry() if realtime is not None else None
|
|
189
|
+
)
|
|
190
|
+
self._realtime_pubsub = realtime.resolve_pubsub() if realtime is not None else None
|
|
191
|
+
self._realtime_emitter: RealtimeEmitter | None = (
|
|
192
|
+
RealtimeEmitter(self._realtime_pubsub, realtime.channel_prefix)
|
|
193
|
+
if realtime is not None and self._realtime_pubsub is not None
|
|
194
|
+
else None
|
|
195
|
+
)
|
|
196
|
+
self._notification_models: set[str] = set()
|
|
197
|
+
|
|
198
|
+
self._validate_secret_key()
|
|
199
|
+
self.oauth_backend = self._configure_oauth(oauth_backend)
|
|
200
|
+
|
|
201
|
+
template_dirs = self.settings.template_dirs
|
|
202
|
+
template_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "templates")
|
|
203
|
+
self.templates = Jinja2Templates(directory=[*template_dirs, template_dir])
|
|
204
|
+
# Wire jinja2.ext.i18n + per-request gettext callables (C1-C). The
|
|
205
|
+
# callables read translations from a context var populated by
|
|
206
|
+
# LocaleMiddleware; outside a request they pass msgids through.
|
|
207
|
+
from hyperadmin.i18n import install_jinja_i18n
|
|
208
|
+
|
|
209
|
+
install_jinja_i18n(self.templates.env)
|
|
210
|
+
# Namespace-aware url_for (C.1): tries "<namespace>:<name>" first when
|
|
211
|
+
# mount() has tagged the request scope (isolated mode), then the plain
|
|
212
|
+
# name (router mode, and host routes in either mode).
|
|
213
|
+
from hyperadmin.views.urls import install_namespaced_url_for
|
|
214
|
+
|
|
215
|
+
install_namespaced_url_for(self.templates.env)
|
|
216
|
+
|
|
217
|
+
self._asgi_app: FastAPI | None = None
|
|
218
|
+
|
|
219
|
+
# Opt-in auto-create decision is made once, here, from the settings this
|
|
220
|
+
# Admin was built with — never re-evaluated on every startup() call.
|
|
221
|
+
self._auto_create_tables = self._should_create_tables(demo_mode=demo_mode)
|
|
222
|
+
self._lifecycle = Lifecycle(
|
|
223
|
+
create_tables=self._create_tables_if_opted_in,
|
|
224
|
+
sync_permissions=self._sync_permissions,
|
|
225
|
+
drain=self._drain_realtime,
|
|
226
|
+
realtime_enabled=realtime is not None,
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
if self.settings.discover_apps:
|
|
230
|
+
discover_admin_modules(self.settings.discover_apps)
|
|
231
|
+
|
|
232
|
+
self.nav_groups: tuple[NavGroup, ...] = tuple(nav_groups)
|
|
233
|
+
self.rate_limiter = rate_limiter
|
|
234
|
+
self._nav_sources: list[ModelNavSource] = []
|
|
235
|
+
#: Sidebar pins (``views/nav_pins.py``); set in mount() when auth is configured.
|
|
236
|
+
self._nav_pins: NavPins | None = None
|
|
237
|
+
# Assigned before loading: a plugin's on_register calls admin.plugins.add_*.
|
|
238
|
+
# What plugins contribute is applied in mount().
|
|
239
|
+
self.plugins = PluginRegistry()
|
|
240
|
+
if self.settings.plugins_enabled:
|
|
241
|
+
self.plugins.load_entry_points(
|
|
242
|
+
admin=self, disabled=disabled_plugins, settings=plugin_settings
|
|
243
|
+
)
|
|
244
|
+
self._register_permissions_matrix()
|
|
245
|
+
|
|
246
|
+
# ── Convenience properties ─────────────────────────────────────────────
|
|
247
|
+
|
|
248
|
+
@property
|
|
249
|
+
def theme(self) -> str:
|
|
250
|
+
"""Active theme from settings."""
|
|
251
|
+
return self.settings.theme
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def asgi_app(self) -> FastAPI | None:
|
|
255
|
+
"""The private admin sub-application, once ``mount()`` ran in isolated mode.
|
|
256
|
+
|
|
257
|
+
``None`` before ``mount()``, and in (legacy) router mode, where admin
|
|
258
|
+
routes live directly on the host app. Hosts may add their own admin-side
|
|
259
|
+
routes to it; they then run behind the admin's middleware.
|
|
260
|
+
"""
|
|
261
|
+
return self._asgi_app
|
|
262
|
+
|
|
263
|
+
# ── Validation helpers ─────────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
@property
|
|
266
|
+
def csrf_mode(self) -> "EffectiveCsrfMode":
|
|
267
|
+
"""The effective CSRF mode: ``csrf_mode="auto"`` enforces when auth is on (SDD D.1).
|
|
268
|
+
|
|
269
|
+
"Auth is on" means ``auth_backend``, ``auth=`` or app-level ``dependencies`` on the
|
|
270
|
+
host app (the usual host login guard). Host auth middleware cannot be
|
|
271
|
+
detected; such hosts set ``csrf_mode="enforce"``.
|
|
272
|
+
"""
|
|
273
|
+
from hyperadmin.core.csrf import resolve_csrf_mode
|
|
274
|
+
|
|
275
|
+
# getattr: a plain Starlette router (or a test double) has no ``dependencies``.
|
|
276
|
+
host_dependencies = getattr(getattr(self.app, "router", None), "dependencies", None)
|
|
277
|
+
auth_enabled = self._auth_mode is not None or bool(host_dependencies)
|
|
278
|
+
return resolve_csrf_mode(self.settings.csrf_mode, auth_enabled=auth_enabled)
|
|
279
|
+
|
|
280
|
+
def _validate_external_auth(self) -> None:
|
|
281
|
+
"""Reject combinations ``auth=`` cannot serve (SDD B.3)."""
|
|
282
|
+
for name, value in (("auth_backend", self.auth_backend), ("otp_service", self.otp_service)):
|
|
283
|
+
if value is not None:
|
|
284
|
+
msg = (
|
|
285
|
+
f"Admin(auth=...) and Admin({name}=...) are mutually exclusive: "
|
|
286
|
+
f"auth= brings the host's own authentication, {name}= is built-in auth."
|
|
287
|
+
)
|
|
288
|
+
raise ValueError(msg)
|
|
289
|
+
# Looked up, not imported: importing auth.permissions registers the
|
|
290
|
+
# hyperadmin_* tables, which a bridge-mode host must never get. A checker
|
|
291
|
+
# cannot be a ModelPermissionChecker unless its module is already loaded.
|
|
292
|
+
model_checker = getattr(
|
|
293
|
+
sys.modules.get("hyperadmin.auth.permissions"), "ModelPermissionChecker", None
|
|
294
|
+
)
|
|
295
|
+
if (
|
|
296
|
+
model_checker is not None
|
|
297
|
+
and isinstance(self.permission_checker, model_checker)
|
|
298
|
+
and self.settings.register_auth_models is not True
|
|
299
|
+
):
|
|
300
|
+
msg = (
|
|
301
|
+
"ModelPermissionChecker with Admin(auth=...) requires "
|
|
302
|
+
"settings.register_auth_models=True: it reads the built-in hyperadmin_* "
|
|
303
|
+
"permission tables keyed on user.id, so host user ids must also be ints "
|
|
304
|
+
"matching hyperadmin_users. Pass ExternalAuth(has_permission=...) instead "
|
|
305
|
+
"to keep permissions in the host application."
|
|
306
|
+
)
|
|
307
|
+
raise ValueError(msg)
|
|
308
|
+
|
|
309
|
+
def _resolve_bridge_permission_checker(self, auth: "ExternalAuth") -> Any:
|
|
310
|
+
"""Pick the bridge-mode permission checker; the first match wins (SDD B.3).
|
|
311
|
+
|
|
312
|
+
1. An explicit ``Admin(permission_checker=...)``.
|
|
313
|
+
2. ``auth.has_permission``: used as is when it is a ``PermissionChecker``,
|
|
314
|
+
wrapped in ``CallablePermissionChecker`` when it is a plain callable.
|
|
315
|
+
3. The fail-safe ``BridgeDefaultPermissionChecker``: superusers get every
|
|
316
|
+
permission, everyone else ``view_*`` only (all of them with
|
|
317
|
+
``allow_full_access=True``).
|
|
318
|
+
|
|
319
|
+
Every checker except one built from ``has_permission`` is wrapped in
|
|
320
|
+
``HostUserModelGuard``, so a non-superuser never gets ``change_*`` or
|
|
321
|
+
``delete_*`` on the host user model unless ``has_permission`` grants it.
|
|
322
|
+
"""
|
|
323
|
+
import hyperadmin.auth as auth_package
|
|
324
|
+
from hyperadmin.auth.bridge import (
|
|
325
|
+
BridgeDefaultPermissionChecker,
|
|
326
|
+
CallablePermissionChecker,
|
|
327
|
+
HostUserModelGuard,
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
# Lets hyperadmin.auth.metadata() warn a bridge-mode host (SDD B.5).
|
|
331
|
+
auth_package._note_bridge_admin_constructed()
|
|
332
|
+
if self.permission_checker is not None:
|
|
333
|
+
return HostUserModelGuard(self.permission_checker)
|
|
334
|
+
has_permission = auth.has_permission
|
|
335
|
+
if has_permission is not None:
|
|
336
|
+
if callable(getattr(has_permission, "has_permission", None)):
|
|
337
|
+
return has_permission
|
|
338
|
+
return CallablePermissionChecker(has_permission) # type: ignore[arg-type]
|
|
339
|
+
logger.warning(
|
|
340
|
+
"HyperAdmin Admin(auth=ExternalAuth(...)) has no has_permission: using the "
|
|
341
|
+
"fail-safe default (superusers get every permission, everyone else view-only). "
|
|
342
|
+
"Pass ExternalAuth(has_permission=...) to map the host's own permissions."
|
|
343
|
+
)
|
|
344
|
+
if auth.allow_full_access:
|
|
345
|
+
logger.warning(
|
|
346
|
+
"HyperAdmin ExternalAuth(allow_full_access=True): every user that passes "
|
|
347
|
+
"can_access gets every permission, except change/delete on the host user model."
|
|
348
|
+
)
|
|
349
|
+
return HostUserModelGuard(
|
|
350
|
+
BridgeDefaultPermissionChecker(allow_full_access=auth.allow_full_access)
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
def _validate_secret_key(self) -> None:
|
|
354
|
+
"""Refuse the default ``secret_key`` when it signs anything that matters.
|
|
355
|
+
|
|
356
|
+
Fires when auth is enabled (it signs the session) or when CSRF resolves to
|
|
357
|
+
``enforce`` (it signs the CSRF tokens, SDD D.1).
|
|
358
|
+
"""
|
|
359
|
+
if not self.auth_backend and self.csrf_mode != "enforce":
|
|
360
|
+
return
|
|
361
|
+
if not self.settings.is_default_secret_key:
|
|
362
|
+
return
|
|
363
|
+
if self.settings.debug:
|
|
364
|
+
logger.warning(
|
|
365
|
+
"Using default session secret. Set HYPERADMIN_SECRET_KEY for production."
|
|
366
|
+
)
|
|
367
|
+
else:
|
|
368
|
+
msg = (
|
|
369
|
+
"Auth or CSRF enforcement is enabled but no secret_key is configured. "
|
|
370
|
+
"Set HYPERADMIN_SECRET_KEY (or pass HyperAdminSettings(secret_key=...))."
|
|
371
|
+
)
|
|
372
|
+
raise ValueError(msg)
|
|
373
|
+
|
|
374
|
+
# ── Internal helpers ───────────────────────────────────────────────────
|
|
375
|
+
|
|
376
|
+
def _should_create_tables(self, *, demo_mode: bool) -> bool:
|
|
377
|
+
"""Whether ``startup()`` auto-creates tables (SDD C.2).
|
|
378
|
+
|
|
379
|
+
``create_tables`` defaults to ``False``, so a host ``engine=`` or
|
|
380
|
+
``session_factory=`` never gets DDL run against it unless the host opts in
|
|
381
|
+
explicitly. Demo mode (no ``engine=``, no ``session_factory=``) builds its
|
|
382
|
+
engine from ``settings.database_url``, which may be the host's own database
|
|
383
|
+
(``HYPERADMIN_DATABASE_URL``); there, tables are still auto-created when that
|
|
384
|
+
URL is SQLite — so zero-config ``Admin(app).mount("/admin")`` keeps working —
|
|
385
|
+
but never for any other URL, so a host database is never altered behind its
|
|
386
|
+
migrations' back (Goal 4). An explicit ``create_tables=`` (either value)
|
|
387
|
+
always wins over the demo-mode default.
|
|
388
|
+
"""
|
|
389
|
+
if "create_tables" in self.settings.model_fields_set:
|
|
390
|
+
return self.settings.create_tables
|
|
391
|
+
if not demo_mode:
|
|
392
|
+
return False
|
|
393
|
+
from hyperadmin.db import is_sqlite_url
|
|
394
|
+
|
|
395
|
+
if is_sqlite_url(self.settings.database_url):
|
|
396
|
+
logger.warning(
|
|
397
|
+
"HyperAdmin demo mode: database_url is SQLite, so tables are created "
|
|
398
|
+
"automatically at startup. Set create_tables=False to disable this."
|
|
399
|
+
)
|
|
400
|
+
return True
|
|
401
|
+
logger.warning(
|
|
402
|
+
"HyperAdmin demo mode: database_url is not SQLite, so no tables are created "
|
|
403
|
+
"automatically. Set create_tables=True (HYPERADMIN_CREATE_TABLES=true) to "
|
|
404
|
+
"create them at startup, or create them with your migrations."
|
|
405
|
+
)
|
|
406
|
+
return False
|
|
407
|
+
|
|
408
|
+
def _default_engine(self) -> Any:
|
|
409
|
+
"""Build (or reuse) the demo-mode engine for ``settings.database_url``."""
|
|
410
|
+
from hyperadmin.db import get_default_engine
|
|
411
|
+
|
|
412
|
+
return get_default_engine(self.settings)
|
|
413
|
+
|
|
414
|
+
async def _create_db_and_tables(self) -> None:
|
|
415
|
+
"""Creates the database and all tables using the configured engine.
|
|
416
|
+
|
|
417
|
+
In ``session_factory=``-only mode (no ``engine=``), the bind is taken
|
|
418
|
+
from the factory itself via ``db.resolve_bind``, which raises a clear
|
|
419
|
+
error when the factory carries no async engine (SDD C.3).
|
|
420
|
+
|
|
421
|
+
Kept as a private alias for one release — the ERP example calls it
|
|
422
|
+
directly from its own host lifespan (SDD C.2 review amendments).
|
|
423
|
+
"""
|
|
424
|
+
from hyperadmin.db import create_tables, resolve_bind
|
|
425
|
+
|
|
426
|
+
bind = self.engine if self.engine is not None else resolve_bind(self.session_factory)
|
|
427
|
+
await create_tables(bind)
|
|
428
|
+
|
|
429
|
+
async def _create_tables_if_opted_in(self) -> None:
|
|
430
|
+
"""``Lifecycle``'s ``create_tables`` callable: respects the opt-in decision.
|
|
431
|
+
|
|
432
|
+
``self._auto_create_tables`` is computed once, in ``__init__``, from the
|
|
433
|
+
settings this ``Admin`` was built with (SDD C.2) — never re-evaluated here.
|
|
434
|
+
"""
|
|
435
|
+
if self._auto_create_tables:
|
|
436
|
+
await self._create_db_and_tables()
|
|
437
|
+
|
|
438
|
+
async def _drain_realtime(self) -> None:
|
|
439
|
+
"""``Lifecycle``'s ``drain`` callable: a no-op when realtime is disabled."""
|
|
440
|
+
if self._realtime_registry is not None:
|
|
441
|
+
await self._realtime_registry.drain()
|
|
442
|
+
if self._realtime_emitter is not None:
|
|
443
|
+
await self._realtime_emitter.drain()
|
|
444
|
+
if self._realtime_pubsub is not None:
|
|
445
|
+
await self._realtime_pubsub.close()
|
|
446
|
+
|
|
447
|
+
def publish_event(self, event: RealtimeEvent) -> None:
|
|
448
|
+
"""Publish a custom CRUD event; a no-op unless realtime and notifications are enabled."""
|
|
449
|
+
if (
|
|
450
|
+
self._realtime_emitter is None
|
|
451
|
+
or event.model_name.lower() not in self._notification_models
|
|
452
|
+
):
|
|
453
|
+
logger.debug("Dropping realtime event for %s (not enabled)", event.model_name)
|
|
454
|
+
return
|
|
455
|
+
self._realtime_emitter.schedule(event)
|
|
456
|
+
|
|
457
|
+
# ── Public lifecycle API (SDD C.2) ─────────────────────────────────────
|
|
458
|
+
|
|
459
|
+
async def startup(self) -> None:
|
|
460
|
+
"""Create tables (if opted in), then sync permissions. Idempotent.
|
|
461
|
+
|
|
462
|
+
Call this directly, or compose :meth:`lifespan` into the host's own
|
|
463
|
+
``lifespan=`` — either way it only runs once. When neither is done,
|
|
464
|
+
the first admin request runs it instead, as a safety net (``mount()``
|
|
465
|
+
installs :class:`~hyperadmin.core.lifecycle.StartupGuardMiddleware`).
|
|
466
|
+
"""
|
|
467
|
+
await self._lifecycle.startup()
|
|
468
|
+
|
|
469
|
+
async def shutdown(self) -> None:
|
|
470
|
+
"""Drain realtime (SSE/WebSocket) connections.
|
|
471
|
+
|
|
472
|
+
Unlike :meth:`startup`, this has **no** safety net: it only runs when
|
|
473
|
+
the host calls it directly or composes :meth:`lifespan`.
|
|
474
|
+
"""
|
|
475
|
+
await self._lifecycle.shutdown()
|
|
476
|
+
|
|
477
|
+
def lifespan(self) -> "AbstractAsyncContextManager[None]":
|
|
478
|
+
"""Async context manager the host composes into its own ``lifespan=``.
|
|
479
|
+
|
|
480
|
+
Example::
|
|
481
|
+
|
|
482
|
+
@asynccontextmanager
|
|
483
|
+
async def lifespan(app: FastAPI):
|
|
484
|
+
async with admin.lifespan():
|
|
485
|
+
yield
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
app = FastAPI(lifespan=lifespan)
|
|
489
|
+
"""
|
|
490
|
+
return self._lifecycle.lifespan()
|
|
491
|
+
|
|
492
|
+
async def create_tables(self, scope: "TableScope" = "all") -> None:
|
|
493
|
+
"""Create database tables directly, independent of ``settings.create_tables``.
|
|
494
|
+
|
|
495
|
+
Args:
|
|
496
|
+
scope: ``"hyperadmin"`` creates only the built-in ``hyperadmin_*``
|
|
497
|
+
tables (what ``hyperadmin init-db`` does by default);
|
|
498
|
+
``"all"`` creates every table on ``SQLModel.metadata``,
|
|
499
|
+
matching ``settings.create_tables=True``'s behaviour.
|
|
500
|
+
"""
|
|
501
|
+
from hyperadmin.db import create_tables as db_create_tables
|
|
502
|
+
from hyperadmin.db import resolve_bind
|
|
503
|
+
|
|
504
|
+
bind = self.engine if self.engine is not None else resolve_bind(self.session_factory)
|
|
505
|
+
tables = None
|
|
506
|
+
if scope == "hyperadmin":
|
|
507
|
+
import hyperadmin.auth as auth_module
|
|
508
|
+
|
|
509
|
+
tables = list(auth_module.metadata().tables.values())
|
|
510
|
+
await db_create_tables(bind, tables=tables)
|
|
511
|
+
|
|
512
|
+
def _register_views(self) -> None:
|
|
513
|
+
"""Registers the views from the site registry."""
|
|
514
|
+
from hyperadmin.routing import HyperAdminRouter
|
|
515
|
+
|
|
516
|
+
admin_router = HyperAdminRouter(
|
|
517
|
+
engine=self.engine,
|
|
518
|
+
templates=self.templates,
|
|
519
|
+
permission_checker=self.permission_checker if self._auth_mode is not None else None,
|
|
520
|
+
storage=self.storage,
|
|
521
|
+
timezone=self.settings.tzinfo,
|
|
522
|
+
datetime_format=self.settings.datetime_format,
|
|
523
|
+
session_factory=self.session_factory,
|
|
524
|
+
debug=self.settings.debug,
|
|
525
|
+
route_class=self.router.route_class,
|
|
526
|
+
realtime_emitter=self._realtime_emitter,
|
|
527
|
+
realtime_settings=self.realtime,
|
|
528
|
+
count_cache=InMemoryTTLCache(self.settings.count_cache_max_entries),
|
|
529
|
+
concurrency_use_updated_at=self.settings.concurrency_use_updated_at,
|
|
530
|
+
occ_render_dialog=self.settings.occ_render_dialog,
|
|
531
|
+
home_page=lambda: self.plugins.home_page,
|
|
532
|
+
default_page_size=self.settings.items_per_page,
|
|
533
|
+
hook_dispatcher=self.dispatch_hook,
|
|
534
|
+
plugins=self.plugins,
|
|
535
|
+
)
|
|
536
|
+
admin_router.generate_routes()
|
|
537
|
+
self._nav_sources = admin_router.nav_sources
|
|
538
|
+
self._notification_models = admin_router.notification_models
|
|
539
|
+
routers = admin_router.get_routers()
|
|
540
|
+
for router in routers:
|
|
541
|
+
self.router.include_router(router)
|
|
542
|
+
|
|
543
|
+
def _register_auth_routes(self, path: str) -> None:
|
|
544
|
+
"""Register login/logout (and MFA) routes when auth is enabled."""
|
|
545
|
+
from starlette.requests import Request
|
|
546
|
+
|
|
547
|
+
from hyperadmin.auth.views import login_view, logout_view
|
|
548
|
+
from hyperadmin.views.urls import request_admin_path
|
|
549
|
+
|
|
550
|
+
admin_prefix = path.rstrip("/")
|
|
551
|
+
templates = self.templates
|
|
552
|
+
auth_backend = self.auth_backend
|
|
553
|
+
otp_service = self.otp_service
|
|
554
|
+
|
|
555
|
+
# Redirects use the per-request admin path (SDD C.1), so they follow a
|
|
556
|
+
# host served under a root_path (e.g. "/api/admin/", not "/admin/").
|
|
557
|
+
async def login_get(request: Request):
|
|
558
|
+
base = request_admin_path(request, admin_prefix)
|
|
559
|
+
return await login_view(
|
|
560
|
+
request, templates, auth_backend, base, otp_service, self.dispatch_hook
|
|
561
|
+
)
|
|
562
|
+
|
|
563
|
+
async def login_post(request: Request):
|
|
564
|
+
base = request_admin_path(request, admin_prefix)
|
|
565
|
+
return await login_view(
|
|
566
|
+
request, templates, auth_backend, base, otp_service, self.dispatch_hook
|
|
567
|
+
)
|
|
568
|
+
|
|
569
|
+
async def logout_post(request: Request):
|
|
570
|
+
base = request_admin_path(request, admin_prefix)
|
|
571
|
+
return await logout_view(request, auth_backend, base, self.dispatch_hook)
|
|
572
|
+
|
|
573
|
+
self.router.add_api_route("/login", login_get, methods=["GET"], name="admin-login")
|
|
574
|
+
self.router.add_api_route("/login", login_post, methods=["POST"], name="admin-login-post")
|
|
575
|
+
self.router.add_api_route("/logout", logout_post, methods=["POST"], name="admin-logout")
|
|
576
|
+
|
|
577
|
+
if otp_service is not None:
|
|
578
|
+
self._register_mfa_routes(admin_prefix)
|
|
579
|
+
|
|
580
|
+
def _register_bridge_routes(self, path: str, auth: "ExternalAuth") -> None:
|
|
581
|
+
"""Register the bridge-mode logout, token handoff and login form (SDD B.3, B.4).
|
|
582
|
+
|
|
583
|
+
- ``POST {prefix}/logout``: protected and CSRF-checked; clears the token
|
|
584
|
+
cookie and redirects to ``auth.logout_url or "/"``.
|
|
585
|
+
- ``POST {prefix}/auth/session`` (with ``token_cookie``): exempt from
|
|
586
|
+
CSRF and guarded by its own dependencies, the size check first, then
|
|
587
|
+
``build_admin_dependency(auth)``.
|
|
588
|
+
- ``GET/POST {prefix}/login`` (with ``token_cookie.token_endpoint``): the
|
|
589
|
+
public, CSRF-protected admin login form for bearer-only hosts.
|
|
590
|
+
|
|
591
|
+
Raises:
|
|
592
|
+
ValueError: ``token_endpoint="auto"`` finds no ``OAuth2PasswordBearer``
|
|
593
|
+
in ``auth.get_user``'s dependencies.
|
|
594
|
+
"""
|
|
595
|
+
from starlette.requests import Request
|
|
596
|
+
|
|
597
|
+
from hyperadmin.auth import token_handoff
|
|
598
|
+
from hyperadmin.auth.bridge import build_admin_dependency
|
|
599
|
+
from hyperadmin.views.route import csrf_exempt
|
|
600
|
+
from hyperadmin.views.urls import request_admin_path
|
|
601
|
+
|
|
602
|
+
admin_prefix = path.rstrip("/")
|
|
603
|
+
cookie = auth.token_cookie
|
|
604
|
+
cookie_secure = self.settings.cookie_secure
|
|
605
|
+
|
|
606
|
+
async def logout_post(request: Request):
|
|
607
|
+
return await token_handoff.bridge_logout_view(
|
|
608
|
+
request,
|
|
609
|
+
cookie=cookie,
|
|
610
|
+
admin_path=request_admin_path(request, admin_prefix),
|
|
611
|
+
logout_url=auth.logout_url,
|
|
612
|
+
cookie_secure=cookie_secure,
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
self.router.add_api_route("/logout", logout_post, methods=["POST"], name="admin-logout")
|
|
616
|
+
if cookie is None:
|
|
617
|
+
return
|
|
618
|
+
|
|
619
|
+
@csrf_exempt
|
|
620
|
+
async def handoff_post(request: Request):
|
|
621
|
+
return await token_handoff.token_handoff_view(
|
|
622
|
+
request,
|
|
623
|
+
cookie=cookie,
|
|
624
|
+
admin_path=request_admin_path(request, admin_prefix),
|
|
625
|
+
cookie_secure=cookie_secure,
|
|
626
|
+
next_param=auth.next_param,
|
|
627
|
+
)
|
|
628
|
+
|
|
629
|
+
self.public_router.add_api_route(
|
|
630
|
+
cookie.handoff_path,
|
|
631
|
+
handoff_post,
|
|
632
|
+
methods=["POST"],
|
|
633
|
+
name="admin-token-handoff",
|
|
634
|
+
dependencies=[
|
|
635
|
+
Depends(token_handoff.reject_oversized_token),
|
|
636
|
+
Depends(build_admin_dependency(auth)),
|
|
637
|
+
],
|
|
638
|
+
)
|
|
639
|
+
if cookie.token_endpoint is None:
|
|
640
|
+
return
|
|
641
|
+
endpoint = token_handoff.resolve_token_endpoint(cookie.token_endpoint, auth.get_user)
|
|
642
|
+
templates = self.templates
|
|
643
|
+
host_app = self.app
|
|
644
|
+
|
|
645
|
+
async def login(request: Request):
|
|
646
|
+
return await token_handoff.bridge_login_view(
|
|
647
|
+
request,
|
|
648
|
+
templates=templates,
|
|
649
|
+
cookie=cookie,
|
|
650
|
+
endpoint=endpoint,
|
|
651
|
+
host_app=host_app,
|
|
652
|
+
admin_path=request_admin_path(request, admin_prefix),
|
|
653
|
+
cookie_secure=cookie_secure,
|
|
654
|
+
next_param=auth.next_param,
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
self.public_router.add_api_route(
|
|
658
|
+
"/login", login, methods=["GET", "POST"], name="admin-login"
|
|
659
|
+
)
|
|
660
|
+
|
|
661
|
+
def _register_mfa_routes(self, admin_prefix: str) -> None:
|
|
662
|
+
"""Register the MFA challenge / verify / resend / settings endpoints.
|
|
663
|
+
|
|
664
|
+
Only called when ``otp_service`` is configured. Apps without MFA see
|
|
665
|
+
no new routes — ``mfa_enabled=True`` users in such apps will hit the
|
|
666
|
+
normal single-factor path because ``login_view`` skips the MFA branch
|
|
667
|
+
unless an ``otp_service`` is provided.
|
|
668
|
+
"""
|
|
669
|
+
from starlette.requests import Request
|
|
670
|
+
|
|
671
|
+
from hyperadmin.auth.views import (
|
|
672
|
+
mfa_challenge_view,
|
|
673
|
+
mfa_disable_view,
|
|
674
|
+
mfa_enable_view,
|
|
675
|
+
mfa_resend_view,
|
|
676
|
+
mfa_settings_view,
|
|
677
|
+
mfa_verify_view,
|
|
678
|
+
)
|
|
679
|
+
from hyperadmin.views.urls import request_admin_path
|
|
680
|
+
|
|
681
|
+
templates = self.templates
|
|
682
|
+
auth_backend = self.auth_backend
|
|
683
|
+
otp_service = self.otp_service
|
|
684
|
+
|
|
685
|
+
# Redirects and template links use the per-request admin path (SDD C.1).
|
|
686
|
+
async def challenge_get(request: Request):
|
|
687
|
+
base = request_admin_path(request, admin_prefix)
|
|
688
|
+
return await mfa_challenge_view(request, templates, base)
|
|
689
|
+
|
|
690
|
+
async def verify_post(request: Request):
|
|
691
|
+
base = request_admin_path(request, admin_prefix)
|
|
692
|
+
return await mfa_verify_view(request, templates, auth_backend, otp_service, base)
|
|
693
|
+
|
|
694
|
+
async def resend_post(request: Request):
|
|
695
|
+
base = request_admin_path(request, admin_prefix)
|
|
696
|
+
return await mfa_resend_view(request, templates, auth_backend, otp_service, base)
|
|
697
|
+
|
|
698
|
+
async def settings_get(request: Request):
|
|
699
|
+
base = request_admin_path(request, admin_prefix)
|
|
700
|
+
return await mfa_settings_view(request, templates, base)
|
|
701
|
+
|
|
702
|
+
async def enable_post(request: Request):
|
|
703
|
+
base = request_admin_path(request, admin_prefix)
|
|
704
|
+
return await mfa_enable_view(request, templates, auth_backend, otp_service, base)
|
|
705
|
+
|
|
706
|
+
async def disable_post(request: Request):
|
|
707
|
+
base = request_admin_path(request, admin_prefix)
|
|
708
|
+
return await mfa_disable_view(request, templates, auth_backend, otp_service, base)
|
|
709
|
+
|
|
710
|
+
self.router.add_api_route(
|
|
711
|
+
"/mfa/challenge", challenge_get, methods=["GET"], name="admin-mfa-challenge"
|
|
712
|
+
)
|
|
713
|
+
self.router.add_api_route(
|
|
714
|
+
"/mfa/verify", verify_post, methods=["POST"], name="admin-mfa-verify"
|
|
715
|
+
)
|
|
716
|
+
self.router.add_api_route(
|
|
717
|
+
"/mfa/resend", resend_post, methods=["POST"], name="admin-mfa-resend"
|
|
718
|
+
)
|
|
719
|
+
self.router.add_api_route(
|
|
720
|
+
"/mfa/settings", settings_get, methods=["GET"], name="admin-mfa-settings"
|
|
721
|
+
)
|
|
722
|
+
self.router.add_api_route(
|
|
723
|
+
"/mfa/enable", enable_post, methods=["POST"], name="admin-mfa-enable"
|
|
724
|
+
)
|
|
725
|
+
self.router.add_api_route(
|
|
726
|
+
"/mfa/disable", disable_post, methods=["POST"], name="admin-mfa-disable"
|
|
727
|
+
)
|
|
728
|
+
|
|
729
|
+
def _register_realtime_routes(self) -> None:
|
|
730
|
+
"""Register the SSE GET route and WebSocket route on the admin router.
|
|
731
|
+
|
|
732
|
+
Both endpoints share a single ``ConnectionRegistry`` so ``shutdown()``
|
|
733
|
+
(``Admin.shutdown()`` / ``Lifecycle.shutdown()``) can drain every open
|
|
734
|
+
connection in one pass. There is no ``on_event("shutdown")`` hook here
|
|
735
|
+
any more (SDD C.2): it only ever drained when the host did NOT pass
|
|
736
|
+
its own ``lifespan=``, which is backwards — draining matters most
|
|
737
|
+
for hosts that DO manage their own lifespan. Compose ``admin.lifespan()``
|
|
738
|
+
(or call ``admin.shutdown()`` yourself) to drain on shutdown.
|
|
739
|
+
"""
|
|
740
|
+
if self.realtime is None or self._realtime_registry is None:
|
|
741
|
+
return
|
|
742
|
+
registry = self._realtime_registry
|
|
743
|
+
settings = self.realtime
|
|
744
|
+
|
|
745
|
+
sse_handler = make_sse_handler(registry, settings)
|
|
746
|
+
self.router.add_api_route(
|
|
747
|
+
"/realtime/sse",
|
|
748
|
+
sse_handler,
|
|
749
|
+
methods=["GET"],
|
|
750
|
+
name="admin-realtime-sse",
|
|
751
|
+
)
|
|
752
|
+
self._register_realtime_ws_route(registry, settings)
|
|
753
|
+
|
|
754
|
+
if settings.enable_test_endpoints:
|
|
755
|
+
from hyperadmin.realtime._debug import (
|
|
756
|
+
make_count_handler,
|
|
757
|
+
make_disconnect_all_handler,
|
|
758
|
+
make_disconnect_transport_handler,
|
|
759
|
+
)
|
|
760
|
+
|
|
761
|
+
self.router.add_api_route(
|
|
762
|
+
"/_test/realtime/count",
|
|
763
|
+
make_count_handler(registry),
|
|
764
|
+
methods=["GET"],
|
|
765
|
+
name="admin-realtime-test-count",
|
|
766
|
+
)
|
|
767
|
+
self.router.add_api_route(
|
|
768
|
+
"/_test/realtime/disconnect_all",
|
|
769
|
+
make_disconnect_all_handler(registry),
|
|
770
|
+
methods=["POST"],
|
|
771
|
+
name="admin-realtime-test-disconnect-all",
|
|
772
|
+
)
|
|
773
|
+
self.router.add_api_route(
|
|
774
|
+
"/_test/realtime/disconnect/{transport}",
|
|
775
|
+
make_disconnect_transport_handler(registry),
|
|
776
|
+
methods=["POST"],
|
|
777
|
+
name="admin-realtime-test-disconnect-transport",
|
|
778
|
+
)
|
|
779
|
+
|
|
780
|
+
def _register_realtime_ws_route(
|
|
781
|
+
self, registry: ConnectionRegistry, settings: RealtimeSettings
|
|
782
|
+
) -> None:
|
|
783
|
+
"""Register the realtime WebSocket route, with its handshake ``Origin`` check.
|
|
784
|
+
|
|
785
|
+
In bridge mode the host resolves WebSocket users through
|
|
786
|
+
``ExternalAuth.websocket_user`` (HTTP dependencies do not run on WebSocket
|
|
787
|
+
scope). Without it no user could ever be admitted, so the route is not
|
|
788
|
+
registered at all; SSE keeps working (SDD B, Edge cases).
|
|
789
|
+
"""
|
|
790
|
+
from hyperadmin.views.csrf import make_websocket_origin_check
|
|
791
|
+
|
|
792
|
+
ws_auth: Any = self.auth_backend
|
|
793
|
+
if self.auth is not None:
|
|
794
|
+
if self.auth.websocket_user is None:
|
|
795
|
+
logger.info(
|
|
796
|
+
"HyperAdmin realtime: WebSocket route not registered in bridge mode "
|
|
797
|
+
"because ExternalAuth.websocket_user is not set; SSE stays available."
|
|
798
|
+
)
|
|
799
|
+
return
|
|
800
|
+
from hyperadmin.auth.bridge import BridgeWebSocketAuth
|
|
801
|
+
|
|
802
|
+
ws_auth = BridgeWebSocketAuth(self.auth)
|
|
803
|
+
origin_allowed = make_websocket_origin_check(self.settings.csrf_trusted_origins)
|
|
804
|
+
ws_handler = make_ws_handler(
|
|
805
|
+
registry,
|
|
806
|
+
settings,
|
|
807
|
+
ws_auth,
|
|
808
|
+
origin_allowed,
|
|
809
|
+
pubsub=self._realtime_pubsub,
|
|
810
|
+
authorize=self._authorize_notification_subscription,
|
|
811
|
+
)
|
|
812
|
+
# On the admin router, so it lands under the prefix in both mount modes
|
|
813
|
+
# (and inside the namespace in isolated mode).
|
|
814
|
+
self.router.add_websocket_route("/realtime/ws", ws_handler, name="admin-realtime-ws")
|
|
815
|
+
self.router.add_api_route(
|
|
816
|
+
"/realtime/ws",
|
|
817
|
+
ws_http_fallback,
|
|
818
|
+
methods=["GET"],
|
|
819
|
+
include_in_schema=False,
|
|
820
|
+
name="admin-realtime-ws-http",
|
|
821
|
+
)
|
|
822
|
+
|
|
823
|
+
async def _authorize_notification_subscription(self, user: Any, model_name: str) -> bool:
|
|
824
|
+
"""Whether ``user`` may follow CRUD notifications of ``model_name`` over the WebSocket.
|
|
825
|
+
|
|
826
|
+
The model must have notifications enabled and the user must hold the same
|
|
827
|
+
``view_<model>`` permission the list page checks (always true without auth).
|
|
828
|
+
"""
|
|
829
|
+
name = model_name.lower()
|
|
830
|
+
if name not in self._notification_models:
|
|
831
|
+
return False
|
|
832
|
+
if self.permission_checker is None:
|
|
833
|
+
return True
|
|
834
|
+
# A socket keeps one user object for its whole life, so the permission set
|
|
835
|
+
# remembered on it is dropped: each subscribe reads the database. Looked up,
|
|
836
|
+
# not imported (see ``__init__``: the module registers the hyperadmin_* tables).
|
|
837
|
+
permissions = sys.modules.get("hyperadmin.auth.permissions")
|
|
838
|
+
if permissions is not None:
|
|
839
|
+
permissions.forget_user_permissions(user)
|
|
840
|
+
return bool(await self.permission_checker.has_permission(user, f"view_{name}"))
|
|
841
|
+
|
|
842
|
+
def _notification_model_labels(self) -> dict[str, tuple[Any, Any]]:
|
|
843
|
+
"""Map each notifying model's slug to its (singular, plural) verbose names.
|
|
844
|
+
|
|
845
|
+
The names stay lazy, so toasts render them in the request locale.
|
|
846
|
+
"""
|
|
847
|
+
from hyperadmin.core.registry import site
|
|
848
|
+
|
|
849
|
+
labels: dict[str, tuple[Any, Any]] = {}
|
|
850
|
+
for model, admin_class in site._registry.items():
|
|
851
|
+
slug = model.__name__.lower()
|
|
852
|
+
if slug in self._notification_models:
|
|
853
|
+
labels[slug] = (
|
|
854
|
+
admin_class.get_verbose_name(model),
|
|
855
|
+
admin_class.get_verbose_name_plural(model),
|
|
856
|
+
)
|
|
857
|
+
return labels
|
|
858
|
+
|
|
859
|
+
def _register_locale_route(self, path: str) -> None:
|
|
860
|
+
"""Register the POST /locale route for the locale switcher."""
|
|
861
|
+
from starlette.requests import Request
|
|
862
|
+
from starlette.responses import Response
|
|
863
|
+
|
|
864
|
+
from hyperadmin.views.locale import set_locale_view
|
|
865
|
+
|
|
866
|
+
admin_prefix = path.rstrip("/")
|
|
867
|
+
settings = self.settings
|
|
868
|
+
|
|
869
|
+
async def locale_post(request: Request) -> Response:
|
|
870
|
+
return await set_locale_view(request, settings, admin_prefix)
|
|
871
|
+
|
|
872
|
+
self.router.add_api_route(
|
|
873
|
+
"/locale",
|
|
874
|
+
locale_post,
|
|
875
|
+
methods=["POST"],
|
|
876
|
+
name="admin-locale",
|
|
877
|
+
)
|
|
878
|
+
|
|
879
|
+
def _add_auth_middleware(self, target: FastAPI, admin_prefix: str, *, isolated: bool) -> None:
|
|
880
|
+
"""Add session and authentication middleware to ``target``.
|
|
881
|
+
|
|
882
|
+
``target`` is the private sub-app in isolated mode, so neither the session
|
|
883
|
+
nor the auth check ever touches a host request; in router mode it is the
|
|
884
|
+
host app, and ``AuthenticationMiddleware`` matches ``admin_prefix`` on whole
|
|
885
|
+
path segments.
|
|
886
|
+
|
|
887
|
+
The session cookie (SDD C.4) is ``settings.session_cookie`` scoped to the
|
|
888
|
+
per-request admin path, and ``AdminSessionMiddleware`` keeps a host
|
|
889
|
+
``scope["session"]`` intact. Router mode keeps the legacy cookie
|
|
890
|
+
(``session``, ``Path=/``) unless ``session_cookie`` is set explicitly.
|
|
891
|
+
"""
|
|
892
|
+
from starlette.requests import Request
|
|
893
|
+
|
|
894
|
+
from hyperadmin.auth.middleware import AuthenticationMiddleware
|
|
895
|
+
from hyperadmin.auth.session_middleware import AdminSessionMiddleware
|
|
896
|
+
from hyperadmin.views.urls import request_admin_path
|
|
897
|
+
|
|
898
|
+
def admin_path(request: Request) -> str:
|
|
899
|
+
return request_admin_path(request, admin_prefix)
|
|
900
|
+
|
|
901
|
+
settings = self.settings
|
|
902
|
+
scoped_cookie = isolated or "session_cookie" in settings.model_fields_set
|
|
903
|
+
|
|
904
|
+
target.add_middleware(
|
|
905
|
+
AuthenticationMiddleware,
|
|
906
|
+
auth_backend=self.auth_backend,
|
|
907
|
+
admin_prefix=admin_prefix,
|
|
908
|
+
permission_checker=self.permission_checker,
|
|
909
|
+
isolated=isolated,
|
|
910
|
+
admin_path=admin_path,
|
|
911
|
+
user_cache_ttl=settings.user_cache_ttl,
|
|
912
|
+
public_paths=self._oauth_public_paths(),
|
|
913
|
+
)
|
|
914
|
+
if self.oauth_backend is not None:
|
|
915
|
+
# Between the session and authentication middleware (add_middleware prepends).
|
|
916
|
+
from hyperadmin.auth.oauth import wiring as oauth_wiring
|
|
917
|
+
|
|
918
|
+
oauth_wiring.add_refresh_middleware(self, target)
|
|
919
|
+
target.add_middleware(
|
|
920
|
+
AdminSessionMiddleware,
|
|
921
|
+
secret_key=settings.secret_key,
|
|
922
|
+
session_cookie=settings.session_cookie if scoped_cookie else "session",
|
|
923
|
+
max_age=settings.session_max_age,
|
|
924
|
+
same_site=settings.session_same_site,
|
|
925
|
+
cookie_secure=settings.cookie_secure,
|
|
926
|
+
admin_path=admin_path if scoped_cookie else None,
|
|
927
|
+
)
|
|
928
|
+
|
|
929
|
+
def _configure_oauth(self, oauth_backend: "OAuthBackend | None") -> "OAuthBackend | None":
|
|
930
|
+
"""Validate and bind ``oauth_backend`` (``docs/specs/oauth-sso.md``); ``None`` is off."""
|
|
931
|
+
if oauth_backend is not None:
|
|
932
|
+
from hyperadmin.auth.oauth import wiring as oauth_wiring
|
|
933
|
+
|
|
934
|
+
oauth_wiring.configure(self, oauth_backend)
|
|
935
|
+
return oauth_backend
|
|
936
|
+
|
|
937
|
+
def _oauth_public_paths(self) -> tuple[str, ...]:
|
|
938
|
+
"""Admin paths OAuth opens to signed-out visitors; none without ``oauth_backend``."""
|
|
939
|
+
if self.oauth_backend is None:
|
|
940
|
+
return ()
|
|
941
|
+
from hyperadmin.auth.oauth.wiring import PUBLIC_PATHS
|
|
942
|
+
|
|
943
|
+
return PUBLIC_PATHS
|
|
944
|
+
|
|
945
|
+
def _add_rate_limit_middleware(self, target: FastAPI, admin_prefix: str) -> None:
|
|
946
|
+
"""Add the rate-limit middleware to ``target`` when a limit is configured.
|
|
947
|
+
|
|
948
|
+
Call it last so it is outermost: a throttled request is answered before the
|
|
949
|
+
startup sync, session, authentication or any database work.
|
|
950
|
+
"""
|
|
951
|
+
from hyperadmin.core.rate_limit import InMemoryRateLimiter
|
|
952
|
+
from hyperadmin.views.rate_limit import RateLimitMiddleware
|
|
953
|
+
|
|
954
|
+
settings = self.settings
|
|
955
|
+
window = settings.rate_limit_window_seconds
|
|
956
|
+
limiter = self.rate_limiter
|
|
957
|
+
if limiter is None and settings.rate_limit_requests is not None:
|
|
958
|
+
limiter = InMemoryRateLimiter(settings.rate_limit_requests, window)
|
|
959
|
+
login_limiter = (
|
|
960
|
+
InMemoryRateLimiter(settings.rate_limit_login_requests, window)
|
|
961
|
+
if settings.rate_limit_login_requests is not None
|
|
962
|
+
else None
|
|
963
|
+
)
|
|
964
|
+
if limiter is None and login_limiter is None:
|
|
965
|
+
return
|
|
966
|
+
target.add_middleware(
|
|
967
|
+
RateLimitMiddleware,
|
|
968
|
+
limiter=limiter,
|
|
969
|
+
login_limiter=login_limiter,
|
|
970
|
+
admin_prefix=admin_prefix,
|
|
971
|
+
)
|
|
972
|
+
|
|
973
|
+
def _add_locale_middleware(self, target: FastAPI) -> None:
|
|
974
|
+
"""Add the locale-resolution middleware to ``target``."""
|
|
975
|
+
from hyperadmin.i18n import LocaleMiddleware
|
|
976
|
+
|
|
977
|
+
target.add_middleware(LocaleMiddleware, settings=self.settings)
|
|
978
|
+
|
|
979
|
+
def _default_storage(self) -> Any:
|
|
980
|
+
"""Build the storage ``settings.storage_backend`` selects when no ``storage=`` is passed.
|
|
981
|
+
|
|
982
|
+
``"s3"`` returns an ``S3StorageBackend`` built from the ``aws_*`` settings
|
|
983
|
+
(story #402). ``"local"`` returns ``None``: uploads stay off until the host
|
|
984
|
+
passes a ``FileSystemStorage``, as before.
|
|
985
|
+
"""
|
|
986
|
+
if self.settings.storage_backend != "s3":
|
|
987
|
+
return None
|
|
988
|
+
from hyperadmin.uploads.storage import S3StorageBackend
|
|
989
|
+
|
|
990
|
+
return S3StorageBackend.from_settings(self.settings)
|
|
991
|
+
|
|
992
|
+
def _mount_public_uploads(self, path: str) -> None:
|
|
993
|
+
"""Legacy escape hatch: mount the storage directory publicly at ``path`` (SDD C.5).
|
|
994
|
+
|
|
995
|
+
Only used when ``settings.public_uploads_path`` is set. Files are
|
|
996
|
+
otherwise served per record behind the admin's permission checks.
|
|
997
|
+
"""
|
|
998
|
+
root = storage_root(self.storage)
|
|
999
|
+
if root is None or not root.is_dir():
|
|
1000
|
+
logger.warning(
|
|
1001
|
+
"public_uploads_path=%r ignored: the storage has no local directory", path
|
|
1002
|
+
)
|
|
1003
|
+
return
|
|
1004
|
+
logger.warning(
|
|
1005
|
+
"HyperAdmin serves uploaded files publicly at %r (settings.public_uploads_path), "
|
|
1006
|
+
"outside the admin's authentication and permissions. Unset it to serve files "
|
|
1007
|
+
"only per record under the admin prefix.",
|
|
1008
|
+
path,
|
|
1009
|
+
)
|
|
1010
|
+
self.app.mount(path, StaticFiles(directory=str(root)), name="uploads")
|
|
1011
|
+
|
|
1012
|
+
async def _sync_permissions(self) -> None:
|
|
1013
|
+
"""Sync permissions for all registered models to the database."""
|
|
1014
|
+
if not self.permission_registry:
|
|
1015
|
+
return
|
|
1016
|
+
|
|
1017
|
+
from hyperadmin.core.registry import site
|
|
1018
|
+
|
|
1019
|
+
models = []
|
|
1020
|
+
for model, admin_class in site._registry.items():
|
|
1021
|
+
model_name = model.__name__.lower()
|
|
1022
|
+
models.append((model_name, admin_class))
|
|
1023
|
+
await self.permission_registry.sync_permissions(models)
|
|
1024
|
+
await self._sync_plugin_permissions(models)
|
|
1025
|
+
|
|
1026
|
+
async def _sync_plugin_permissions(self, models: "list[tuple[str, Any]]") -> None:
|
|
1027
|
+
"""Sync plugin codenames next to the model ones (plugin-registry SDD).
|
|
1028
|
+
|
|
1029
|
+
Needs a registry with ``sync_codenames`` (``PermissionSyncService``); a
|
|
1030
|
+
codename a model already defines is logged and skipped.
|
|
1031
|
+
"""
|
|
1032
|
+
sync_codenames = getattr(self.permission_registry, "sync_codenames", None)
|
|
1033
|
+
if not self.plugins.permissions or sync_codenames is None:
|
|
1034
|
+
return
|
|
1035
|
+
from hyperadmin.auth.permissions import (
|
|
1036
|
+
generate_admin_permissions,
|
|
1037
|
+
generate_default_permissions,
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
taken = {
|
|
1041
|
+
codename
|
|
1042
|
+
for model_name, admin_class in models
|
|
1043
|
+
for codename, _ in [
|
|
1044
|
+
*generate_default_permissions(model_name),
|
|
1045
|
+
*generate_admin_permissions(model_name, admin_class),
|
|
1046
|
+
]
|
|
1047
|
+
}
|
|
1048
|
+
await sync_codenames(plugin_permission_rows(self.plugins, taken=taken))
|
|
1049
|
+
|
|
1050
|
+
def _register_permissions_matrix(self) -> None:
|
|
1051
|
+
"""Register the built-in permission-matrix page (``docs/specs/permission-matrix-ui.md``).
|
|
1052
|
+
|
|
1053
|
+
It edits the built-in ``Group`` / ``GroupPermission`` tables, so it is only
|
|
1054
|
+
registered when those are in use: built-in auth, or bridge mode with
|
|
1055
|
+
``settings.register_auth_models=True``. Otherwise there are no groups to
|
|
1056
|
+
edit and the page, its nav entry and its codename are left out (the URL
|
|
1057
|
+
answers 404), as they are with ``permissions_matrix_enabled=False``.
|
|
1058
|
+
"""
|
|
1059
|
+
if not self.settings.permissions_matrix_enabled or self._auth_mode is None:
|
|
1060
|
+
return
|
|
1061
|
+
if self._auth_mode == "external" and self.settings.register_auth_models is not True:
|
|
1062
|
+
logger.info(
|
|
1063
|
+
"HyperAdmin permission matrix not registered: Admin(auth=...) without the "
|
|
1064
|
+
"built-in auth models (settings.register_auth_models=True), so there are "
|
|
1065
|
+
"no groups to edit."
|
|
1066
|
+
)
|
|
1067
|
+
return
|
|
1068
|
+
from hyperadmin.views.permissions_matrix import PermissionMatrixPage
|
|
1069
|
+
|
|
1070
|
+
self.plugins.register(PermissionMatrixPage(self), admin=self)
|
|
1071
|
+
|
|
1072
|
+
def dispatch_hook(self, hook: str, /, **kwargs: Any) -> None:
|
|
1073
|
+
"""Fire a plugin lifecycle hook with ``admin=self`` (errors are logged, not raised)."""
|
|
1074
|
+
self.plugins.dispatch_hook(hook, admin=self, **kwargs)
|
|
1075
|
+
|
|
1076
|
+
def _apply_plugins(self) -> None:
|
|
1077
|
+
"""Add plugin pages after the model routes, plugin templates and sidebar entries."""
|
|
1078
|
+
from hyperadmin.core.registry import site
|
|
1079
|
+
|
|
1080
|
+
model_slugs = {model.__name__.lower() for model in site._registry}
|
|
1081
|
+
self.router.routes.extend(
|
|
1082
|
+
build_plugin_routes(
|
|
1083
|
+
self.plugins, route_class=self.router.route_class, reserved=model_slugs
|
|
1084
|
+
)
|
|
1085
|
+
)
|
|
1086
|
+
extend_template_loader(self.templates.env, self.plugins)
|
|
1087
|
+
nav_entries = resolve_plugin_nav_entries(self.plugins, self.router)
|
|
1088
|
+
self.templates.env.globals["plugin_nav"] = plugin_nav_sections(nav_entries)
|
|
1089
|
+
self.templates.env.globals["nav_tree"] = build_nav_tree(
|
|
1090
|
+
self._nav_sources, nav_entries, self.nav_groups
|
|
1091
|
+
)
|
|
1092
|
+
|
|
1093
|
+
def _auto_register_models(self) -> None:
|
|
1094
|
+
"""Auto-register discovered SQLModel models with smart defaults.
|
|
1095
|
+
|
|
1096
|
+
For each model not already in ``site._registry``, generates
|
|
1097
|
+
``AdminOptions`` with inferred list_display, search_fields,
|
|
1098
|
+
and list_filter. Called from ``mount()`` when
|
|
1099
|
+
``settings.auto_discover`` is ``True``.
|
|
1100
|
+
"""
|
|
1101
|
+
from hyperadmin.core.model import ModelAdmin
|
|
1102
|
+
from hyperadmin.core.options import AdminOptions
|
|
1103
|
+
from hyperadmin.core.registry import site
|
|
1104
|
+
|
|
1105
|
+
discovered = discover_sqlmodel_models()
|
|
1106
|
+
for model in discovered:
|
|
1107
|
+
if model in site._registry:
|
|
1108
|
+
continue
|
|
1109
|
+
try:
|
|
1110
|
+
options = AdminOptions(
|
|
1111
|
+
list_display=infer_list_display(model),
|
|
1112
|
+
search_fields=infer_search_fields(model),
|
|
1113
|
+
list_filter=infer_list_filter(model),
|
|
1114
|
+
)
|
|
1115
|
+
admin_cls = type(f"{model.__name__}Admin", (ModelAdmin,), {})
|
|
1116
|
+
site.register(model, admin_class=admin_cls, options=options)
|
|
1117
|
+
except Exception:
|
|
1118
|
+
logger.warning("Failed to auto-register model %s", model.__name__)
|
|
1119
|
+
|
|
1120
|
+
def _should_register_auth_models(self) -> bool:
|
|
1121
|
+
"""Whether ``mount()`` registers the built-in auth model admins (SDD B.3).
|
|
1122
|
+
|
|
1123
|
+
``settings.register_auth_models=None`` (default) means on for
|
|
1124
|
+
``auth_backend=``, off for ``auth=`` and without auth; a bool wins.
|
|
1125
|
+
"""
|
|
1126
|
+
explicit = self.settings.register_auth_models
|
|
1127
|
+
if explicit is not None:
|
|
1128
|
+
return explicit
|
|
1129
|
+
return self._auth_mode == "builtin"
|
|
1130
|
+
|
|
1131
|
+
def _register_auth_models(self) -> None:
|
|
1132
|
+
"""Auto-register User, Group, Permission in the admin site.
|
|
1133
|
+
|
|
1134
|
+
Called from ``mount()`` when :meth:`_should_register_auth_models` is true.
|
|
1135
|
+
Skips silently if a model is already registered.
|
|
1136
|
+
Each auth model gets its own admin class to avoid shared
|
|
1137
|
+
class-level state on the default ``ModelAdmin``. They join the sidebar's
|
|
1138
|
+
"Access" group, next to the permission matrix.
|
|
1139
|
+
"""
|
|
1140
|
+
from hyperadmin.auth.models import Group, Permission, User
|
|
1141
|
+
from hyperadmin.core.model import ModelAdmin
|
|
1142
|
+
from hyperadmin.core.navigation import ACCESS_GROUP
|
|
1143
|
+
from hyperadmin.core.options import AdminOptions
|
|
1144
|
+
from hyperadmin.core.registry import site
|
|
1145
|
+
|
|
1146
|
+
if User not in site._registry:
|
|
1147
|
+
user_admin = type(
|
|
1148
|
+
"UserAdmin", (ModelAdmin,), {"nav_group": ACCESS_GROUP, "icon": "user"}
|
|
1149
|
+
)
|
|
1150
|
+
site.register(
|
|
1151
|
+
User,
|
|
1152
|
+
admin_class=user_admin,
|
|
1153
|
+
options=AdminOptions(
|
|
1154
|
+
can_delete=False,
|
|
1155
|
+
list_filter=["is_active", "is_superuser"],
|
|
1156
|
+
),
|
|
1157
|
+
)
|
|
1158
|
+
if Group not in site._registry:
|
|
1159
|
+
group_admin = type(
|
|
1160
|
+
"GroupAdmin",
|
|
1161
|
+
(ModelAdmin,),
|
|
1162
|
+
{"nav_group": ACCESS_GROUP, "icon": "users", "nav_order": 1},
|
|
1163
|
+
)
|
|
1164
|
+
site.register(Group, admin_class=group_admin)
|
|
1165
|
+
if Permission not in site._registry:
|
|
1166
|
+
perm_admin = type(
|
|
1167
|
+
"PermissionAdmin",
|
|
1168
|
+
(ModelAdmin,),
|
|
1169
|
+
{"nav_group": ACCESS_GROUP, "icon": "key-round", "nav_order": 2},
|
|
1170
|
+
)
|
|
1171
|
+
site.register(
|
|
1172
|
+
Permission,
|
|
1173
|
+
admin_class=perm_admin,
|
|
1174
|
+
options=AdminOptions(can_create=False, can_delete=False),
|
|
1175
|
+
)
|
|
1176
|
+
|
|
1177
|
+
def _resolve_mount_mode(self, admin_prefix: str) -> bool:
|
|
1178
|
+
"""Return ``True`` for an isolated sub-app mount, ``False`` for router mode.
|
|
1179
|
+
|
|
1180
|
+
Router mode is the deprecated legacy mode (SDD C.1). Mounting at the root
|
|
1181
|
+
always uses it: a ``Mount("/")`` would shadow every host route.
|
|
1182
|
+
"""
|
|
1183
|
+
if self.settings.mount_mode == "router":
|
|
1184
|
+
warnings.warn(
|
|
1185
|
+
"HyperAdmin mount_mode='router' is deprecated and will be removed in 0.6. "
|
|
1186
|
+
"The default isolated mode mounts the admin as a private sub-application; "
|
|
1187
|
+
"admin route names then resolve as "
|
|
1188
|
+
f"'{self.settings.route_namespace}:<name>'.",
|
|
1189
|
+
DeprecationWarning,
|
|
1190
|
+
stacklevel=3,
|
|
1191
|
+
)
|
|
1192
|
+
return False
|
|
1193
|
+
if not admin_prefix:
|
|
1194
|
+
logger.warning(
|
|
1195
|
+
"HyperAdmin mounted at '/': using router mode, because an isolated "
|
|
1196
|
+
"sub-application mounted at the root would shadow every host route."
|
|
1197
|
+
)
|
|
1198
|
+
return False
|
|
1199
|
+
return True
|
|
1200
|
+
|
|
1201
|
+
def _make_route_class(self) -> "type[APIRoute]":
|
|
1202
|
+
"""Build the ``HyperAdminRoute`` class shared by every admin router (SDD B.2)."""
|
|
1203
|
+
from hyperadmin.views.route import DEFAULT_API_PREFIXES, make_admin_route_class
|
|
1204
|
+
|
|
1205
|
+
csrf = self._build_csrf_guard()
|
|
1206
|
+
auth = self.auth
|
|
1207
|
+
if auth is None:
|
|
1208
|
+
return make_admin_route_class(self.templates, csrf=csrf)
|
|
1209
|
+
# Bridge mode: the route class owns auth-error translation and the
|
|
1210
|
+
# token-cookie bridge (SDD B.2, B.4).
|
|
1211
|
+
token_cookie = auth.token_cookie
|
|
1212
|
+
# A rejected token handoff is an API call from an SPA: always a bare 401,
|
|
1213
|
+
# never a browser redirect to a login page (SDD B.4).
|
|
1214
|
+
api_prefixes = (
|
|
1215
|
+
(*DEFAULT_API_PREFIXES, token_cookie.handoff_path)
|
|
1216
|
+
if token_cookie is not None
|
|
1217
|
+
else DEFAULT_API_PREFIXES
|
|
1218
|
+
)
|
|
1219
|
+
return make_admin_route_class(
|
|
1220
|
+
self.templates,
|
|
1221
|
+
csrf=csrf,
|
|
1222
|
+
translate_auth_errors=True,
|
|
1223
|
+
api_prefixes=api_prefixes,
|
|
1224
|
+
login_url=auth.login_url,
|
|
1225
|
+
login_path="/login" if token_cookie and token_cookie.token_endpoint else None,
|
|
1226
|
+
next_param=auth.next_param,
|
|
1227
|
+
token_cookie=token_cookie.name if token_cookie is not None else None,
|
|
1228
|
+
token_scheme=token_cookie.scheme if token_cookie is not None else "Bearer",
|
|
1229
|
+
)
|
|
1230
|
+
|
|
1231
|
+
def _protected_dependencies(self) -> "list[params.Depends]":
|
|
1232
|
+
"""Dependencies the (protected) admin router is included with (SDD B.3).
|
|
1233
|
+
|
|
1234
|
+
In bridge mode the host's ``get_user``, through ``build_admin_dependency``,
|
|
1235
|
+
guards every admin route. With sidebar pins on, their loader runs after it,
|
|
1236
|
+
once the request has a ``user_key``.
|
|
1237
|
+
"""
|
|
1238
|
+
dependencies: list[params.Depends] = []
|
|
1239
|
+
if self.auth is not None:
|
|
1240
|
+
from hyperadmin.auth.bridge import build_admin_dependency
|
|
1241
|
+
|
|
1242
|
+
dependencies.append(Depends(build_admin_dependency(self.auth)))
|
|
1243
|
+
if self._nav_pins is not None:
|
|
1244
|
+
dependencies.append(Depends(self._nav_pins.load))
|
|
1245
|
+
return dependencies
|
|
1246
|
+
|
|
1247
|
+
def _register_nav_pins(self) -> None:
|
|
1248
|
+
"""Mount the sidebar pins (st-v059-nav-03) when auth gives requests a ``user_key``."""
|
|
1249
|
+
if self._auth_mode is None:
|
|
1250
|
+
return
|
|
1251
|
+
from hyperadmin.navigation.pins import NavPinService
|
|
1252
|
+
from hyperadmin.views.nav_pins import NavPins
|
|
1253
|
+
|
|
1254
|
+
service = NavPinService(
|
|
1255
|
+
self.engine,
|
|
1256
|
+
session_factory=self.session_factory,
|
|
1257
|
+
max_pins=self.settings.nav_pins_max,
|
|
1258
|
+
)
|
|
1259
|
+
self._nav_pins = NavPins(service, self.templates)
|
|
1260
|
+
self._nav_pins.register(self.router)
|
|
1261
|
+
|
|
1262
|
+
def _build_csrf_guard(self) -> "CsrfGuard | None":
|
|
1263
|
+
"""Build the CSRF check and its template globals; ``None`` when CSRF is off."""
|
|
1264
|
+
from hyperadmin.views.csrf import CsrfGuard, install_csrf_globals
|
|
1265
|
+
|
|
1266
|
+
mode = self.csrf_mode
|
|
1267
|
+
if mode == "off":
|
|
1268
|
+
return None
|
|
1269
|
+
settings = self.settings
|
|
1270
|
+
install_csrf_globals(
|
|
1271
|
+
self.templates.env,
|
|
1272
|
+
field_name=settings.csrf_field_name,
|
|
1273
|
+
header_name=settings.csrf_header_name,
|
|
1274
|
+
)
|
|
1275
|
+
# Only the count: the settings object also carries secret_key, and an Origin
|
|
1276
|
+
# rejection already logs the offending origin together with csrf_trusted_origins.
|
|
1277
|
+
logger.info(
|
|
1278
|
+
"HyperAdmin CSRF %s; %d trusted origin(s) beyond the request host",
|
|
1279
|
+
mode,
|
|
1280
|
+
len(settings.csrf_trusted_origins),
|
|
1281
|
+
)
|
|
1282
|
+
return CsrfGuard(
|
|
1283
|
+
settings.secret_key,
|
|
1284
|
+
mode=mode,
|
|
1285
|
+
cookie_name=settings.csrf_cookie_name,
|
|
1286
|
+
header_name=settings.csrf_header_name,
|
|
1287
|
+
field_name=settings.csrf_field_name,
|
|
1288
|
+
trusted_origins=settings.csrf_trusted_origins,
|
|
1289
|
+
cookie_secure=settings.cookie_secure,
|
|
1290
|
+
)
|
|
1291
|
+
|
|
1292
|
+
def mount(self, path: str = "/admin") -> None:
|
|
1293
|
+
"""Mount the admin interface on the host FastAPI application.
|
|
1294
|
+
|
|
1295
|
+
By default (``settings.mount_mode == "isolated"``) the admin is built as a
|
|
1296
|
+
private ``FastAPI`` sub-application, without OpenAPI or docs, and attached
|
|
1297
|
+
with ``app.mount(path, sub_app, name=settings.route_namespace)`` (SDD C.1):
|
|
1298
|
+
|
|
1299
|
+
- its middleware (locale, session, authentication, the startup guard)
|
|
1300
|
+
wraps admin requests only;
|
|
1301
|
+
- its static files and realtime WebSocket live under ``path``;
|
|
1302
|
+
- its route names are namespaced, e.g. ``hyperadmin:user-list``;
|
|
1303
|
+
- it shares the host's ``dependency_overrides`` and ``state``.
|
|
1304
|
+
|
|
1305
|
+
``mount_mode="router"`` (deprecated) and ``mount("/")`` keep the legacy
|
|
1306
|
+
``include_router`` behaviour.
|
|
1307
|
+
"""
|
|
1308
|
+
admin_prefix = path.rstrip("/")
|
|
1309
|
+
isolated = self._resolve_mount_mode(admin_prefix)
|
|
1310
|
+
|
|
1311
|
+
from hyperadmin.core.registry import site
|
|
1312
|
+
|
|
1313
|
+
# Plugins hear about every model from here on, and once about those
|
|
1314
|
+
# registered earlier (``on_model_register``).
|
|
1315
|
+
site.attach_hook_dispatcher(self.dispatch_hook)
|
|
1316
|
+
|
|
1317
|
+
# Every admin route uses HyperAdminRoute (SDD B.2): 403/404/409 render inside
|
|
1318
|
+
# the admin layout for people (JSON stays for API callers), and it is the one
|
|
1319
|
+
# place for the auth-error translation, token-cookie bridge and CSRF hook.
|
|
1320
|
+
# Set before any route is added to the admin router.
|
|
1321
|
+
self.router.route_class = self._make_route_class()
|
|
1322
|
+
self.public_router.route_class = self.router.route_class
|
|
1323
|
+
|
|
1324
|
+
if self.storage and self.settings.public_uploads_path:
|
|
1325
|
+
self._mount_public_uploads(self.settings.public_uploads_path)
|
|
1326
|
+
|
|
1327
|
+
if self.auth_backend:
|
|
1328
|
+
self._register_auth_routes(path)
|
|
1329
|
+
if self.oauth_backend is not None:
|
|
1330
|
+
from hyperadmin.auth.oauth import wiring as oauth_wiring
|
|
1331
|
+
|
|
1332
|
+
oauth_wiring.register_routes(self, path)
|
|
1333
|
+
if self.auth is not None:
|
|
1334
|
+
self._register_bridge_routes(path, self.auth)
|
|
1335
|
+
if self._should_register_auth_models():
|
|
1336
|
+
self._register_auth_models()
|
|
1337
|
+
|
|
1338
|
+
if self.settings.auto_discover:
|
|
1339
|
+
self._auto_register_models()
|
|
1340
|
+
|
|
1341
|
+
self._register_locale_route(path)
|
|
1342
|
+
self._register_realtime_routes()
|
|
1343
|
+
self._register_views()
|
|
1344
|
+
self._apply_plugins()
|
|
1345
|
+
self._register_nav_pins()
|
|
1346
|
+
self.templates.env.globals["admin_prefix"] = admin_prefix
|
|
1347
|
+
# Per-request override of the static global (SDD C.1): under a host
|
|
1348
|
+
# root_path, "{{ admin_prefix }}/..." links must carry it too.
|
|
1349
|
+
from hyperadmin.views.urls import admin_prefix_context
|
|
1350
|
+
|
|
1351
|
+
if admin_prefix_context not in self.templates.context_processors:
|
|
1352
|
+
self.templates.context_processors.append(admin_prefix_context)
|
|
1353
|
+
self.templates.env.globals["auth_enabled"] = self._auth_mode is not None
|
|
1354
|
+
self.templates.env.globals["auth_mode"] = self._auth_mode
|
|
1355
|
+
self.templates.env.globals["logout_url"] = (
|
|
1356
|
+
self.auth.logout_url if self.auth is not None else None
|
|
1357
|
+
)
|
|
1358
|
+
self.templates.env.globals["realtime_enabled"] = self.realtime is not None
|
|
1359
|
+
self.templates.env.globals["realtime_notification_models"] = (
|
|
1360
|
+
self._notification_model_labels()
|
|
1361
|
+
)
|
|
1362
|
+
self.templates.env.globals["theme"] = self.settings.theme
|
|
1363
|
+
self.templates.env.globals["theme_preset"] = self.settings.theme_preset
|
|
1364
|
+
self.templates.env.globals["site_title"] = self.settings.site_title
|
|
1365
|
+
self.templates.env.globals["site_header"] = self.settings.site_header
|
|
1366
|
+
self.templates.env.globals["supported_locales"] = self.settings.supported_locales
|
|
1367
|
+
from hyperadmin.i18n import RTL_LOCALES
|
|
1368
|
+
|
|
1369
|
+
self.templates.env.globals["rtl_locales"] = RTL_LOCALES
|
|
1370
|
+
|
|
1371
|
+
if isolated:
|
|
1372
|
+
self._mount_isolated(admin_prefix)
|
|
1373
|
+
else:
|
|
1374
|
+
self._mount_router(admin_prefix)
|
|
1375
|
+
|
|
1376
|
+
def _mount_isolated(self, admin_prefix: str) -> None:
|
|
1377
|
+
"""Build the private admin sub-app and attach it under ``admin_prefix`` (SDD C.1)."""
|
|
1378
|
+
from hyperadmin.views.urls import AdminScopeMiddleware
|
|
1379
|
+
|
|
1380
|
+
sub_app = FastAPI(openapi_url=None, docs_url=None, redoc_url=None)
|
|
1381
|
+
# Shared, not copied: host test overrides and dependencies that read
|
|
1382
|
+
# request.app.state keep working under the admin prefix.
|
|
1383
|
+
sub_app.dependency_overrides = self.app.dependency_overrides
|
|
1384
|
+
sub_app.state = self.app.state
|
|
1385
|
+
mount_plugin_static(sub_app, self.plugins)
|
|
1386
|
+
sub_app.mount("/static", StaticFiles(directory=_STATIC_DIR), name="static")
|
|
1387
|
+
sub_app.include_router(
|
|
1388
|
+
self.router, tags=["HyperAdmin"], dependencies=self._protected_dependencies()
|
|
1389
|
+
)
|
|
1390
|
+
sub_app.include_router(self.public_router, tags=["HyperAdmin"])
|
|
1391
|
+
|
|
1392
|
+
# add_middleware prepends, so the last one added runs first:
|
|
1393
|
+
# StartupGuard -> AdminScope -> Session -> Authentication -> Locale -> routes.
|
|
1394
|
+
self._add_locale_middleware(sub_app)
|
|
1395
|
+
if self.auth_backend:
|
|
1396
|
+
self._add_auth_middleware(sub_app, admin_prefix, isolated=True)
|
|
1397
|
+
sub_app.add_middleware(AdminScopeMiddleware, namespace=self.settings.route_namespace)
|
|
1398
|
+
# Every sub-app request is an admin request, hence the "/" prefix.
|
|
1399
|
+
sub_app.add_middleware(StartupGuardMiddleware, lifecycle=self._lifecycle, admin_prefix="/")
|
|
1400
|
+
self._add_rate_limit_middleware(sub_app, "/")
|
|
1401
|
+
|
|
1402
|
+
self.app.mount(admin_prefix, sub_app, name=self.settings.route_namespace)
|
|
1403
|
+
self._asgi_app = sub_app
|
|
1404
|
+
|
|
1405
|
+
def _mount_router(self, admin_prefix: str) -> None:
|
|
1406
|
+
"""Legacy router mode: admin routes and middleware live on the host app."""
|
|
1407
|
+
from hyperadmin.views.urls import AdminScopeMiddleware
|
|
1408
|
+
|
|
1409
|
+
mount_plugin_static(self.app, self.plugins)
|
|
1410
|
+
self.app.mount("/static", StaticFiles(directory=_STATIC_DIR), name="static")
|
|
1411
|
+
self.app.include_router(
|
|
1412
|
+
self.router,
|
|
1413
|
+
prefix=admin_prefix,
|
|
1414
|
+
tags=["HyperAdmin"],
|
|
1415
|
+
dependencies=self._protected_dependencies(),
|
|
1416
|
+
)
|
|
1417
|
+
self.app.include_router(self.public_router, prefix=admin_prefix, tags=["HyperAdmin"])
|
|
1418
|
+
|
|
1419
|
+
# LocaleMiddleware runs whether or not auth is configured. It must be
|
|
1420
|
+
# added before the auth middleware so the chain is
|
|
1421
|
+
# SessionMiddleware -> AuthenticationMiddleware -> LocaleMiddleware -> routes.
|
|
1422
|
+
self._add_locale_middleware(self.app)
|
|
1423
|
+
|
|
1424
|
+
if self.auth_backend:
|
|
1425
|
+
self._add_auth_middleware(self.app, admin_prefix, isolated=False)
|
|
1426
|
+
|
|
1427
|
+
self.app.add_middleware(AdminScopeMiddleware, namespace=None, prefix=admin_prefix)
|
|
1428
|
+
# Added last so it is outermost (SDD C.2): the safety net must run before
|
|
1429
|
+
# Session/Auth/Locale, so a permission sync it triggers is visible to this
|
|
1430
|
+
# same request's own permission checks. One mechanism now, not two — there
|
|
1431
|
+
# is no more ``router.on_startup`` append here (Starlette silently ignores
|
|
1432
|
+
# on_startup/on_shutdown handlers once a host passes its own ``lifespan=``,
|
|
1433
|
+
# and a mounted sub-app never receives lifespan events at all).
|
|
1434
|
+
self.app.add_middleware(
|
|
1435
|
+
StartupGuardMiddleware, lifecycle=self._lifecycle, admin_prefix=admin_prefix
|
|
1436
|
+
)
|
|
1437
|
+
self._add_rate_limit_middleware(self.app, admin_prefix)
|