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.
Files changed (442) hide show
  1. hyper_admin-1.0.0.dist-info/METADATA +366 -0
  2. hyper_admin-1.0.0.dist-info/RECORD +442 -0
  3. hyper_admin-1.0.0.dist-info/WHEEL +4 -0
  4. hyper_admin-1.0.0.dist-info/entry_points.txt +2 -0
  5. hyper_admin-1.0.0.dist-info/licenses/LICENSE +21 -0
  6. hyperadmin/__init__.py +52 -0
  7. hyperadmin/__main__.py +21 -0
  8. hyperadmin/adapters/__init__.py +28 -0
  9. hyperadmin/adapters/_estimate.py +33 -0
  10. hyperadmin/adapters/_filter_clause.py +9 -0
  11. hyperadmin/adapters/_occ.py +44 -0
  12. hyperadmin/adapters/_relation_loading.py +23 -0
  13. hyperadmin/adapters/_search.py +84 -0
  14. hyperadmin/adapters/filtering.py +86 -0
  15. hyperadmin/adapters/introspection.py +239 -0
  16. hyperadmin/adapters/registry.py +37 -0
  17. hyperadmin/adapters/schema.py +239 -0
  18. hyperadmin/adapters/sqlalchemy.py +423 -0
  19. hyperadmin/adapters/sqlmodel.py +650 -0
  20. hyperadmin/auth/__init__.py +156 -0
  21. hyperadmin/auth/_types.py +52 -0
  22. hyperadmin/auth/backend.py +37 -0
  23. hyperadmin/auth/bridge.py +351 -0
  24. hyperadmin/auth/exceptions.py +124 -0
  25. hyperadmin/auth/middleware.py +287 -0
  26. hyperadmin/auth/models.py +245 -0
  27. hyperadmin/auth/oauth/__init__.py +81 -0
  28. hyperadmin/auth/oauth/backend.py +611 -0
  29. hyperadmin/auth/oauth/providers.py +214 -0
  30. hyperadmin/auth/oauth/refresh.py +126 -0
  31. hyperadmin/auth/oauth/session.py +96 -0
  32. hyperadmin/auth/oauth/tokens.py +114 -0
  33. hyperadmin/auth/oauth/views.py +306 -0
  34. hyperadmin/auth/oauth/wiring.py +131 -0
  35. hyperadmin/auth/otp.py +189 -0
  36. hyperadmin/auth/permissions.py +232 -0
  37. hyperadmin/auth/session.py +81 -0
  38. hyperadmin/auth/session_middleware.py +164 -0
  39. hyperadmin/auth/token_handoff.py +452 -0
  40. hyperadmin/auth/user_cache.py +222 -0
  41. hyperadmin/auth/views.py +581 -0
  42. hyperadmin/core/__init__.py +76 -0
  43. hyperadmin/core/actions.py +151 -0
  44. hyperadmin/core/adapters.py +883 -0
  45. hyperadmin/core/app.py +1437 -0
  46. hyperadmin/core/auth.py +97 -0
  47. hyperadmin/core/bulk_results.py +28 -0
  48. hyperadmin/core/cache.py +68 -0
  49. hyperadmin/core/choices.py +38 -0
  50. hyperadmin/core/concurrency.py +107 -0
  51. hyperadmin/core/csrf.py +108 -0
  52. hyperadmin/core/discovery.py +161 -0
  53. hyperadmin/core/display.py +172 -0
  54. hyperadmin/core/fields.py +158 -0
  55. hyperadmin/core/fieldsets.py +22 -0
  56. hyperadmin/core/filtering.py +403 -0
  57. hyperadmin/core/filters_compat.py +78 -0
  58. hyperadmin/core/inlines.py +64 -0
  59. hyperadmin/core/introspection.py +280 -0
  60. hyperadmin/core/layouts.py +17 -0
  61. hyperadmin/core/lifecycle.py +278 -0
  62. hyperadmin/core/model.py +189 -0
  63. hyperadmin/core/navigation.py +354 -0
  64. hyperadmin/core/options.py +391 -0
  65. hyperadmin/core/palette.py +94 -0
  66. hyperadmin/core/panels.py +227 -0
  67. hyperadmin/core/plugin_wiring.py +205 -0
  68. hyperadmin/core/plugins.py +588 -0
  69. hyperadmin/core/primary_key.py +118 -0
  70. hyperadmin/core/rate_limit.py +90 -0
  71. hyperadmin/core/registry.py +129 -0
  72. hyperadmin/core/relation_loading.py +25 -0
  73. hyperadmin/core/schema.py +83 -0
  74. hyperadmin/core/sensitive.py +134 -0
  75. hyperadmin/core/settings.py +377 -0
  76. hyperadmin/core/storage_paths.py +54 -0
  77. hyperadmin/core/timezones.py +137 -0
  78. hyperadmin/core/uploads.py +16 -0
  79. hyperadmin/db.py +160 -0
  80. hyperadmin/discover.py +54 -0
  81. hyperadmin/filters/__init__.py +39 -0
  82. hyperadmin/filters/base.py +246 -0
  83. hyperadmin/filters/boolean.py +105 -0
  84. hyperadmin/filters/choice.py +74 -0
  85. hyperadmin/filters/date.py +265 -0
  86. hyperadmin/filters/relation.py +69 -0
  87. hyperadmin/filters/saved_views.py +203 -0
  88. hyperadmin/i18n/__init__.py +50 -0
  89. hyperadmin/i18n/loader.py +150 -0
  90. hyperadmin/i18n/middleware.py +159 -0
  91. hyperadmin/i18n/validation_messages.py +264 -0
  92. hyperadmin/loadtest/__init__.py +28 -0
  93. hyperadmin/loadtest/batch.py +263 -0
  94. hyperadmin/loadtest/checkpoint.py +168 -0
  95. hyperadmin/loadtest/generators/__init__.py +29 -0
  96. hyperadmin/loadtest/generators/auth.py +86 -0
  97. hyperadmin/loadtest/generators/erp.py +177 -0
  98. hyperadmin/loadtest/plan.py +189 -0
  99. hyperadmin/loadtest/pool.py +113 -0
  100. hyperadmin/loadtest/progress.py +150 -0
  101. hyperadmin/locale/ar/LC_MESSAGES/messages.mo +0 -0
  102. hyperadmin/locale/ar/LC_MESSAGES/messages.po +2139 -0
  103. hyperadmin/locale/de/LC_MESSAGES/messages.mo +0 -0
  104. hyperadmin/locale/de/LC_MESSAGES/messages.po +2114 -0
  105. hyperadmin/locale/en/LC_MESSAGES/messages.mo +0 -0
  106. hyperadmin/locale/en/LC_MESSAGES/messages.po +1780 -0
  107. hyperadmin/locale/es/LC_MESSAGES/messages.mo +0 -0
  108. hyperadmin/locale/es/LC_MESSAGES/messages.po +2094 -0
  109. hyperadmin/locale/fr/LC_MESSAGES/messages.mo +0 -0
  110. hyperadmin/locale/fr/LC_MESSAGES/messages.po +2100 -0
  111. hyperadmin/locale/he/LC_MESSAGES/messages.mo +0 -0
  112. hyperadmin/locale/he/LC_MESSAGES/messages.po +2076 -0
  113. hyperadmin/locale/hi/LC_MESSAGES/messages.mo +0 -0
  114. hyperadmin/locale/hi/LC_MESSAGES/messages.po +2084 -0
  115. hyperadmin/locale/id/LC_MESSAGES/messages.mo +0 -0
  116. hyperadmin/locale/id/LC_MESSAGES/messages.po +2071 -0
  117. hyperadmin/locale/it/LC_MESSAGES/messages.mo +0 -0
  118. hyperadmin/locale/it/LC_MESSAGES/messages.po +2098 -0
  119. hyperadmin/locale/ja/LC_MESSAGES/messages.mo +0 -0
  120. hyperadmin/locale/ja/LC_MESSAGES/messages.po +2049 -0
  121. hyperadmin/locale/ko/LC_MESSAGES/messages.mo +0 -0
  122. hyperadmin/locale/ko/LC_MESSAGES/messages.po +2049 -0
  123. hyperadmin/locale/nl/LC_MESSAGES/messages.mo +0 -0
  124. hyperadmin/locale/nl/LC_MESSAGES/messages.po +2100 -0
  125. hyperadmin/locale/pl/LC_MESSAGES/messages.mo +0 -0
  126. hyperadmin/locale/pl/LC_MESSAGES/messages.po +2112 -0
  127. hyperadmin/locale/pt_BR/LC_MESSAGES/messages.mo +0 -0
  128. hyperadmin/locale/pt_BR/LC_MESSAGES/messages.po +2098 -0
  129. hyperadmin/locale/ru/LC_MESSAGES/messages.mo +0 -0
  130. hyperadmin/locale/ru/LC_MESSAGES/messages.po +2112 -0
  131. hyperadmin/locale/th/LC_MESSAGES/messages.mo +0 -0
  132. hyperadmin/locale/th/LC_MESSAGES/messages.po +2065 -0
  133. hyperadmin/locale/tr/LC_MESSAGES/messages.mo +0 -0
  134. hyperadmin/locale/tr/LC_MESSAGES/messages.po +2084 -0
  135. hyperadmin/locale/uk/LC_MESSAGES/messages.mo +0 -0
  136. hyperadmin/locale/uk/LC_MESSAGES/messages.po +1889 -0
  137. hyperadmin/locale/vi/LC_MESSAGES/messages.mo +0 -0
  138. hyperadmin/locale/vi/LC_MESSAGES/messages.po +2063 -0
  139. hyperadmin/locale/zh_CN/LC_MESSAGES/messages.mo +0 -0
  140. hyperadmin/locale/zh_CN/LC_MESSAGES/messages.po +2049 -0
  141. hyperadmin/main.py +3 -0
  142. hyperadmin/management/__init__.py +0 -0
  143. hyperadmin/management/commands/__init__.py +0 -0
  144. hyperadmin/management/commands/createsuperuser.py +114 -0
  145. hyperadmin/management/commands/initdb.py +76 -0
  146. hyperadmin/management/commands/plugins.py +31 -0
  147. hyperadmin/management/commands/seed.py +125 -0
  148. hyperadmin/navigation/__init__.py +9 -0
  149. hyperadmin/navigation/pins.py +153 -0
  150. hyperadmin/panels/__init__.py +10 -0
  151. hyperadmin/panels/pdf.py +151 -0
  152. hyperadmin/permissions/__init__.py +59 -0
  153. hyperadmin/permissions/audit.py +109 -0
  154. hyperadmin/permissions/matrix.py +343 -0
  155. hyperadmin/permissions/object_rules.py +143 -0
  156. hyperadmin/realtime/__init__.py +51 -0
  157. hyperadmin/realtime/_debug.py +77 -0
  158. hyperadmin/realtime/config.py +124 -0
  159. hyperadmin/realtime/emitting.py +143 -0
  160. hyperadmin/realtime/events.py +107 -0
  161. hyperadmin/realtime/presence.py +193 -0
  162. hyperadmin/realtime/presence_redis.py +142 -0
  163. hyperadmin/realtime/pubsub.py +129 -0
  164. hyperadmin/realtime/pubsub_redis.py +159 -0
  165. hyperadmin/realtime/registry.py +102 -0
  166. hyperadmin/realtime/sse.py +82 -0
  167. hyperadmin/realtime/ws.py +477 -0
  168. hyperadmin/routing.py +680 -0
  169. hyperadmin/static/css/_accessibility.css +149 -0
  170. hyperadmin/static/css/_alerts.css +147 -0
  171. hyperadmin/static/css/_autocomplete.css +39 -0
  172. hyperadmin/static/css/_banner.css +118 -0
  173. hyperadmin/static/css/_buttons.css +241 -0
  174. hyperadmin/static/css/_card.css +86 -0
  175. hyperadmin/static/css/_dark-mode.css +232 -0
  176. hyperadmin/static/css/_fieldsets.css +71 -0
  177. hyperadmin/static/css/_filter.css +203 -0
  178. hyperadmin/static/css/_fonts.css +25 -0
  179. hyperadmin/static/css/_forms.css +862 -0
  180. hyperadmin/static/css/_inline-cell.css +222 -0
  181. hyperadmin/static/css/_inlines.css +160 -0
  182. hyperadmin/static/css/_layout.css +62 -0
  183. hyperadmin/static/css/_login.css +112 -0
  184. hyperadmin/static/css/_menu.css +156 -0
  185. hyperadmin/static/css/_navbar.css +299 -0
  186. hyperadmin/static/css/_page-header.css +139 -0
  187. hyperadmin/static/css/_pagination.css +125 -0
  188. hyperadmin/static/css/_palette.css +304 -0
  189. hyperadmin/static/css/_panels.css +174 -0
  190. hyperadmin/static/css/_permissions.css +547 -0
  191. hyperadmin/static/css/_pill.css +123 -0
  192. hyperadmin/static/css/_popover.css +170 -0
  193. hyperadmin/static/css/_popup.css +65 -0
  194. hyperadmin/static/css/_progress.css +161 -0
  195. hyperadmin/static/css/_realtime.css +78 -0
  196. hyperadmin/static/css/_reset.css +48 -0
  197. hyperadmin/static/css/_responsive.css +51 -0
  198. hyperadmin/static/css/_rtl.css +23 -0
  199. hyperadmin/static/css/_search.css +67 -0
  200. hyperadmin/static/css/_seg.css +95 -0
  201. hyperadmin/static/css/_sidebar.css +446 -0
  202. hyperadmin/static/css/_sticky.css +54 -0
  203. hyperadmin/static/css/_table.css +776 -0
  204. hyperadmin/static/css/_theme-terminal-type.css +92 -0
  205. hyperadmin/static/css/_theme-terminal.css +330 -0
  206. hyperadmin/static/css/_theme-toggle.css +46 -0
  207. hyperadmin/static/css/_tokens.css +232 -0
  208. hyperadmin/static/css/_utilities.css +133 -0
  209. hyperadmin/static/css/hyperadmin.css +58 -0
  210. hyperadmin/static/fonts/Inter-OFL.txt +93 -0
  211. hyperadmin/static/fonts/InterVariable.woff2 +0 -0
  212. hyperadmin/static/fonts/JetBrainsMono-OFL.txt +93 -0
  213. hyperadmin/static/fonts/JetBrainsMonoVariable.woff2 +0 -0
  214. hyperadmin/static/icons/arrow-down.svg +1 -0
  215. hyperadmin/static/icons/arrow-up.svg +1 -0
  216. hyperadmin/static/icons/bar-chart-3.svg +1 -0
  217. hyperadmin/static/icons/bell.svg +1 -0
  218. hyperadmin/static/icons/bookmark.svg +1 -0
  219. hyperadmin/static/icons/briefcase.svg +1 -0
  220. hyperadmin/static/icons/building-2.svg +1 -0
  221. hyperadmin/static/icons/calendar.svg +1 -0
  222. hyperadmin/static/icons/check.svg +1 -0
  223. hyperadmin/static/icons/chevron-down.svg +1 -0
  224. hyperadmin/static/icons/chevron-left.svg +1 -0
  225. hyperadmin/static/icons/chevron-right.svg +1 -0
  226. hyperadmin/static/icons/circle-check.svg +1 -0
  227. hyperadmin/static/icons/circle-help.svg +1 -0
  228. hyperadmin/static/icons/circle-x.svg +1 -0
  229. hyperadmin/static/icons/clock.svg +1 -0
  230. hyperadmin/static/icons/columns-3.svg +1 -0
  231. hyperadmin/static/icons/command.svg +1 -0
  232. hyperadmin/static/icons/copy.svg +1 -0
  233. hyperadmin/static/icons/credit-card.svg +1 -0
  234. hyperadmin/static/icons/database.svg +1 -0
  235. hyperadmin/static/icons/download.svg +1 -0
  236. hyperadmin/static/icons/ellipsis.svg +1 -0
  237. hyperadmin/static/icons/external-link.svg +1 -0
  238. hyperadmin/static/icons/eye.svg +1 -0
  239. hyperadmin/static/icons/file-text.svg +1 -0
  240. hyperadmin/static/icons/filter.svg +1 -0
  241. hyperadmin/static/icons/folder.svg +1 -0
  242. hyperadmin/static/icons/globe.svg +1 -0
  243. hyperadmin/static/icons/history.svg +1 -0
  244. hyperadmin/static/icons/home.svg +1 -0
  245. hyperadmin/static/icons/image.svg +1 -0
  246. hyperadmin/static/icons/info.svg +1 -0
  247. hyperadmin/static/icons/key-round.svg +1 -0
  248. hyperadmin/static/icons/layers.svg +1 -0
  249. hyperadmin/static/icons/layout-grid.svg +1 -0
  250. hyperadmin/static/icons/list-checks.svg +1 -0
  251. hyperadmin/static/icons/lock.svg +1 -0
  252. hyperadmin/static/icons/log-out.svg +1 -0
  253. hyperadmin/static/icons/mail.svg +1 -0
  254. hyperadmin/static/icons/map-pin.svg +1 -0
  255. hyperadmin/static/icons/menu.svg +1 -0
  256. hyperadmin/static/icons/moon.svg +1 -0
  257. hyperadmin/static/icons/package.svg +1 -0
  258. hyperadmin/static/icons/panel-left-close.svg +1 -0
  259. hyperadmin/static/icons/panel-left-open.svg +1 -0
  260. hyperadmin/static/icons/pencil.svg +1 -0
  261. hyperadmin/static/icons/pin-off.svg +1 -0
  262. hyperadmin/static/icons/pin.svg +1 -0
  263. hyperadmin/static/icons/plus.svg +1 -0
  264. hyperadmin/static/icons/receipt.svg +1 -0
  265. hyperadmin/static/icons/refresh-cw.svg +1 -0
  266. hyperadmin/static/icons/rotate-ccw.svg +1 -0
  267. hyperadmin/static/icons/search.svg +1 -0
  268. hyperadmin/static/icons/settings.svg +1 -0
  269. hyperadmin/static/icons/shield-check.svg +1 -0
  270. hyperadmin/static/icons/shopping-cart.svg +1 -0
  271. hyperadmin/static/icons/sliders-horizontal.svg +1 -0
  272. hyperadmin/static/icons/sparkles.svg +1 -0
  273. hyperadmin/static/icons/store.svg +1 -0
  274. hyperadmin/static/icons/sun.svg +1 -0
  275. hyperadmin/static/icons/tag.svg +1 -0
  276. hyperadmin/static/icons/trash-2.svg +1 -0
  277. hyperadmin/static/icons/triangle-alert.svg +1 -0
  278. hyperadmin/static/icons/truck.svg +1 -0
  279. hyperadmin/static/icons/upload.svg +1 -0
  280. hyperadmin/static/icons/user.svg +1 -0
  281. hyperadmin/static/icons/users.svg +1 -0
  282. hyperadmin/static/icons/wallet.svg +1 -0
  283. hyperadmin/static/icons/x.svg +1 -0
  284. hyperadmin/static/img/hyperadmin-favicon.svg +1 -0
  285. hyperadmin/static/img/hyperadmin-mark-mono.svg +1 -0
  286. hyperadmin/static/img/hyperadmin-mark.svg +1 -0
  287. hyperadmin/static/img/hyperadmin-wordmark-dark.svg +1 -0
  288. hyperadmin/static/img/hyperadmin-wordmark.svg +1 -0
  289. hyperadmin/static/img/terminal/hyperadmin-favicon-16.svg +1 -0
  290. hyperadmin/static/img/terminal/hyperadmin-favicon.svg +1 -0
  291. hyperadmin/static/img/terminal/hyperadmin-mark.svg +1 -0
  292. hyperadmin/static/img/terminal/hyperadmin-wordmark-dark.svg +1 -0
  293. hyperadmin/static/img/terminal/hyperadmin-wordmark.svg +1 -0
  294. hyperadmin/static/js/autocomplete.js +475 -0
  295. hyperadmin/static/js/confirm_delete.js +113 -0
  296. hyperadmin/static/js/error_summary.js +37 -0
  297. hyperadmin/static/js/form_guard.js +77 -0
  298. hyperadmin/static/js/inline_edit.js +97 -0
  299. hyperadmin/static/js/palette.js +292 -0
  300. hyperadmin/static/js/primitives.js +205 -0
  301. hyperadmin/static/js/realtime-status.js +515 -0
  302. hyperadmin/static/js/request_errors.js +85 -0
  303. hyperadmin/static/js/shortcuts.js +175 -0
  304. hyperadmin/static/js/sidebar.js +83 -0
  305. hyperadmin/static/js/vendor/LICENSE-alpinejs.txt +21 -0
  306. hyperadmin/static/js/vendor/LICENSE-htmx.txt +25 -0
  307. hyperadmin/static/js/vendor/alpinejs-3.17.4.min.js +21 -0
  308. hyperadmin/static/js/vendor/alpinejs-focus-3.17.4.min.js +18 -0
  309. hyperadmin/static/js/vendor/htmx-1.9.10.min.js +1 -0
  310. hyperadmin/templates/_base.html +161 -0
  311. hyperadmin/templates/_messages.html +11 -0
  312. hyperadmin/templates/_navbar.html +126 -0
  313. hyperadmin/templates/_sidebar.html +80 -0
  314. hyperadmin/templates/auth/mfa_challenge.html +75 -0
  315. hyperadmin/templates/auth/mfa_settings.html +110 -0
  316. hyperadmin/templates/auth/oauth_link_required.html +24 -0
  317. hyperadmin/templates/auth/oauth_settings.html +55 -0
  318. hyperadmin/templates/base.html +16 -0
  319. hyperadmin/templates/bulk_form.html +18 -0
  320. hyperadmin/templates/bulk_result.html +20 -0
  321. hyperadmin/templates/components/_icons.html +86 -0
  322. hyperadmin/templates/components/_macros.html +27 -0
  323. hyperadmin/templates/components/_nav.html +55 -0
  324. hyperadmin/templates/components/_row_access.html +26 -0
  325. hyperadmin/templates/components/banner.html +77 -0
  326. hyperadmin/templates/components/bulk_form.html +81 -0
  327. hyperadmin/templates/components/bulk_result.html +133 -0
  328. hyperadmin/templates/components/bulk_toolbar.html +63 -0
  329. hyperadmin/templates/components/command_palette.html +59 -0
  330. hyperadmin/templates/components/confirm_delete_dialog.html +26 -0
  331. hyperadmin/templates/components/conflict_dialog.html +42 -0
  332. hyperadmin/templates/components/csrf_reload_banner.html +20 -0
  333. hyperadmin/templates/components/error_summary.html +39 -0
  334. hyperadmin/templates/components/error_toast.html +18 -0
  335. hyperadmin/templates/components/fieldset.html +38 -0
  336. hyperadmin/templates/components/filter_bar.html +50 -0
  337. hyperadmin/templates/components/filter_sidebar.html +31 -0
  338. hyperadmin/templates/components/filters/boolean.html +10 -0
  339. hyperadmin/templates/components/filters/current_period.html +8 -0
  340. hyperadmin/templates/components/filters/date_range.html +26 -0
  341. hyperadmin/templates/components/filters/is_owner.html +8 -0
  342. hyperadmin/templates/components/filters/multi_choice.html +10 -0
  343. hyperadmin/templates/components/filters/multi_relation.html +20 -0
  344. hyperadmin/templates/components/filters/select.html +11 -0
  345. hyperadmin/templates/components/inline_cell.html +23 -0
  346. hyperadmin/templates/components/inline_cell_error.html +51 -0
  347. hyperadmin/templates/components/inline_cell_stale.html +20 -0
  348. hyperadmin/templates/components/inline_editor.html +85 -0
  349. hyperadmin/templates/components/inline_formset.html +34 -0
  350. hyperadmin/templates/components/inline_row.html +49 -0
  351. hyperadmin/templates/components/list_error.html +12 -0
  352. hyperadmin/templates/components/menu.html +74 -0
  353. hyperadmin/templates/components/nav_pinned.html +24 -0
  354. hyperadmin/templates/components/pagination.html +87 -0
  355. hyperadmin/templates/components/panel_document.html +19 -0
  356. hyperadmin/templates/components/panel_states.html +35 -0
  357. hyperadmin/templates/components/panel_tab_strip.html +31 -0
  358. hyperadmin/templates/components/pill.html +15 -0
  359. hyperadmin/templates/components/popover.html +59 -0
  360. hyperadmin/templates/components/presence_banner.html +28 -0
  361. hyperadmin/templates/components/progress.html +72 -0
  362. hyperadmin/templates/components/saved_views.html +61 -0
  363. hyperadmin/templates/components/search_input.html +19 -0
  364. hyperadmin/templates/components/seg.html +38 -0
  365. hyperadmin/templates/components/shortcuts_overlay.html +45 -0
  366. hyperadmin/templates/components/sortable_header.html +23 -0
  367. hyperadmin/templates/components/table.html +45 -0
  368. hyperadmin/templates/components/table_body.html +86 -0
  369. hyperadmin/templates/components/thumbnail.html +8 -0
  370. hyperadmin/templates/components/toast.html +36 -0
  371. hyperadmin/templates/components/tooltip.html +20 -0
  372. hyperadmin/templates/create.html +43 -0
  373. hyperadmin/templates/dashboard.html +8 -0
  374. hyperadmin/templates/detail.html +120 -0
  375. hyperadmin/templates/detail_layout.html +15 -0
  376. hyperadmin/templates/error.html +24 -0
  377. hyperadmin/templates/form_layout.html +26 -0
  378. hyperadmin/templates/list.html +5 -0
  379. hyperadmin/templates/list_layout.html +105 -0
  380. hyperadmin/templates/login.html +79 -0
  381. hyperadmin/templates/permissions/_banner.html +55 -0
  382. hyperadmin/templates/permissions/_diff_row.html +6 -0
  383. hyperadmin/templates/permissions/_group_gone.html +16 -0
  384. hyperadmin/templates/permissions/_macros.html +22 -0
  385. hyperadmin/templates/permissions/matrix.html +408 -0
  386. hyperadmin/templates/permissions/object_popover.html +95 -0
  387. hyperadmin/templates/update.html +69 -0
  388. hyperadmin/templates/widgets/autocomplete.html +100 -0
  389. hyperadmin/templates/widgets/checkbox_input.html +20 -0
  390. hyperadmin/templates/widgets/choices_options.html +3 -0
  391. hyperadmin/templates/widgets/date_input.html +13 -0
  392. hyperadmin/templates/widgets/datetime_input.html +18 -0
  393. hyperadmin/templates/widgets/encoded_textarea.html +4 -0
  394. hyperadmin/templates/widgets/file_input.html +15 -0
  395. hyperadmin/templates/widgets/float_input.html +12 -0
  396. hyperadmin/templates/widgets/image_input.html +108 -0
  397. hyperadmin/templates/widgets/multiselect_input.html +13 -0
  398. hyperadmin/templates/widgets/number_input.html +11 -0
  399. hyperadmin/templates/widgets/popup_form.html +64 -0
  400. hyperadmin/templates/widgets/relation_multiselect_input.html +36 -0
  401. hyperadmin/templates/widgets/relation_select_input.html +38 -0
  402. hyperadmin/templates/widgets/select_input.html +17 -0
  403. hyperadmin/templates/widgets/text_input.html +13 -0
  404. hyperadmin/templates/widgets/textarea.html +4 -0
  405. hyperadmin/uploads/__init__.py +44 -0
  406. hyperadmin/uploads/images.py +272 -0
  407. hyperadmin/uploads/storage.py +265 -0
  408. hyperadmin/uploads/validation.py +37 -0
  409. hyperadmin/views/__init__.py +3 -0
  410. hyperadmin/views/csrf.py +316 -0
  411. hyperadmin/views/dynamic/__init__.py +35 -0
  412. hyperadmin/views/dynamic/actions.py +264 -0
  413. hyperadmin/views/dynamic/base.py +576 -0
  414. hyperadmin/views/dynamic/concurrency.py +138 -0
  415. hyperadmin/views/dynamic/core.py +33 -0
  416. hyperadmin/views/dynamic/create.py +189 -0
  417. hyperadmin/views/dynamic/detail.py +231 -0
  418. hyperadmin/views/dynamic/files.py +233 -0
  419. hyperadmin/views/dynamic/form_data.py +162 -0
  420. hyperadmin/views/dynamic/helpers.py +151 -0
  421. hyperadmin/views/dynamic/inline.py +348 -0
  422. hyperadmin/views/dynamic/list_view.py +612 -0
  423. hyperadmin/views/dynamic/model_view.py +17 -0
  424. hyperadmin/views/dynamic/palette_search.py +78 -0
  425. hyperadmin/views/dynamic/relations.py +544 -0
  426. hyperadmin/views/dynamic/saved_views.py +159 -0
  427. hyperadmin/views/dynamic/update.py +313 -0
  428. hyperadmin/views/error_pages.py +46 -0
  429. hyperadmin/views/forms.py +1294 -0
  430. hyperadmin/views/htmx.py +53 -0
  431. hyperadmin/views/locale.py +113 -0
  432. hyperadmin/views/nav_pins.py +149 -0
  433. hyperadmin/views/navigation.py +143 -0
  434. hyperadmin/views/palette_context.py +91 -0
  435. hyperadmin/views/palette_search.py +103 -0
  436. hyperadmin/views/permissions_matrix.py +490 -0
  437. hyperadmin/views/rate_limit.py +87 -0
  438. hyperadmin/views/route.py +316 -0
  439. hyperadmin/views/static.py +138 -0
  440. hyperadmin/views/template_filters.py +305 -0
  441. hyperadmin/views/uploads.py +92 -0
  442. hyperadmin/views/urls.py +180 -0
