ordloom 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 (280) hide show
  1. ordloom/__init__.py +3 -0
  2. ordloom/account_security.py +96 -0
  3. ordloom/api/__init__.py +0 -0
  4. ordloom/api/account_admin.py +66 -0
  5. ordloom/api/accounts.py +42 -0
  6. ordloom/api/admin_forms.py +59 -0
  7. ordloom/api/audit_retention.py +18 -0
  8. ordloom/api/auth.py +224 -0
  9. ordloom/api/base.py +113 -0
  10. ordloom/api/collaboration.py +269 -0
  11. ordloom/api/config.py +59 -0
  12. ordloom/api/crud.py +474 -0
  13. ordloom/api/dashboard.py +90 -0
  14. ordloom/api/data_services.py +231 -0
  15. ordloom/api/data_templates.py +21 -0
  16. ordloom/api/dataset_usage.py +49 -0
  17. ordloom/api/datasets.py +302 -0
  18. ordloom/api/events.py +33 -0
  19. ordloom/api/field_scope.py +93 -0
  20. ordloom/api/file_values.py +49 -0
  21. ordloom/api/form_exports.py +57 -0
  22. ordloom/api/form_summary.py +54 -0
  23. ordloom/api/grant_audits.py +80 -0
  24. ordloom/api/identifiers.py +24 -0
  25. ordloom/api/inline_forms.py +248 -0
  26. ordloom/api/json_fields.py +22 -0
  27. ordloom/api/list_query.py +68 -0
  28. ordloom/api/listing.py +159 -0
  29. ordloom/api/notifications.py +152 -0
  30. ordloom/api/offline.py +72 -0
  31. ordloom/api/offline_snapshots.py +106 -0
  32. ordloom/api/operations.py +59 -0
  33. ordloom/api/overview.py +148 -0
  34. ordloom/api/ownership.py +80 -0
  35. ordloom/api/page_bindings.py +140 -0
  36. ordloom/api/page_charts.py +102 -0
  37. ordloom/api/page_forms.py +225 -0
  38. ordloom/api/page_grants.py +297 -0
  39. ordloom/api/pages.py +291 -0
  40. ordloom/api/password_fields.py +182 -0
  41. ordloom/api/rate_limit.py +24 -0
  42. ordloom/api/readonly_fields.py +31 -0
  43. ordloom/api/registry.py +696 -0
  44. ordloom/api/report_bindings.py +38 -0
  45. ordloom/api/report_boards.py +128 -0
  46. ordloom/api/report_exports.py +216 -0
  47. ordloom/api/reports.py +176 -0
  48. ordloom/api/screen_playlists.py +134 -0
  49. ordloom/api/security.py +159 -0
  50. ordloom/api/share_management.py +59 -0
  51. ordloom/api/share_settings.py +118 -0
  52. ordloom/api/task_diagnostics.py +22 -0
  53. ordloom/api/totp.py +75 -0
  54. ordloom/api/webhooks.py +247 -0
  55. ordloom/apps.py +18 -0
  56. ordloom/asgi.py +12 -0
  57. ordloom/audit_retention.py +78 -0
  58. ordloom/branding.py +4 -0
  59. ordloom/collaboration.py +168 -0
  60. ordloom/components/__init__.py +1 -0
  61. ordloom/components/fields.py +257 -0
  62. ordloom/conf.py +61 -0
  63. ordloom/consumers.py +92 -0
  64. ordloom/data_services.py +228 -0
  65. ordloom/diagnostics.py +84 -0
  66. ordloom/editor/__init__.py +0 -0
  67. ordloom/editor/fields.py +30 -0
  68. ordloom/graphql/__init__.py +1 -0
  69. ordloom/graphql/access.py +279 -0
  70. ordloom/graphql/checks.py +16 -0
  71. ordloom/graphql/datasets.py +325 -0
  72. ordloom/graphql/durations.py +43 -0
  73. ordloom/graphql/event_access.py +45 -0
  74. ordloom/graphql/event_limits.py +12 -0
  75. ordloom/graphql/events.py +118 -0
  76. ordloom/graphql/inputs.py +133 -0
  77. ordloom/graphql/json_projection.py +141 -0
  78. ordloom/graphql/query.py +235 -0
  79. ordloom/graphql/registry.py +160 -0
  80. ordloom/graphql/relations.py +82 -0
  81. ordloom/graphql/schema.py +217 -0
  82. ordloom/graphql/scopes.py +64 -0
  83. ordloom/graphql/subscriptions.py +59 -0
  84. ordloom/graphql/views.py +89 -0
  85. ordloom/management/__init__.py +0 -0
  86. ordloom/management/commands/__init__.py +0 -0
  87. ordloom/management/commands/ordloom_check.py +31 -0
  88. ordloom/management/commands/ordloom_deliver_webhooks.py +25 -0
  89. ordloom/management/commands/ordloom_export_reports.py +24 -0
  90. ordloom/management/commands/ordloom_init.py +42 -0
  91. ordloom/management/commands/ordloom_prune_audit.py +25 -0
  92. ordloom/management/commands/ordloom_prune_share_visits.py +42 -0
  93. ordloom/management/commands/ordloom_reindex_visual.py +45 -0
  94. ordloom/management/commands/ordloom_upgrade.py +56 -0
  95. ordloom/middleware.py +23 -0
  96. ordloom/migrations/0001_initial.py +30 -0
  97. ordloom/migrations/0002_siteconfig.py +25 -0
  98. ordloom/migrations/0003_visualpage.py +33 -0
  99. ordloom/migrations/0004_visualpage_uuid.py +31 -0
  100. ordloom/migrations/0005_visualsubmission.py +23 -0
  101. ordloom/migrations/0006_screenplaylist.py +21 -0
  102. ordloom/migrations/0007_visualdataset.py +38 -0
  103. ordloom/migrations/0008_share_controls.py +19 -0
  104. ordloom/migrations/0009_report.py +21 -0
  105. ordloom/migrations/0010_page_grant.py +21 -0
  106. ordloom/migrations/0011_usersecurity.py +17 -0
  107. ordloom/migrations/0012_visualgrantaudit.py +27 -0
  108. ordloom/migrations/0013_visual_usage.py +55 -0
  109. ordloom/migrations/0014_notifications_retention.py +28 -0
  110. ordloom/migrations/0015_webhooks.py +97 -0
  111. ordloom/migrations/0016_data_services.py +38 -0
  112. ordloom/migrations/0017_dataset_archive.py +18 -0
  113. ordloom/migrations/0018_recovery_devices.py +53 -0
  114. ordloom/migrations/0019_share_access_visits.py +57 -0
  115. ordloom/migrations/0020_initialization_batch.py +30 -0
  116. ordloom/migrations/0021_offline_page_import.py +31 -0
  117. ordloom/migrations/0022_report_board.py +32 -0
  118. ordloom/migrations/0023_report_exports.py +64 -0
  119. ordloom/migrations/0024_collaboration.py +66 -0
  120. ordloom/migrations/0025_organization_members.py +12 -0
  121. ordloom/migrations/0026_ownership_handover.py +161 -0
  122. ordloom/migrations/__init__.py +0 -0
  123. ordloom/models.py +709 -0
  124. ordloom/notifications.py +60 -0
  125. ordloom/offline_worker.js +40 -0
  126. ordloom/organizations.py +181 -0
  127. ordloom/ownership.py +268 -0
  128. ordloom/pwa.py +92 -0
  129. ordloom/report_exports/__init__.py +1 -0
  130. ordloom/report_exports/calendar.py +57 -0
  131. ordloom/report_exports/config.py +31 -0
  132. ordloom/report_exports/files.py +35 -0
  133. ordloom/report_exports/service.py +269 -0
  134. ordloom/routing.py +20 -0
  135. ordloom/session_devices.py +120 -0
  136. ordloom/setup_tools.py +268 -0
  137. ordloom/share_access.py +45 -0
  138. ordloom/share_analytics.py +67 -0
  139. ordloom/share_limits.py +93 -0
  140. ordloom/starter_templates.json +1828 -0
  141. ordloom/static/ordloom/assets/AntVChart-BojmTL-Y.js +2 -0
  142. ordloom/static/ordloom/assets/ArrowUpOutlined-BK7Q4uIi.js +1 -0
  143. ordloom/static/ordloom/assets/CollaborationWorkspaces-BKW9-_as.js +1 -0
  144. ordloom/static/ordloom/assets/ComponentGallery-BxhkXpfP.js +17 -0
  145. ordloom/static/ordloom/assets/DataServicesPage-QJv4K_F5.js +1 -0
  146. ordloom/static/ordloom/assets/DataTemplateWizard-xfmGniII.js +1 -0
  147. ordloom/static/ordloom/assets/DatasetDefinitionEditor-CJ3Mh0Bs.js +1 -0
  148. ordloom/static/ordloom/assets/DatasetDiffDialog-DJ67-lSk.js +1 -0
  149. ordloom/static/ordloom/assets/DatasetManager-CQ0B81Ir.js +1 -0
  150. ordloom/static/ordloom/assets/FieldHelp-CRCeq7I3.js +1 -0
  151. ordloom/static/ordloom/assets/ListPage-D7xh7bVw.js +3 -0
  152. ordloom/static/ordloom/assets/MapInput-B9gGNYEP.js +1 -0
  153. ordloom/static/ordloom/assets/MapInput-CIGW-MKW.css +1 -0
  154. ordloom/static/ordloom/assets/MarkdownEditor-VPtMJjYh.js +27 -0
  155. ordloom/static/ordloom/assets/MarkdownPreview-X4ByFMEn.js +1 -0
  156. ordloom/static/ordloom/assets/OfflineManager-Bn-OXfuJ.js +1 -0
  157. ordloom/static/ordloom/assets/OfflineStudio-BFKOLEIl.js +2 -0
  158. ordloom/static/ordloom/assets/OfflineStudio-CHMOkowM.css +1 -0
  159. ordloom/static/ordloom/assets/PasswordResetModal-BM49m5rd.js +1 -0
  160. ordloom/static/ordloom/assets/ReportBoard-BR7yNUg4.js +1 -0
  161. ordloom/static/ordloom/assets/ReportBoardsPage-BBwjUvc1.js +1 -0
  162. ordloom/static/ordloom/assets/ReportBuilder-351dd4me.js +1 -0
  163. ordloom/static/ordloom/assets/ReportsPage-B8HgL-Y7.css +1 -0
  164. ordloom/static/ordloom/assets/ReportsPage-CPRhGLQH.js +1 -0
  165. ordloom/static/ordloom/assets/ScreenPlaylistManager-CB-oxQey.js +1 -0
  166. ordloom/static/ordloom/assets/ScreenPlaylistPlayer-okeMCPM2.js +1 -0
  167. ordloom/static/ordloom/assets/ShareAltOutlined-DW3yw-mg.js +1 -0
  168. ordloom/static/ordloom/assets/SnapshotCapture-CBEtdhtC.js +1 -0
  169. ordloom/static/ordloom/assets/TaskDiagnosticsPage-D-FXN4nU.js +1 -0
  170. ordloom/static/ordloom/assets/UploadOutlined-bFpyTlaX.js +4 -0
  171. ordloom/static/ordloom/assets/VisualEditor-VGjww2oH.js +4 -0
  172. ordloom/static/ordloom/assets/WebhooksPage-C5smoskE.js +1 -0
  173. ordloom/static/ordloom/assets/antvRuntime-DTdop13K.js +52 -0
  174. ordloom/static/ordloom/assets/bootstrap-Cpbq7tW-.js +410 -0
  175. ordloom/static/ordloom/assets/bootstrap-D2zNl10I.css +1 -0
  176. ordloom/static/ordloom/assets/chartRuntime-BDiSlyel.js +1 -0
  177. ordloom/static/ordloom/assets/chartRuntime-Co53qbqJ.js +1 -0
  178. ordloom/static/ordloom/assets/client-NN9rkfuB.js +1 -0
  179. ordloom/static/ordloom/assets/document-DmZes12j.js +1 -0
  180. ordloom/static/ordloom/assets/index-Cg-wJrAe.js +1 -0
  181. ordloom/static/ordloom/assets/index.css +1 -0
  182. ordloom/static/ordloom/assets/index.js +2 -0
  183. ordloom/static/ordloom/assets/installCanvasRenderer-Cyw3KEQY.js +18 -0
  184. ordloom/static/ordloom/assets/markdown.worker-BzqxKdkw.js +71 -0
  185. ordloom/static/ordloom/assets/preload-BF3UiITl.js +1 -0
  186. ordloom/static/ordloom/assets/reportBoards-DSTrDDne.css +1 -0
  187. ordloom/static/ordloom/assets/snapshotStore-CIIzd0oa.js +1 -0
  188. ordloom/static/ordloom/assets/tslib.es6-1xh5QPgC.js +1 -0
  189. ordloom/static/ordloom/assets/useConfigurationAccess-DMNpfk3o.js +1 -0
  190. ordloom/static/ordloom/assets/widgets-CE3Rq9Ku.js +36 -0
  191. ordloom/static/ordloom/component-cover.svg +11 -0
  192. ordloom/static/ordloom/icons/icon-192.png +0 -0
  193. ordloom/static/ordloom/icons/icon-512.png +0 -0
  194. ordloom/static/ordloom/index.html +14 -0
  195. ordloom/static/ordloom/offline-assets.json +301 -0
  196. ordloom/static/ordloom/visual-assets/SOURCES.md +15 -0
  197. ordloom/static/ordloom/visual-assets/city.jpg +0 -0
  198. ordloom/static/ordloom/visual-assets/coffee.jpg +0 -0
  199. ordloom/static/ordloom/visual-assets/event.jpg +0 -0
  200. ordloom/static/ordloom/visual-assets/headphones.jpg +0 -0
  201. ordloom/static/ordloom/visual-assets/nature.jpg +0 -0
  202. ordloom/static/ordloom/visual-assets/workspace.jpg +0 -0
  203. ordloom/task_runtime.py +297 -0
  204. ordloom/templates/ordloom/index.html +22 -0
  205. ordloom/templates/ordloom/offline.html +3 -0
  206. ordloom/tests/__init__.py +0 -0
  207. ordloom/tests/admin.py +461 -0
  208. ordloom/tests/apps.py +7 -0
  209. ordloom/tests/email_account.py +35 -0
  210. ordloom/tests/models.py +323 -0
  211. ordloom/tests/test_account_admin.py +375 -0
  212. ordloom/tests/test_accounts.py +257 -0
  213. ordloom/tests/test_audit_retention.py +145 -0
  214. ordloom/tests/test_collaboration.py +413 -0
  215. ordloom/tests/test_create_only.py +73 -0
  216. ordloom/tests/test_data_services.py +273 -0
  217. ordloom/tests/test_data_templates.py +97 -0
  218. ordloom/tests/test_dataset_archive.py +235 -0
  219. ordloom/tests/test_dataset_usage.py +147 -0
  220. ordloom/tests/test_datasets.py +416 -0
  221. ordloom/tests/test_durations.py +205 -0
  222. ordloom/tests/test_events.py +179 -0
  223. ordloom/tests/test_events_channels.py +233 -0
  224. ordloom/tests/test_fields.py +371 -0
  225. ordloom/tests/test_form_results.py +130 -0
  226. ordloom/tests/test_generic_inline.py +318 -0
  227. ordloom/tests/test_grant_audits.py +123 -0
  228. ordloom/tests/test_graphql.py +361 -0
  229. ordloom/tests/test_graphql_queries.py +358 -0
  230. ordloom/tests/test_host_setup.py +272 -0
  231. ordloom/tests/test_identifiers.py +141 -0
  232. ordloom/tests/test_inline_contract.py +220 -0
  233. ordloom/tests/test_json_fields.py +175 -0
  234. ordloom/tests/test_json_projection.py +272 -0
  235. ordloom/tests/test_management.py +73 -0
  236. ordloom/tests/test_markdown.py +131 -0
  237. ordloom/tests/test_notifications.py +183 -0
  238. ordloom/tests/test_offline.py +139 -0
  239. ordloom/tests/test_offline_snapshots.py +194 -0
  240. ordloom/tests/test_operations.py +203 -0
  241. ordloom/tests/test_organizations.py +290 -0
  242. ordloom/tests/test_overview.py +236 -0
  243. ordloom/tests/test_ownership.py +285 -0
  244. ordloom/tests/test_page_bindings.py +161 -0
  245. ordloom/tests/test_page_grants.py +300 -0
  246. ordloom/tests/test_pages.py +320 -0
  247. ordloom/tests/test_recovery_devices.py +304 -0
  248. ordloom/tests/test_relations.py +313 -0
  249. ordloom/tests/test_report_boards.py +152 -0
  250. ordloom/tests/test_report_exports.py +418 -0
  251. ordloom/tests/test_report_initialization.py +236 -0
  252. ordloom/tests/test_report_reuse.py +233 -0
  253. ordloom/tests/test_reports.py +193 -0
  254. ordloom/tests/test_request_body.py +69 -0
  255. ordloom/tests/test_screen_playlists.py +141 -0
  256. ordloom/tests/test_secret_fields.py +192 -0
  257. ordloom/tests/test_share_access.py +188 -0
  258. ordloom/tests/test_share_limits.py +165 -0
  259. ordloom/tests/test_share_settings.py +120 -0
  260. ordloom/tests/test_sql_scopes.py +259 -0
  261. ordloom/tests/test_task_diagnostics.py +216 -0
  262. ordloom/tests/test_totp.py +206 -0
  263. ordloom/tests/test_webhook_bots.py +280 -0
  264. ordloom/tests/test_webhooks.py +349 -0
  265. ordloom/tests/test_workspace.py +65 -0
  266. ordloom/urls.py +152 -0
  267. ordloom/views.py +115 -0
  268. ordloom/visual_templates.py +118 -0
  269. ordloom/visual_usage.py +61 -0
  270. ordloom/webhooks/__init__.py +1 -0
  271. ordloom/webhooks/access.py +41 -0
  272. ordloom/webhooks/bots.py +135 -0
  273. ordloom/webhooks/config.py +79 -0
  274. ordloom/webhooks/signals.py +70 -0
  275. ordloom/webhooks/transport.py +78 -0
  276. ordloom/webhooks/worker.py +149 -0
  277. ordloom-1.0.0.dist-info/METADATA +2543 -0
  278. ordloom-1.0.0.dist-info/RECORD +280 -0
  279. ordloom-1.0.0.dist-info/WHEEL +5 -0
  280. ordloom-1.0.0.dist-info/top_level.txt +1 -0