@@ -0,0 +1,81 @@
1
+ """OAuth2/OIDC single sign-on for the built-in auth (``docs/specs/oauth-sso.md``).
2
+
3
+ Opt-in: nothing here is imported unless the host passes ``Admin(oauth_backend=...)``,
4
+ and the HTTP client and the token cipher need ``pip install 'hyper-admin[oauth]'``.
5
+
6
+ Exports are resolved lazily (PEP 562), so importing this package, its provider
7
+ configuration or its exceptions loads neither the ORM models nor the extra.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ if TYPE_CHECKING:
16
+ from hyperadmin.auth.exceptions import (
17
+ AccountLinkRequiredError,
18
+ MFARequiredError,
19
+ OAuthConfigError,
20
+ OAuthProviderError,
21
+ )
22
+ from hyperadmin.auth.oauth.backend import OAuthBackend, OAuthIdentity
23
+ from hyperadmin.auth.oauth.providers import (
24
+ OAuthProviderConfig,
25
+ github_provider,
26
+ google_provider,
27
+ )
28
+ from hyperadmin.auth.oauth.tokens import (
29
+ FernetTokenCipher,
30
+ configure_token_cipher,
31
+ token_cipher,
32
+ )
33
+
34
+ _BACKEND_MODULE = "hyperadmin.auth.oauth.backend"
35
+ _EXCEPTIONS_MODULE = "hyperadmin.auth.exceptions"
36
+ _PROVIDERS_MODULE = "hyperadmin.auth.oauth.providers"
37
+ _TOKENS_MODULE = "hyperadmin.auth.oauth.tokens"
38
+ _LAZY_EXPORTS: dict[str, str] = {
39
+ "OAuthBackend": _BACKEND_MODULE,
40
+ "OAuthIdentity": _BACKEND_MODULE,
41
+ "AccountLinkRequiredError": _EXCEPTIONS_MODULE,
42
+ "MFARequiredError": _EXCEPTIONS_MODULE,
43
+ "OAuthConfigError": _EXCEPTIONS_MODULE,
44
+ "OAuthProviderError": _EXCEPTIONS_MODULE,
45
+ "OAuthProviderConfig": _PROVIDERS_MODULE,
46
+ "github_provider": _PROVIDERS_MODULE,
47
+ "google_provider": _PROVIDERS_MODULE,
48
+ "FernetTokenCipher": _TOKENS_MODULE,
49
+ "configure_token_cipher": _TOKENS_MODULE,
50
+ "token_cipher": _TOKENS_MODULE,
51
+ }
52
+
53
+ __all__ = [
54
+ "AccountLinkRequiredError",
55
+ "FernetTokenCipher",
56
+ "MFARequiredError",
57
+ "OAuthBackend",
58
+ "OAuthConfigError",
59
+ "OAuthIdentity",
60
+ "OAuthProviderConfig",
61
+ "OAuthProviderError",
62
+ "configure_token_cipher",
63
+ "github_provider",
64
+ "google_provider",
65
+ "token_cipher",
66
+ ]
67
+
68
+
69
+ def __getattr__(name: str) -> Any:
70
+ """Resolve an export on first access and cache it on the module."""
71
+ module_name = _LAZY_EXPORTS.get(name)
72
+ if module_name is None:
73
+ msg = f"module {__name__!r} has no attribute {name!r}"
74
+ raise AttributeError(msg)
75
+ value = getattr(importlib.import_module(module_name), name)
76
+ globals()[name] = value
77
+ return value
78
+
79
+
80
+ def __dir__() -> list[str]:
81
+ return sorted({*globals(), *__all__})
@@ -0,0 +1,611 @@
1
+ """OAuth2/OIDC backend: provider calls, user provisioning and token storage.
2
+
3
+ :class:`OAuthBackend` holds the configured providers and does everything that is
4
+ not HTTP handling of the admin itself: it builds the authorization URL (PKCE
5
+ ``S256``), exchanges the code, reads userinfo, maps an identity to a ``User`` and
6
+ keeps the encrypted tokens fresh. The route handlers live in
7
+ ``hyperadmin.auth.oauth.views``; the session itself is still issued by the
8
+ ``auth_backend`` the ``Admin`` was built with. See ``docs/specs/oauth-sso.md``.
9
+
10
+ Needs ``pip install 'hyper-admin[oauth]'`` (``httpx-oauth``, ``cryptography``).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import asyncio
16
+ import base64
17
+ import hashlib
18
+ import logging
19
+ import re
20
+ import weakref
21
+ from dataclasses import dataclass
22
+ from datetime import datetime, timedelta, timezone
23
+ from typing import TYPE_CHECKING, Any
24
+
25
+ from sqlalchemy import func
26
+ from sqlalchemy.exc import IntegrityError
27
+ from sqlalchemy.orm import noload
28
+ from sqlmodel import col, select
29
+
30
+ from hyperadmin.auth.backend import make_unusable_password
31
+ from hyperadmin.auth.exceptions import (
32
+ AccountDisabledError,
33
+ AccountLinkRequiredError,
34
+ LastSignInMethodError,
35
+ OAuthConfigError,
36
+ OAuthProviderError,
37
+ OAuthSignupDisabledError,
38
+ )
39
+ from hyperadmin.auth.models import OAuthToken, User
40
+ from hyperadmin.core.adapters import open_session
41
+ from hyperadmin.core.timezones import utc_now
42
+
43
+ if TYPE_CHECKING:
44
+ from collections.abc import Callable, Mapping
45
+ from contextlib import AbstractAsyncContextManager
46
+
47
+ from hyperadmin.auth.oauth.providers import OAuthProviderConfig
48
+ from hyperadmin.core.adapters import AsyncSessionLike, SessionFactory
49
+
50
+ logger = logging.getLogger("hyperadmin")
51
+
52
+ _INSTALL_HINT = "Install the OAuth extra: pip install 'hyper-admin[oauth]'."
53
+ _USERNAME_UNSAFE = re.compile(r"[^A-Za-z0-9._-]")
54
+ _USERNAME_MAX = 50
55
+ _NAME_MAX = 50
56
+ _EMAIL_MAX = 100
57
+ _SERVER_ERROR = 500
58
+
59
+
60
+ @dataclass(frozen=True, slots=True)
61
+ class OAuthIdentity:
62
+ """Who the provider says signed in.
63
+
64
+ Attributes:
65
+ provider: Name of the provider.
66
+ sub: The provider's stable id of the user, as a string.
67
+ email: The user's email address.
68
+ claims: The raw userinfo document.
69
+ """
70
+
71
+ provider: str
72
+ sub: str
73
+ email: str
74
+ claims: Mapping[str, Any]
75
+
76
+
77
+ def pkce_challenge(code_verifier: str) -> str:
78
+ """Return the PKCE ``S256`` code challenge of ``code_verifier`` (RFC 7636)."""
79
+ digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
80
+ return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
81
+
82
+
83
+ def _build_client(config: OAuthProviderConfig, transport: Any, timeout: float) -> Any:
84
+ """Build the ``httpx-oauth`` client of one provider."""
85
+ try:
86
+ import httpx # noqa: PLC0415
87
+ from httpx_oauth.oauth2 import BaseOAuth2 # noqa: PLC0415
88
+ except ImportError as exc:
89
+ msg = f"OAuth sign-in needs the 'httpx-oauth' package. {_INSTALL_HINT}"
90
+ raise OAuthConfigError(msg) from exc
91
+
92
+ class _Client(BaseOAuth2[dict[str, Any]]):
93
+ def get_httpx_client(self) -> Any:
94
+ return httpx.AsyncClient(transport=transport, timeout=timeout)
95
+
96
+ return _Client(
97
+ config.client_id,
98
+ config.client_secret,
99
+ config.authorize_url,
100
+ config.token_url,
101
+ refresh_token_endpoint=config.token_url,
102
+ name=config.name,
103
+ base_scopes=list(config.scopes),
104
+ )
105
+
106
+
107
+ def _error_code(response: Any) -> str | None:
108
+ """Return the OAuth ``error`` code of a provider response, if it carries one."""
109
+ try:
110
+ payload = response.json()
111
+ except ValueError:
112
+ return None
113
+ code = payload.get("error") if isinstance(payload, dict) else None
114
+ return code if isinstance(code, str) else None
115
+
116
+
117
+ def _split_scopes(raw: Any, default: tuple[str, ...]) -> list[str]:
118
+ """Parse a token response ``scope`` (space- or comma-separated) into a list."""
119
+ if isinstance(raw, str) and raw.strip():
120
+ return [scope for scope in re.split(r"[\s,]+", raw.strip()) if scope]
121
+ return list(default)
122
+
123
+
124
+ def _names(claims: Mapping[str, Any]) -> tuple[str, str]:
125
+ """Return ``(first_name, last_name)`` from OIDC name claims, best effort."""
126
+ first, last = claims.get("given_name"), claims.get("family_name")
127
+ if not first and not last and isinstance(claims.get("name"), str):
128
+ first, _, last = claims["name"].strip().partition(" ")
129
+ return str(first or "")[:_NAME_MAX], str(last or "")[:_NAME_MAX]
130
+
131
+
132
+ class OAuthBackend:
133
+ """OAuth2/OIDC sign-in for the built-in users.
134
+
135
+ Pass it to ``Admin(oauth_backend=...)`` next to ``auth_backend=``::
136
+
137
+ Admin(
138
+ app,
139
+ engine=engine,
140
+ auth_backend=SessionAuthBackend(engine=engine),
141
+ oauth_backend=OAuthBackend(
142
+ providers={"google": google_provider(client_id, client_secret)}
143
+ ),
144
+ )
145
+
146
+ Args:
147
+ providers: Provider configurations by name; each key must equal its
148
+ configuration's ``name``.
149
+ session_factory: Session factory to store users and tokens with. When
150
+ neither it nor ``engine`` is given, ``Admin`` binds its own.
151
+ engine: An async SQLAlchemy engine, as an alternative to ``session_factory``.
152
+ tenant_resolver: Maps the value of a provider's ``tenant_id_claim`` to a
153
+ tenant id when a user is created; return ``None`` for "no tenant".
154
+ transport: ``httpx`` transport for every provider call (tests, proxies).
155
+ timeout: Seconds a provider call may take.
156
+
157
+ Raises:
158
+ OAuthConfigError: No provider, a key that differs from its provider name,
159
+ or the ``oauth`` extra is not installed.
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ providers: Mapping[str, OAuthProviderConfig],
165
+ session_factory: SessionFactory | None = None,
166
+ *,
167
+ engine: Any = None,
168
+ tenant_resolver: Callable[[Any], Any] | None = None,
169
+ transport: Any = None,
170
+ timeout: float = 10.0,
171
+ ) -> None:
172
+ if not providers:
173
+ msg = "OAuthBackend needs at least one provider."
174
+ raise OAuthConfigError(msg)
175
+ for key, config in providers.items():
176
+ if key != config.name:
177
+ msg = f"OAuth provider key {key!r} must equal its name {config.name!r}."
178
+ raise OAuthConfigError(msg)
179
+ self.providers: dict[str, OAuthProviderConfig] = dict(providers)
180
+ self.session_factory = session_factory
181
+ self.engine = engine
182
+ self.tenant_resolver = tenant_resolver
183
+ self._clients = {
184
+ name: _build_client(config, transport, timeout)
185
+ for name, config in self.providers.items()
186
+ }
187
+ self._refresh_locks: weakref.WeakValueDictionary[tuple[int, str], asyncio.Lock] = (
188
+ weakref.WeakValueDictionary()
189
+ )
190
+
191
+ # ── Wiring ────────────────────────────────────────────────────────────
192
+
193
+ def bind(self, *, engine: Any = None, session_factory: SessionFactory | None = None) -> None:
194
+ """Use ``engine`` / ``session_factory`` unless the backend already has its own."""
195
+ if self.engine is None and self.session_factory is None:
196
+ self.engine = engine
197
+ self.session_factory = session_factory
198
+
199
+ def provider(self, name: str) -> OAuthProviderConfig | None:
200
+ """Return the provider configured as ``name``, or ``None``."""
201
+ return self.providers.get(name)
202
+
203
+ def _config(self, name: str) -> OAuthProviderConfig:
204
+ config = self.providers.get(name)
205
+ if config is None:
206
+ msg = f"OAuth provider {name!r} is not configured."
207
+ raise OAuthConfigError(msg)
208
+ return config
209
+
210
+ def _session(self) -> AbstractAsyncContextManager[AsyncSessionLike]:
211
+ if self.engine is None and self.session_factory is None:
212
+ msg = (
213
+ "OAuthBackend has no database: pass engine= or session_factory=, or hand "
214
+ "it to Admin(oauth_backend=...)."
215
+ )
216
+ raise OAuthConfigError(msg)
217
+ return open_session(self.engine, self.session_factory)
218
+
219
+ # ── Provider calls ────────────────────────────────────────────────────
220
+
221
+ async def authorization_url(
222
+ self, provider: str, redirect_uri: str, state: str, code_verifier: str
223
+ ) -> str:
224
+ """Return the provider URL the browser is sent to, with ``state`` and PKCE."""
225
+ config = self._config(provider)
226
+ return await self._clients[provider].get_authorization_url(
227
+ redirect_uri,
228
+ state=state,
229
+ code_challenge=pkce_challenge(code_verifier),
230
+ code_challenge_method="S256",
231
+ extras_params=dict(config.authorize_params) or None,
232
+ )
233
+
234
+ async def exchange_code(
235
+ self, provider: str, code: str, redirect_uri: str, code_verifier: str | None = None
236
+ ) -> dict[str, Any]:
237
+ """Exchange an authorization ``code`` for tokens.
238
+
239
+ Returns:
240
+ The token response: ``access_token``, and when the provider sends them
241
+ ``refresh_token``, ``expires_at`` (epoch seconds) and ``scope``.
242
+
243
+ Raises:
244
+ OAuthProviderError: The provider rejected the code or was unreachable.
245
+ """
246
+ self._config(provider)
247
+ from httpx_oauth.oauth2 import GetAccessTokenError # noqa: PLC0415
248
+
249
+ try:
250
+ token = await self._clients[provider].get_access_token(
251
+ code, redirect_uri, code_verifier
252
+ )
253
+ except GetAccessTokenError as exc:
254
+ raise self._request_error(provider, "Token exchange failed", exc) from exc
255
+ return self._checked_token(provider, token, "Token exchange failed")
256
+
257
+ async def get_userinfo(self, provider: str, access_token: str) -> dict[str, Any]:
258
+ """Return the provider's profile of the token's user.
259
+
260
+ When the profile has no email and the provider has an ``emails_url``
261
+ (GitHub), the primary verified address is looked up and added.
262
+
263
+ Raises:
264
+ OAuthProviderError: The provider refused the token or was unreachable.
265
+ """
266
+ config = self._config(provider)
267
+ claims = await self._get_json(provider, config.userinfo_url, access_token)
268
+ if not isinstance(claims, dict):
269
+ raise OAuthProviderError(provider, "Userinfo is not a JSON object")
270
+ if not claims.get(config.email_claim) and config.emails_url:
271
+ emails = await self._get_json(provider, config.emails_url, access_token)
272
+ email = _primary_email(emails)
273
+ if email:
274
+ claims[config.email_claim] = email
275
+ return claims
276
+
277
+ async def _get_json(self, provider: str, url: str, access_token: str) -> Any:
278
+ import httpx # noqa: PLC0415
279
+
280
+ headers = {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}
281
+ try:
282
+ async with self._clients[provider].get_httpx_client() as http:
283
+ response = await http.get(url, headers=headers)
284
+ except httpx.HTTPError as exc:
285
+ detail = "Userinfo request failed: provider unreachable"
286
+ raise OAuthProviderError(provider, detail, transient=True) from exc
287
+ if response.is_error:
288
+ raise OAuthProviderError(
289
+ provider,
290
+ f"Userinfo request failed (HTTP {response.status_code})",
291
+ error_code=_error_code(response),
292
+ transient=response.status_code >= _SERVER_ERROR,
293
+ )
294
+ try:
295
+ return response.json()
296
+ except ValueError as exc:
297
+ raise OAuthProviderError(provider, "Userinfo is not valid JSON") from exc
298
+
299
+ @staticmethod
300
+ def _request_error(provider: str, what: str, exc: Any) -> OAuthProviderError:
301
+ """Turn an ``httpx-oauth`` request error into an :class:`OAuthProviderError`."""
302
+ response = getattr(exc, "response", None)
303
+ if response is None:
304
+ return OAuthProviderError(provider, f"{what}: provider unreachable", transient=True)
305
+ code = _error_code(response)
306
+ detail = f"{what} (HTTP {response.status_code}{f', {code}' if code else ''})"
307
+ return OAuthProviderError(
308
+ provider,
309
+ detail,
310
+ error_code=code,
311
+ transient=response.status_code >= _SERVER_ERROR,
312
+ )
313
+
314
+ @staticmethod
315
+ def _checked_token(provider: str, token: Mapping[str, Any], what: str) -> dict[str, Any]:
316
+ """Reject a 200 answer that is an error document (GitHub) or has no access token."""
317
+ error = token.get("error")
318
+ if error or not token.get("access_token"):
319
+ code = error if isinstance(error, str) else None
320
+ detail = f"{what} ({code})" if code else f"{what}: no access token returned"
321
+ raise OAuthProviderError(provider, detail, error_code=code)
322
+ return dict(token)
323
+
324
+ # ── Identity ──────────────────────────────────────────────────────────
325
+
326
+ def identity(self, provider: str, userinfo: Mapping[str, Any]) -> OAuthIdentity:
327
+ """Validate ``userinfo`` and return the identity it describes.
328
+
329
+ Raises:
330
+ OAuthProviderError: No stable id, no usable email, an unverified
331
+ email or a ``required_claims`` mismatch.
332
+ """
333
+ config = self._config(provider)
334
+ sub = userinfo.get(config.sub_claim)
335
+ if sub is None or sub == "":
336
+ raise OAuthProviderError(provider, f"Userinfo has no {config.sub_claim!r} claim")
337
+ email = userinfo.get(config.email_claim)
338
+ if not isinstance(email, str) or "@" not in email or len(email) > _EMAIL_MAX:
339
+ raise OAuthProviderError(provider, "Email required")
340
+ if userinfo.get("email_verified") in (False, "false"):
341
+ raise OAuthProviderError(provider, "Email address is not verified")
342
+ for claim, expected in config.required_claims:
343
+ if userinfo.get(claim) != expected:
344
+ raise OAuthProviderError(provider, f"Account is not allowed ({claim} mismatch)")
345
+ return OAuthIdentity(provider, str(sub), email.strip(), userinfo)
346
+
347
+ # ── Users and tokens ──────────────────────────────────────────────────
348
+
349
+ async def provision_user(
350
+ self, provider: str, userinfo: Mapping[str, Any], token: Mapping[str, Any]
351
+ ) -> User:
352
+ """Return the user of this identity, creating it on the first sign-in.
353
+
354
+ A known ``(provider, sub)`` returns its user and stores the new tokens.
355
+ An unknown identity creates a user with no usable password, unless its
356
+ email already belongs to a user: accounts are never linked by email.
357
+
358
+ Raises:
359
+ AccountLinkRequiredError: The email belongs to an existing user.
360
+ AccountDisabledError: The identity's user is not active.
361
+ OAuthSignupDisabledError: Unknown identity and ``allow_signup=False``.
362
+ OAuthProviderError: ``userinfo`` is unusable (see :meth:`identity`).
363
+ """
364
+ identity = self.identity(provider, userinfo)
365
+ try:
366
+ return await self._provision(identity, token)
367
+ except IntegrityError:
368
+ # A concurrent callback of the same identity created the rows first:
369
+ # this one is now a returning sign-in (or an email conflict).
370
+ return await self._provision(identity, token)
371
+
372
+ async def _provision(self, identity: OAuthIdentity, token: Mapping[str, Any]) -> User:
373
+ config = self._config(identity.provider)
374
+ async with self._session() as session:
375
+ row = await self._row_by_sub(session, identity)
376
+ if row is not None:
377
+ user = await session.get(User, row.user_id)
378
+ if user is None or not user.is_active:
379
+ raise AccountDisabledError(identity.email)
380
+ self._store_token(row, config, token)
381
+ session.add(row)
382
+ await session.commit()
383
+ await session.refresh(user)
384
+ return user
385
+ taken = select(User.id).where(func.lower(User.email) == identity.email.lower())
386
+ if (await session.execute(taken)).first() is not None:
387
+ raise AccountLinkRequiredError(identity.provider, identity.email)
388
+ if not config.allow_signup:
389
+ raise OAuthSignupDisabledError(identity.provider)
390
+ first_name, last_name = _names(identity.claims)
391
+ user = User(
392
+ username=await self._free_username(session, identity.email),
393
+ email=identity.email,
394
+ password_hash=make_unusable_password(),
395
+ first_name=first_name,
396
+ last_name=last_name,
397
+ )
398
+ self._apply_tenant(user, config, identity.claims)
399
+ row = OAuthToken(provider=identity.provider, sub=identity.sub, user=user)
400
+ self._store_token(row, config, token)
401
+ session.add_all([user, row])
402
+ await session.commit()
403
+ await session.refresh(user)
404
+ return user
405
+
406
+ async def link_identity(
407
+ self, provider: str, user_id: int, userinfo: Mapping[str, Any], token: Mapping[str, Any]
408
+ ) -> None:
409
+ """Link this identity to the signed-in user ``user_id`` and store its tokens.
410
+
411
+ A provider the user linked before is re-pointed to the new identity.
412
+
413
+ Raises:
414
+ AccountLinkRequiredError: The identity is linked to another user.
415
+ OAuthProviderError: ``userinfo`` is unusable (see :meth:`identity`).
416
+ """
417
+ identity = self.identity(provider, userinfo)
418
+ config = self._config(provider)
419
+ async with self._session() as session:
420
+ row = await self._row_by_sub(session, identity)
421
+ if row is not None and row.user_id != user_id:
422
+ raise AccountLinkRequiredError(provider, identity.email)
423
+ if row is None:
424
+ row = await self._row_by_user(session, user_id, provider)
425
+ if row is None:
426
+ row = OAuthToken(user_id=user_id, provider=provider, sub=identity.sub)
427
+ row.sub = identity.sub
428
+ self._store_token(row, config, token)
429
+ session.add(row)
430
+ await session.commit()
431
+
432
+ async def unlink_identity(self, provider: str, user_id: int) -> bool:
433
+ """Delete the user's link to ``provider``; ``False`` when there was none.
434
+
435
+ Raises:
436
+ LastSignInMethodError: The user has no usable password and no other
437
+ linked provider.
438
+ """
439
+ async with self._session() as session:
440
+ stmt = select(OAuthToken).where(OAuthToken.user_id == user_id).options(_NO_USER)
441
+ rows = list((await session.execute(stmt)).scalars())
442
+ row = next((candidate for candidate in rows if candidate.provider == provider), None)
443
+ if row is None:
444
+ return False
445
+ user = await session.get(User, user_id)
446
+ if len(rows) == 1 and (user is None or user.oauth_only):
447
+ raise LastSignInMethodError(provider)
448
+ await session.delete(row)
449
+ await session.commit()
450
+ return True
451
+
452
+ async def linked_providers(self, user_id: int) -> set[str]:
453
+ """Return the names of the providers ``user_id`` has linked."""
454
+ async with self._session() as session:
455
+ stmt = select(OAuthToken.provider).where(OAuthToken.user_id == user_id)
456
+ return set((await session.execute(stmt)).scalars())
457
+
458
+ async def refresh_token(self, provider: str, user_id: int, *, leeway: float) -> float | None:
459
+ """Make sure the user's access token outlives ``leeway`` seconds.
460
+
461
+ Asks the provider for a new access token when the stored one expires within
462
+ ``leeway`` seconds. Concurrent calls for one user and provider run one after
463
+ another, so a rotating refresh token is used once.
464
+
465
+ Returns:
466
+ The expiry of the (possibly new) access token as epoch seconds, or
467
+ ``None`` when there is nothing to refresh: no link, no expiry or no
468
+ refresh token.
469
+
470
+ Raises:
471
+ OAuthProviderError: The refresh failed. ``transient`` tells a network
472
+ or server failure from a refusal (a revoked refresh token).
473
+ """
474
+ config = self._config(provider)
475
+ key = (user_id, provider)
476
+ lock = self._refresh_locks.get(key)
477
+ if lock is None:
478
+ lock = self._refresh_locks[key] = asyncio.Lock()
479
+ async with lock, self._session() as session:
480
+ row = await self._row_by_user(session, user_id, provider)
481
+ if row is None or row.expires_at is None:
482
+ return None
483
+ if row.expires_at - utc_now() > timedelta(seconds=leeway):
484
+ return _epoch(row.expires_at)
485
+ try:
486
+ refresh_token = row.refresh_token
487
+ except OAuthConfigError as exc:
488
+ raise OAuthProviderError(provider, "Stored token cannot be decrypted") from exc
489
+ if refresh_token is None:
490
+ return None
491
+ token = await self._request_refresh(provider, refresh_token)
492
+ self._store_token(row, config, token)
493
+ session.add(row)
494
+ await session.commit()
495
+ return token.get("expires_at")
496
+
497
+ async def _request_refresh(self, provider: str, refresh_token: str) -> dict[str, Any]:
498
+ from httpx_oauth.oauth2 import RefreshTokenError # noqa: PLC0415
499
+
500
+ try:
501
+ token = await self._clients[provider].refresh_token(refresh_token)
502
+ except RefreshTokenError as exc:
503
+ raise self._request_error(provider, "Token refresh failed", exc) from exc
504
+ return self._checked_token(provider, token, "Token refresh failed")
505
+
506
+ # ── Helpers ───────────────────────────────────────────────────────────
507
+
508
+ @staticmethod
509
+ async def _row_by_sub(session: AsyncSessionLike, identity: OAuthIdentity) -> OAuthToken | None:
510
+ stmt = (
511
+ select(OAuthToken)
512
+ .where(OAuthToken.provider == identity.provider, OAuthToken.sub == identity.sub)
513
+ .options(_NO_USER)
514
+ )
515
+ return (await session.execute(stmt)).scalar_one_or_none()
516
+
517
+ @staticmethod
518
+ async def _row_by_user(
519
+ session: AsyncSessionLike, user_id: int, provider: str
520
+ ) -> OAuthToken | None:
521
+ stmt = (
522
+ select(OAuthToken)
523
+ .where(OAuthToken.user_id == user_id, OAuthToken.provider == provider)
524
+ .options(_NO_USER)
525
+ )
526
+ return (await session.execute(stmt)).scalar_one_or_none()
527
+
528
+ @staticmethod
529
+ def _store_token(
530
+ row: OAuthToken, config: OAuthProviderConfig, token: Mapping[str, Any]
531
+ ) -> None:
532
+ """Copy a token response onto ``row`` (encrypting the tokens)."""
533
+ row.access_token = str(token["access_token"])
534
+ # Providers send a refresh token on the first consent only (Google) or on
535
+ # every refresh (rotation); without a new one the stored one stays valid.
536
+ if token.get("refresh_token"):
537
+ row.refresh_token = str(token["refresh_token"])
538
+ expires_at = token.get("expires_at")
539
+ row.expires_at = (
540
+ datetime.fromtimestamp(float(expires_at), tz=timezone.utc)
541
+ if expires_at is not None
542
+ else None
543
+ )
544
+ row.scopes = _split_scopes(token.get("scope"), config.scopes)
545
+ row.updated_at = utc_now()
546
+
547
+ @staticmethod
548
+ async def _free_username(session: AsyncSessionLike, email: str) -> str:
549
+ """Derive a unique username from the email's local part."""
550
+ base = _USERNAME_UNSAFE.sub("", email.partition("@")[0])[: _USERNAME_MAX - 10] or "user"
551
+ stmt = select(User.username).where(col(User.username).startswith(base, autoescape=True))
552
+ taken = set((await session.execute(stmt)).scalars())
553
+ candidate, suffix = base, 1
554
+ while candidate in taken:
555
+ suffix += 1
556
+ candidate = f"{base}-{suffix}"
557
+ return candidate
558
+
559
+ def _apply_tenant(
560
+ self, user: Any, config: OAuthProviderConfig, claims: Mapping[str, Any]
561
+ ) -> None:
562
+ """Set ``user.tenant_id`` from the provider's tenant claim, when one maps.
563
+
564
+ The built-in ``User`` has no ``tenant_id`` column before multi-tenancy
565
+ (v0.5.3); the resolved value is then only logged.
566
+ """
567
+ if config.tenant_id_claim is None:
568
+ return
569
+ value = claims.get(config.tenant_id_claim)
570
+ resolver = self.tenant_resolver
571
+ tenant_id = resolver(value) if resolver is not None and value is not None else None
572
+ if tenant_id is None:
573
+ logger.info(
574
+ "OAuth provider %s: no tenant for claim %s=%r; the new user has no tenant.",
575
+ config.name,
576
+ config.tenant_id_claim,
577
+ value,
578
+ )
579
+ return
580
+ if not hasattr(user, "tenant_id"):
581
+ logger.info(
582
+ "OAuth provider %s: tenant %r resolved, but the user model has no tenant_id.",
583
+ config.name,
584
+ tenant_id,
585
+ )
586
+ return
587
+ user.tenant_id = tenant_id
588
+
589
+
590
+ #: Token queries never need the user relationship (it would load groups and permissions).
591
+ _NO_USER = noload(OAuthToken.user) # type: ignore[arg-type]
592
+
593
+
594
+ def _epoch(moment: datetime | None) -> float | None:
595
+ return moment.timestamp() if moment is not None else None
596
+
597
+
598
+ def _primary_email(emails: Any) -> str | None:
599
+ """Pick the primary verified address from a GitHub ``/user/emails`` answer."""
600
+ if not isinstance(emails, list):
601
+ return None
602
+ verified = [
603
+ entry
604
+ for entry in emails
605
+ if isinstance(entry, dict) and entry.get("verified") and isinstance(entry.get("email"), str)
606
+ ]
607
+ verified.sort(key=lambda entry: not entry.get("primary"))
608
+ return verified[0]["email"] if verified else None
609
+
610
+
611
+ __all__ = ["OAuthBackend", "OAuthIdentity", "pkce_challenge"]