ordloom/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """序衡 Ordloom — a configurable React + Ant Design workspace for Django Admin."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,96 @@
1
+ """Atomic high-entropy recovery codes and reauthentication; no stored cleartext."""
2
+ import hashlib
3
+ import re
4
+ import secrets
5
+ import time
6
+
7
+ from django.utils import timezone
8
+ from django.views.decorators.debug import sensitive_variables
9
+
10
+ from .api.rate_limit import is_locked, record_failure, reset_failures
11
+
12
+
13
+ def locked_security(user):
14
+ from .models import UserSecurity
15
+ from django.contrib.auth import get_user_model
16
+ # Native Django login updates the account before its login signals. Use the
17
+ # same account -> security lock order for MFA, passwords and device quotas.
18
+ current = get_user_model()._default_manager.select_for_update().get(pk=user.pk)
19
+ if not current.is_active or not (current.is_staff or current.is_superuser):
20
+ raise ReauthenticationError('账号不可用', 403)
21
+ row, _ = UserSecurity.objects.get_or_create(user=current)
22
+ locked = UserSecurity.objects.select_for_update().get(pk=row.pk)
23
+ locked.user = current
24
+ return locked
25
+
26
+
27
+ @sensitive_variables('code')
28
+ def recovery_hash(user_id, code):
29
+ if not isinstance(code, str) or len(code) > 80: return None
30
+ normalized = re.sub(r'[-\s]', '', code).upper()
31
+ if not re.fullmatch(r'[0-9A-F]{32}', normalized): return None
32
+ return hashlib.sha256(('ordloom-recovery-v1:' + str(user_id) + ':' + normalized).encode()).hexdigest()
33
+
34
+
35
+ @sensitive_variables('codes', 'raw')
36
+ def issue_codes(security):
37
+ from .models import TOTPRecoveryCode
38
+ codes = []
39
+ for _ in range(10):
40
+ raw = secrets.token_hex(16).upper()
41
+ codes.append('-'.join(raw[index:index+4] for index in range(0, 32, 4)))
42
+ security.recovery_codes.all().delete()
43
+ TOTPRecoveryCode.objects.bulk_create([TOTPRecoveryCode(security=security,
44
+ code_hash=recovery_hash(security.user_id, code)) for code in codes])
45
+ security.recovery_issued_at = timezone.now()
46
+ security.save(update_fields=['recovery_issued_at', 'updated_at'])
47
+ return codes
48
+
49
+
50
+ @sensitive_variables('code')
51
+ def consume_code(security, code):
52
+ if not security.totp_enabled: return False
53
+ digest = recovery_hash(security.user_id, code)
54
+ if digest is None: return False
55
+ return bool(security.recovery_codes.filter(code_hash=digest, used_at__isnull=True).update(used_at=timezone.now()))
56
+
57
+
58
+ class ReauthenticationError(Exception):
59
+ def __init__(self, message='安全验证未通过', status=400):
60
+ self.status = status
61
+ super().__init__(message)
62
+
63
+
64
+ @sensitive_variables('body', 'password', 'recovery')
65
+ def reauthenticate(request, security, body):
66
+ """Call inside the same transaction as the protected action and code consume."""
67
+ from .api.totp import verify
68
+ key = 'su-reauth:' + hashlib.sha256(str(request.user.pk).encode()).hexdigest()
69
+ if is_locked(key): raise ReauthenticationError('尝试次数过多,请 5 分钟后再试', 429)
70
+ password = body.get('password')
71
+ if security.user.has_usable_password():
72
+ valid = isinstance(password, str) and len(password) <= 4096 and security.user.check_password(password)
73
+ else:
74
+ # SSO accounts must re-enter through the host authentication flow recently.
75
+ at = request.session.get('ordloom_authenticated_at', 0)
76
+ valid = isinstance(at, (int, float)) and 0 <= time.time()-at <= 300
77
+ recovery = body.get('recovery_code')
78
+ if security.totp_enabled:
79
+ if recovery:
80
+ valid = valid and not body.get('code') and consume_code(security, recovery)
81
+ else:
82
+ valid = valid and verify(security.totp_secret, body.get('code'))
83
+ elif recovery or body.get('code'):
84
+ valid = False
85
+ if not valid:
86
+ record_failure(key, 300)
87
+ raise ReauthenticationError('密码或安全验证码不正确' if security.user.has_usable_password()
88
+ else '请重新登录,并提供有效的安全验证码后操作')
89
+ reset_failures(key)
90
+
91
+
92
+ def audit(user, action):
93
+ from django.contrib.admin.models import CHANGE, LogEntry
94
+ from django.contrib.contenttypes.models import ContentType
95
+ LogEntry.objects.create(user_id=user.pk, content_type=ContentType.objects.get_for_model(user),
96
+ object_id=str(user.pk), object_repr='账号安全', action_flag=CHANGE, change_message=action)
File without changes
@@ -0,0 +1,66 @@
1
+ """Password administration through the project's native UserAdmin form and audit hook."""
2
+ from django import forms
3
+ from django.contrib.auth import update_session_auth_hash
4
+ from django.core.exceptions import PermissionDenied
5
+ from django.db import transaction
6
+ from django.views.decorators.cache import never_cache
7
+ from django.views.decorators.debug import sensitive_post_parameters, sensitive_variables
8
+
9
+ from .accounts import csrf_payload, identity_payload
10
+ from .base import get_admin, json_err, json_ok, read_body, staff_required
11
+ from .crud import _write_errors
12
+ from .field_scope import scoped_object
13
+ from .inline_forms import merge_post
14
+ from .password_fields import can_reset_password, initial_field_value, password_state, password_toggle_fields
15
+ from .json_fields import json_source
16
+
17
+
18
+ @never_cache
19
+ @staff_required
20
+ @_write_errors
21
+ @transaction.atomic
22
+ @sensitive_post_parameters()
23
+ @sensitive_variables('body', 'values', 'form')
24
+ def password_form(request, model_key, obj_id=None):
25
+ if request.method not in ('GET', 'POST'): return json_err('仅支持 GET 或 POST', status=405)
26
+ if obj_id is None and 'object_id' not in request.GET: return json_err('请提供记录标识')
27
+ model, madmin = get_admin(model_key)
28
+ user = scoped_object(madmin.get_queryset(request), request.GET['object_id'] if obj_id is None else obj_id)
29
+ if not can_reset_password(request, madmin, user): raise PermissionDenied('没有设置此账号密码的权限')
30
+ body = read_body(request) if request.method == 'POST' else {}
31
+ values = body.get('data', {})
32
+ if not isinstance(values, dict): return json_err('data 必须是对象')
33
+ form = madmin.change_password_form(user, data=values) if request.method == 'POST' else madmin.change_password_form(user)
34
+ if request.method == 'GET':
35
+ from .registry import build_field_meta
36
+ fields = []
37
+ for name, field in form.fields.items():
38
+ meta = build_field_meta(None, field, name)
39
+ meta['default'] = field.prepare_value(initial_field_value(form, name, field))
40
+ source = json_source(form, name)
41
+ if source is not None and not meta.get('write_only'): meta['json_source'] = source
42
+ fields.append(meta)
43
+ return json_ok({'fields': password_toggle_fields(form, fields), 'status': password_state(user.password),
44
+ 'object_label': str(user.get_username()), **csrf_payload(request)})
45
+ for name, field in form.fields.items():
46
+ if isinstance(field.widget, forms.PasswordInput) and name in values:
47
+ if not isinstance(values[name], str) or len(values[name]) > 4096:
48
+ transaction.set_rollback(True)
49
+ return json_err('请输入有效的密码', errors={name: ['密码最多 4096 个字符']})
50
+ merge_post(request, values)
51
+ if not form.is_valid():
52
+ transaction.set_rollback(True)
53
+ from .password_fields import safe_form_errors
54
+ return json_err('请检查标记的密码字段', errors=safe_form_errors(form))
55
+ # Match UserAdmin's explicit submit action when disabling password login.
56
+ if form.cleaned_data.get('set_usable_password') is False and body.get('action') != 'disable':
57
+ transaction.set_rollback(True)
58
+ return json_err('请明确选择停用密码登录', errors={'usable_password': ['请确认停用密码登录']})
59
+ if body.get('action', 'set') not in ('set', 'disable') or body.get('action') == 'disable' and form.cleaned_data.get('set_usable_password', True):
60
+ transaction.set_rollback(True)
61
+ return json_err('密码操作与表单选择不一致')
62
+ user = form.save()
63
+ madmin.log_change(request, user, madmin.construct_change_message(request, form, None))
64
+ update_session_auth_hash(request, user)
65
+ return json_ok({'status': password_state(user.password), **csrf_payload(request),
66
+ 'current_user': identity_payload(user, request) if request.user == user else None})
@@ -0,0 +1,42 @@
1
+ """Account metadata shared by authentication and site settings."""
2
+ from django.contrib.auth import get_user_model
3
+ from django.contrib.auth.password_validation import password_validators_help_texts
4
+ from django.db import models
5
+ from django.utils.text import capfirst
6
+ from django.conf import settings
7
+ from django.middleware.csrf import get_token
8
+
9
+
10
+ def login_field():
11
+ model = get_user_model()
12
+ field = model._meta.get_field(model.USERNAME_FIELD)
13
+ return {'key': model.USERNAME_FIELD, 'label': capfirst(str(field.verbose_name)),
14
+ 'max_length': field.max_length or 254,
15
+ 'type': 'email' if isinstance(field, models.EmailField) else 'text'}
16
+
17
+
18
+ def can_manage_settings(user):
19
+ return bool(user.is_authenticated and getattr(user, 'is_active', True)
20
+ and (user.is_staff or user.is_superuser)
21
+ and user.has_perm('ordloom.change_siteconfig'))
22
+
23
+
24
+ def csrf_payload(request):
25
+ readable = not settings.CSRF_COOKIE_HTTPONLY and not settings.CSRF_USE_SESSIONS
26
+ return {'csrf_token': get_token(request), 'csrf_cookie_name': settings.CSRF_COOKIE_NAME if readable else None}
27
+
28
+
29
+ def identity_payload(user, request):
30
+ username = str(user.get_username())
31
+ name = ''
32
+ for method in ('get_full_name', 'get_short_name'):
33
+ getter = getattr(user, method, None)
34
+ if callable(getter): name = str(getter() or '').strip()
35
+ if name: break
36
+ return {**csrf_payload(request), 'id': str(user.pk), 'username': username, 'name': name or username,
37
+ 'is_superuser': bool(user.is_superuser),
38
+ 'access_admin': bool(getattr(user, 'is_active', True) and (user.is_staff or user.is_superuser)),
39
+ 'capabilities': {'manage_settings': can_manage_settings(user),
40
+ 'view_audit_retention': bool(user.is_superuser),
41
+ 'change_password': user.has_usable_password()},
42
+ 'password_help': password_validators_help_texts()}
@@ -0,0 +1,59 @@
1
+ """Shared ModelAdmin form construction for metadata, validation and related choices."""
2
+ from django.db import models
3
+ from django.forms import modelform_factory
4
+
5
+
6
+ def admin_form_class(model, madmin=None, request=None, obj=None, include_files=True, exclude_names=(), for_display=False):
7
+ excluded = set(exclude_names) | {'deleted_at', 'deleted'}
8
+ if not include_files:
9
+ excluded.update(field.name for field in model._meta.concrete_fields if isinstance(field, models.FileField))
10
+ if madmin is None:
11
+ names = [field.name for field in model._meta.get_fields() if getattr(field, 'editable', False)
12
+ and not field.auto_created and field.name not in excluded]
13
+ return modelform_factory(model, fields=names)
14
+ admin_excluded = madmin.get_exclude(request, obj)
15
+ excluded.update(admin_excluded or [])
16
+ excluded.update(madmin.get_readonly_fields(request, obj) or [])
17
+ if admin_excluded is None:
18
+ excluded.update(getattr(getattr(madmin.form, '_meta', None), 'exclude', None) or [])
19
+ if hasattr(madmin, 'get_form'):
20
+ Form = madmin.get_form(request, obj, change=obj is not None and (not for_display or madmin.has_change_permission(request, obj)), exclude=list(excluded))
21
+ from .password_fields import protect_hash_form
22
+ return protect_hash_form(Form, model)
23
+ # InlineModelAdmin exposes get_formset rather than get_form.
24
+ return madmin.get_formset(request, obj, exclude=list(excluded)).form
25
+
26
+
27
+ def normalize_form_payload(model, payload, form_fields=None):
28
+ from ..components.fields import CheckboxField
29
+ result = dict(payload)
30
+ for field in model._meta.concrete_fields:
31
+ if isinstance(field, CheckboxField) and isinstance(result.get(field.name), str):
32
+ result[field.name] = [part for part in result[field.name].split(',') if part]
33
+ from django import forms
34
+ from django.core.exceptions import ValidationError
35
+ import json
36
+ from django.core.serializers.json import DjangoJSONEncoder
37
+ for name, field in (form_fields or {}).items():
38
+ if isinstance(field, forms.JSONField) and name in result and not isinstance(result[name], str):
39
+ result[name] = json.dumps(result[name], cls=DjangoJSONEncoder)
40
+ if isinstance(field, forms.SplitDateTimeField) and name in result:
41
+ value = result[name]
42
+ try:
43
+ if value in (None, ''): parts = [None, None]
44
+ elif isinstance(value, (list, tuple)): parts = value
45
+ else: parts = field.widget.decompress(forms.DateTimeField(required=field.required).clean(value))
46
+ except ValidationError as error: raise ValidationError({name: error.messages}) from error
47
+ for suffix, part in zip(field.widget.widgets_names, parts): result[f'{name}{suffix}'] = part
48
+ return result
49
+
50
+
51
+ def bind_admin_form(Form, model, data, instance):
52
+ values = normalize_form_payload(model, data, Form.base_fields)
53
+ form = Form(data=values, instance=instance)
54
+ from .password_fields import preserve_secret_values, protect_hash_instance
55
+ protect_hash_instance(form, model)
56
+ # Native forms may add JSON or split date/time fields in __init__.
57
+ form.data = normalize_form_payload(model, values, form.fields)
58
+ preserve_secret_values(form)
59
+ return form
@@ -0,0 +1,18 @@
1
+ from django.views.decorators.cache import never_cache
2
+ from django.core.exceptions import ImproperlyConfigured
3
+
4
+ from .base import json_err, json_ok, staff_required
5
+
6
+
7
+ @staff_required
8
+ @never_cache
9
+ def status(request):
10
+ if not request.user.is_superuser: return json_err('仅超级管理员可查看全局留存策略', status=403)
11
+ if request.method != 'GET': return json_err('仅支持 GET', status=405)
12
+ from ..audit_retention import options
13
+ from ..models import AuditRetentionBatch
14
+ try: policy = options()
15
+ except ImproperlyConfigured: return json_err('审计留存配置不可用,请联系管理员', status=503)
16
+ return json_ok({'policy': policy, 'items': [{'run_id': str(row.run_id), 'stream': row.stream,
17
+ 'cutoff': row.cutoff.isoformat(), 'deleted_count': row.deleted_count, 'created_at': row.created_at.isoformat()}
18
+ for row in AuditRetentionBatch.objects.all()[:20]]})
ordloom/api/auth.py ADDED
@@ -0,0 +1,224 @@
1
+ """认证接口:session 登录 / 登出 / 当前用户 / 登录验证码"""
2
+
3
+ import base64
4
+ import io
5
+ import random
6
+ import secrets
7
+ import time
8
+
9
+ from django.contrib.auth import login as auth_login, logout as auth_logout, update_session_auth_hash
10
+ from django.contrib.auth.forms import AuthenticationForm, PasswordChangeForm
11
+ from django.views.decorators.debug import sensitive_post_parameters
12
+ from django.db import transaction
13
+ from django.views.decorators.cache import never_cache
14
+
15
+ from ..models import SiteConfig
16
+ from .base import body_errors, json_err, json_ok, read_body, staff_required
17
+ from .accounts import csrf_payload, identity_payload
18
+
19
+ CAPTCHA_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
20
+
21
+
22
+ def _captcha_png(code):
23
+ """Pillow 生成验证码图(干扰线 + 噪点 + 字符),返回 base64 PNG"""
24
+ from PIL import Image, ImageDraw, ImageFilter, ImageFont
25
+
26
+ w, h = 168, 52
27
+ img = Image.new("RGB", (w, h), (247, 248, 250))
28
+ draw = ImageDraw.Draw(img)
29
+
30
+ def rc(dark=False):
31
+ if dark:
32
+ return (random.randint(35, 85), random.randint(45, 95), random.randint(110, 190))
33
+ return (random.randint(130, 205), random.randint(145, 215), random.randint(165, 230))
34
+
35
+ for _ in range(5):
36
+ draw.line(
37
+ [(random.randint(0, w), random.randint(0, h)), (random.randint(0, w), random.randint(0, h))],
38
+ fill=rc(),
39
+ width=2,
40
+ )
41
+ for _ in range(70):
42
+ draw.point((random.randint(0, w), random.randint(0, h)), fill=rc())
43
+
44
+ font = None
45
+ for fp in (
46
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
47
+ "/System/Library/Fonts/Supplemental/Arial Bold.ttf",
48
+ "/System/Library/Fonts/Helvetica.ttc",
49
+ ):
50
+ try:
51
+ font = ImageFont.truetype(fp, 30)
52
+ break
53
+ except Exception:
54
+ continue
55
+ if font is None:
56
+ try:
57
+ font = ImageFont.load_default(size=30)
58
+ except TypeError:
59
+ font = ImageFont.load_default()
60
+ for i, ch in enumerate(code):
61
+ draw.text(
62
+ (16 + i * 36 + random.randint(-2, 2), 9 + random.randint(-3, 3)),
63
+ ch,
64
+ fill=rc(dark=True),
65
+ font=font,
66
+ )
67
+ img = img.filter(ImageFilter.SMOOTH)
68
+ buf = io.BytesIO()
69
+ img.save(buf, format="PNG")
70
+ return base64.b64encode(buf.getvalue()).decode()
71
+
72
+
73
+ def _captcha_code():
74
+ return ''.join(secrets.choice(CAPTCHA_CHARS) for _ in range(4))
75
+
76
+
77
+ @never_cache
78
+ def captcha(request):
79
+ """A single-use image challenge, bound to the session and limited in time."""
80
+ if request.method != 'GET': return json_err('仅支持 GET', status=405)
81
+ from django.conf import settings
82
+ timeout = max(1, int(getattr(settings, 'ORDLOOM_CAPTCHA_TIMEOUT', 180)))
83
+ code = _captcha_code()
84
+ request.session['ordloom_captcha'] = {'code': code, 'expires_at': time.time() + timeout}
85
+ return json_ok({'image': 'data:image/png;base64,' + _captcha_png(code), 'expires_in': timeout})
86
+
87
+
88
+ @never_cache
89
+ @staff_required
90
+ def me(request):
91
+ if request.method != 'GET': return json_err('仅支持 GET', status=405)
92
+ return json_ok(identity_payload(request.user, request))
93
+
94
+
95
+ @never_cache
96
+ @sensitive_post_parameters('password', 'captcha', 'totp', 'recovery_code')
97
+ @body_errors
98
+ def login(request):
99
+ if request.method != 'POST': return json_err('仅支持 POST', status=405)
100
+ body = read_body(request)
101
+ enabled = SiteConfig.load().login_captcha
102
+ context = {'captcha_required': enabled}
103
+ if enabled:
104
+ challenge = request.session.pop('ordloom_captcha', None)
105
+ supplied = body.get('captcha')
106
+ if not isinstance(challenge, dict) or challenge.get('expires_at', 0) <= time.time():
107
+ return json_err('验证码已过期,请刷新后重试', errors={'captcha': ['请刷新验证码']}, context=context)
108
+ if not isinstance(supplied, str) or not secrets.compare_digest(supplied.strip().upper().encode(), challenge['code'].encode()):
109
+ return json_err('验证码错误', errors={'captcha': ['请输入图片中的验证码']}, context=context)
110
+ # 登录 IP 白名单:配置 ORDLOOM_LOGIN_IP_ALLOWLIST 后,未命中 REMOTE_ADDR 的尝试一律拒绝
111
+ from django.conf import settings as dj_settings
112
+ allowlist = getattr(dj_settings, 'ORDLOOM_LOGIN_IP_ALLOWLIST', [])
113
+ if allowlist:
114
+ from .totp import ip_allowed
115
+ if not ip_allowed(request.META.get('REMOTE_ADDR', ''), allowlist):
116
+ return json_err('当前网络环境不允许登录', status=403, context=context)
117
+ username, password = body.get('username'), body.get('password')
118
+ if not isinstance(username, str) or not isinstance(password, str) or len(password) > 4096:
119
+ return json_err('请输入有效的账号和密码', context=context)
120
+ # 连续失败锁定:同一账号短时间多次失败后暂停接受尝试(共享 cache,多实例一致)。
121
+ import hashlib
122
+ lockout = 'su-login-fail:' + hashlib.sha256(username.strip().lower().encode()).hexdigest()
123
+ from .rate_limit import is_locked, record_failure, reset_failures
124
+ if is_locked(lockout):
125
+ return json_err('尝试次数过多,账号已暂时锁定,请 15 分钟后再试', status=429, context=context)
126
+ form = AuthenticationForm(request, data={'username': username, 'password': password})
127
+ if not form.is_valid():
128
+ record_failure(lockout, 900)
129
+ return json_err('账号或密码错误,请检查后重试', context=context)
130
+ user = form.get_user()
131
+ if not (user.is_staff or user.is_superuser):
132
+ return json_err('该账号没有工作台访问权限', status=403, context=context)
133
+ # Re-read and lock MFA state; recovery consumption and login share a transaction.
134
+ try:
135
+ with transaction.atomic():
136
+ from ..account_security import consume_code, locked_security, audit
137
+ security = locked_security(user)
138
+ if not secrets.compare_digest(user.get_session_auth_hash(), security.user.get_session_auth_hash()):
139
+ record_failure(lockout, 900)
140
+ return json_err('账号或密码已变化,请重新登录', context=context)
141
+ backend = getattr(user, 'backend', None)
142
+ user = security.user
143
+ recovered = False
144
+ if security.totp_enabled:
145
+ mfa_lockout = 'su-login-mfa:' + hashlib.sha256(str(user.pk).encode()).hexdigest()
146
+ if is_locked(mfa_lockout):
147
+ return json_err('尝试次数过多,账号已暂时锁定,请 15 分钟后再试', status=429, context=context)
148
+ from .totp import verify as verify_totp
149
+ recovery = body.get('recovery_code')
150
+ code = body.get('totp')
151
+ valid = consume_code(security, recovery) if recovery and not code else (
152
+ not recovery and verify_totp(security.totp_secret, code))
153
+ if not valid:
154
+ record_failure(lockout, 900)
155
+ record_failure(mfa_lockout, 900)
156
+ return json_err('请输入有效的动态验证码或未使用的恢复码', errors={'totp': ['请完成两步验证']},
157
+ context={**context, 'totp_required': True})
158
+ recovered = bool(recovery)
159
+ reset_failures(mfa_lockout)
160
+ elif body.get('recovery_code'):
161
+ record_failure(lockout, 900)
162
+ return json_err('账号或安全验证码不正确', context=context)
163
+ reset_failures(lockout)
164
+ auth_login(request, user, backend=backend)
165
+ if recovered:
166
+ audit(user, '使用两步验证恢复码登录')
167
+ from ..notifications import notify
168
+ notify(user, '恢复码已用于登录', '您的账号刚刚使用了一次性恢复码登录,两步验证仍保持开启。',
169
+ category='security', level='warning', target={'kind':'security'})
170
+ return json_ok(identity_payload(user, request))
171
+ except Exception:
172
+ return json_err('登录暂不可用,请稍后重试', status=503, context=context)
173
+
174
+
175
+
176
+ @never_cache
177
+ def logout(request):
178
+ if request.method != 'POST': return json_err('仅支持 POST', status=405)
179
+ auth_logout(request)
180
+ return json_ok(csrf_payload(request))
181
+
182
+
183
+ @never_cache
184
+ @staff_required
185
+ @sensitive_post_parameters('old', 'new1', 'new2')
186
+ def password_change(request):
187
+ """Use Django's password form and validators, retaining the authenticated session."""
188
+ if request.method != 'POST': return json_err('仅支持 POST', status=405)
189
+ if not request.user.has_usable_password():
190
+ return json_err('此账号使用统一身份认证,请在身份服务中修改密码', status=403)
191
+ body = read_body(request)
192
+ names = {'old_password': 'old', 'new_password1': 'new1', 'new_password2': 'new2'}
193
+ for key in names.values():
194
+ if not isinstance(body.get(key), str) or len(body[key]) > 4096:
195
+ return json_err('请输入有效的密码', errors={key: ['请填写密码,最多 4096 个字符']})
196
+ form = PasswordChangeForm(request.user, {name: body[key] for name, key in names.items()})
197
+ if not form.is_valid():
198
+ errors = {}
199
+ for key, failures in form.errors.as_data().items():
200
+ for failure in failures:
201
+ field = names.get(key, key)
202
+ if key == 'new_password2' and failure.code not in ('password_mismatch', 'required'):
203
+ field = 'new1'
204
+ from .password_fields import redact_form_text
205
+ errors.setdefault(field, []).extend(redact_form_text(form, message) for message in failure.messages)
206
+ return json_err('请检查标记的密码字段', errors=errors)
207
+ try:
208
+ with transaction.atomic():
209
+ from ..account_security import locked_security
210
+ current = locked_security(request.user).user
211
+ if not secrets.compare_digest(current.get_session_auth_hash(), request.user.get_session_auth_hash()):
212
+ return json_err('账号密码已变化,请重新登录后再修改', status=409)
213
+ form.save()
214
+ from ..notifications import notify
215
+ notify(request.user, '账号密码已修改', '您的账号密码已修改,请确认是您本人操作。',
216
+ category='security', level='warning', target={'kind':'security'})
217
+ update_session_auth_hash(request, request.user)
218
+ from ..session_devices import revoke_others
219
+ revoke_others(request, 'password_changed')
220
+ except Exception:
221
+ import logging
222
+ logging.getLogger(__name__).exception('Account password update failed')
223
+ return json_err('密码暂时无法修改,请稍后重试', status=500)
224
+ return json_ok(csrf_payload(request))
ordloom/api/base.py ADDED
@@ -0,0 +1,113 @@
1
+ """API 基础设施:JSON 响应、权限装饰器、Admin 注册表查找"""
2
+
3
+ import json
4
+ from functools import wraps
5
+
6
+ from django.contrib import admin
7
+ from django.apps import apps
8
+ from django.http import Http404, JsonResponse
9
+ from django.test import RequestFactory
10
+
11
+ _perm_factory = RequestFactory()
12
+
13
+
14
+ def json_ok(data=None):
15
+ return JsonResponse({"ok": True, "data": data or {}})
16
+
17
+
18
+ def json_err(message, status=400, errors=None, context=None):
19
+ payload = {"ok": False, "error": message}
20
+ if errors:
21
+ payload["errors"] = errors
22
+ if context:
23
+ payload['context'] = context
24
+ return JsonResponse(payload, status=status)
25
+
26
+
27
+ class InvalidRequestBody(ValueError):
28
+ def __init__(self, message, status=400):
29
+ super().__init__(message)
30
+ self.status = status
31
+
32
+
33
+ def body_errors(view):
34
+ @wraps(view)
35
+ def wrapper(*args, **kwargs):
36
+ try: return view(*args, **kwargs)
37
+ except InvalidRequestBody as error: return json_err(str(error), status=error.status)
38
+ return wrapper
39
+
40
+
41
+ def is_json_request(request):
42
+ content_type = (request.content_type or '').lower()
43
+ return content_type == 'application/json' or content_type.endswith('+json')
44
+
45
+
46
+ def read_body(request):
47
+ if not is_json_request(request):
48
+ raise InvalidRequestBody('请使用 application/json 提交请求', status=415)
49
+ def invalid_constant(value):
50
+ raise ValueError('Non-finite JSON number')
51
+ try:
52
+ value = json.loads(request.body, parse_constant=invalid_constant)
53
+ except (ValueError, UnicodeDecodeError, RecursionError) as error:
54
+ raise InvalidRequestBody('请求 JSON 格式不合法,请检查后重试') from error
55
+ if not isinstance(value, dict): raise InvalidRequestBody('请求 JSON 必须是对象')
56
+ return value
57
+
58
+
59
+ def _abs_media_url(url):
60
+ """存储 URL 规范化:MEDIA_URL 可能未带前导斜杠(如 'media/'),
61
+ 浏览器会按当前页面路径解析导致裂图;统一补为绝对路径"""
62
+ if not url:
63
+ return url
64
+ if str(url).startswith(("http://", "https://", "/", "data:")):
65
+ return url
66
+ return "/" + url
67
+
68
+
69
+ def staff_required(view):
70
+ """要求已登录且 is_staff(is_superuser 视为 staff)"""
71
+
72
+ @wraps(view)
73
+ def wrapper(request, *args, **kwargs):
74
+ if not request.user.is_authenticated:
75
+ return json_err("未登录", status=401)
76
+ if not getattr(request.user, 'is_active', True):
77
+ return json_err('账号已停用,请联系管理员', status=403)
78
+ if not (request.user.is_staff or request.user.is_superuser):
79
+ return json_err("需要管理员(Staff)账号", status=403)
80
+ return view(request, *args, **kwargs)
81
+
82
+ return body_errors(wrapper)
83
+
84
+
85
+ def perm_request(user):
86
+ """构造用于 ModelAdmin 权限检查的最小 request(部分自定义 ModelAdmin 需要完整 request,此处尽力兼容)"""
87
+ req = _perm_factory.get("/ordloom/")
88
+ req.user = user
89
+ return req
90
+
91
+
92
+ def get_admin(model_key):
93
+ """'app_label.model_name' → (model, ModelAdmin);未注册到 Admin 的模型返回 404"""
94
+ try:
95
+ app_label, model_name = model_key.split(".", 1)
96
+ except ValueError:
97
+ raise Http404("模型标识不合法")
98
+ try:
99
+ model = apps.get_model(app_label, model_name)
100
+ except (LookupError, ValueError):
101
+ raise Http404("模型不存在")
102
+ madmin = admin.site._registry.get(model)
103
+ if madmin is None:
104
+ raise Http404("该模型未注册到 Django Admin")
105
+ return model, madmin
106
+
107
+
108
+ def readonly_names(madmin, preq):
109
+ """ModelAdmin.readonly_fields → 集合(尽力兼容)"""
110
+ try:
111
+ return set(madmin.get_readonly_fields(preq, None) or [])
112
+ except Exception:
113
+ return set()