1use std::sync::Arc;
34
35use axum::http::StatusCode;
36use axum::response::{IntoResponse, Response};
37use axum::routing::{get, post};
38use axum::Router;
39use serde::Deserialize;
40use tera::Tera;
41
42use crate::page::PageStatus;
43use crate::tree_ops::TreeError;
44
45pub mod admin_page;
46pub mod cms_admin;
47
48pub use handlers::add_chrome;
57pub use handlers::issue_password_reset_link;
58
59pub mod chooser;
60mod handlers;
61mod i18n;
62
63pub(crate) fn tr(headers: &axum::http::HeaderMap, source: &str) -> String {
66 i18n::tr(headers, source, &[])
67}
68pub(crate) mod members;
69pub use members::{authenticate_member, MemberLoginError};
70pub use i18n::extend_ui_catalog;
74pub mod model_admin;
75pub mod pagination;
76pub mod report;
77pub mod resources;
78mod route_perms;
79pub(crate) mod notifications;
80pub(crate) mod sites;
81pub(crate) mod help_center;
82pub(crate) mod site_theme;
83pub(crate) mod template_editor;
84pub use template_editor::CODENAME as TEMPLATE_EDIT_CODENAME;
87pub use notifications::CODENAME as NOTIFICATION_MANAGE_CODENAME;
90pub use sites::CODENAME as SITE_MANAGE_CODENAME;
93pub(crate) use template_editor::offerable as template_offerable;
96pub use handlers::ListQuery;
97pub(crate) use handlers::{
99 allowed_children_for, allowed_root_types, apply_page_edit, dedup_slug_under_parent,
100 media_picker_payload, slugify, store_media, upsert_page_translations, MediaPickerQuery,
101 PageEditActor, PageEditOutcome, PageEditRefusal,
102};
103
104#[derive(Clone)]
110pub(crate) struct AdminState {
111 pub(crate) tera: Arc<Tera>,
112 pub(crate) signing_secret: Arc<Vec<u8>>,
118 pub(crate) cache_invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
125 pub(crate) mailer: Option<Arc<dyn rustango::email::Mailer>>,
130 pub(crate) mailer_from: Arc<String>,
134}
135
136pub fn router(tera: Arc<Tera>) -> Router {
147 let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
148 crate::perf::instrument(router_with_state(AdminState {
149 tera,
150 signing_secret: Arc::new(secret),
151 cache_invalidator: crate::cache_invalidate::noop(),
152 mailer: None,
153 mailer_from: Arc::new(String::new()),
154 }))
155}
156
157pub fn router_with_invalidator(
162 tera: Arc<Tera>,
163 invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
164) -> Router {
165 let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
166 crate::task_queue::set_default_invalidator(Arc::clone(&invalidator));
168 router_with_state(AdminState {
169 tera,
170 signing_secret: Arc::new(secret),
171 cache_invalidator: invalidator,
172 mailer: None,
173 mailer_from: Arc::new(String::new()),
174 })
175}
176
177pub fn router_with_mailer(
183 tera: Arc<Tera>,
184 invalidator: Arc<dyn crate::cache_invalidate::PageCacheInvalidator>,
185 mailer: Arc<dyn rustango::email::Mailer>,
186 from_addr: impl Into<String>,
187) -> Router {
188 let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
189 crate::task_queue::set_default_invalidator(Arc::clone(&invalidator));
191 let from_addr: String = from_addr.into();
192 crate::task_queue::set_default_mailer(Arc::clone(&mailer), from_addr.clone());
194 router_with_state(AdminState {
195 tera,
196 signing_secret: Arc::new(secret),
197 cache_invalidator: invalidator,
198 mailer: Some(mailer),
199 mailer_from: Arc::new(from_addr),
200 })
201}
202
203pub fn public_router(tera: Arc<Tera>) -> Router {
219 public_router_inner(tera, None, String::new())
220}
221
222pub fn public_router_with_mailer(
227 tera: Arc<Tera>,
228 mailer: Arc<dyn rustango::email::Mailer>,
229 from_addr: impl Into<String>,
230) -> Router {
231 public_router_inner(tera, Some(mailer), from_addr.into())
232}
233
234fn public_router_inner(
235 tera: Arc<Tera>,
236 mailer: Option<Arc<dyn rustango::email::Mailer>>,
237 mailer_from: String,
238) -> Router {
239 let secret = crate::signing::derived_key(PASSWORD_RESET_KEY_PURPOSE);
240 let state = AdminState {
241 tera,
242 signing_secret: Arc::new(secret),
243 cache_invalidator: crate::cache_invalidate::noop(),
244 mailer,
245 mailer_from: Arc::new(mailer_from),
246 };
247 Router::new()
248 .route(
249 "/cms-admin/password-reset",
250 get(handlers::password_reset_request_form)
251 .post(handlers::password_reset_request_submit),
252 )
253 .route(
254 "/cms-admin/password-reset/confirm",
255 get(handlers::password_reset_confirm_form)
256 .post(handlers::password_reset_confirm_submit),
257 )
258 .route("/login", get(handlers::cms_login_form))
263 .route(
270 "/members/login",
271 get(members::member_login_form).post(members::member_login_submit),
272 )
273 .route(
274 "/members/signup",
275 get(members::member_signup_form).post(members::member_signup_submit),
276 )
277 .route("/members/logout", post(members::member_logout))
278 .route(
283 "/__cms-branding/logo",
284 get(handlers::settings_branding_serve_logo),
285 )
286 .route(
287 "/__cms-branding/favicon",
288 get(handlers::settings_branding_serve_favicon),
289 )
290 .route("/cms-admin/no-access", get(handlers::no_access_page))
294 .route("/cms-admin/static/cms.css", get(serve_cms_css))
298 .route("/cms-admin/static/fonts.css", get(serve_admin_fonts_css))
309 .route(
310 "/cms-admin/static/vendor/fonts/{file}",
311 get(serve_admin_font_file),
312 )
313 .route("/cms-admin/static/brand/{file}", get(serve_admin_brand_file))
317 .route("/cms-admin/static/cms-ux.js", get(serve_cms_ux_js))
318 .route(
319 "/cms-admin/static/stream_editor.js",
320 get(serve_stream_editor_js),
321 )
322 .route("/cms-admin/static/block_tree.js", get(serve_block_tree_js))
325 .route("/cms-admin/static/cms-preview.js", get(serve_cms_preview_js))
326 .route(
327 "/cms-admin/static/menu-builder.js",
328 get(serve_menu_builder_js),
329 )
330 .route(
332 "/cms-admin/static/form_builder.js",
333 get(serve_form_builder_js),
334 )
335 .route(
336 "/cms-admin/static/page_type_builder.js",
337 get(serve_page_type_builder_js),
338 )
339 .route(
341 "/cms-admin/static/page_builder_rules.js",
342 get(serve_page_builder_rules_js),
343 )
344 .route(
349 "/cms-admin/static/vendor/axe-core.min.js",
350 get(serve_axe_core_js),
351 )
352 .route(
356 "/cms-admin/static/cms-axe-preview.js",
357 get(serve_cms_axe_preview_js),
358 )
359 .route(
362 "/cms-admin/static/cms-preview-guard.js",
363 get(serve_cms_preview_guard_js),
364 )
365 .route(
368 "/cms-admin/static/template-editor.js",
369 get(serve_template_editor_js),
370 )
371 .route(
372 "/cms-admin/static/vendor/codemirror.bundle.js",
373 get(serve_codemirror_bundle_js),
374 )
375 .route(
376 "/cms-admin/static/vendor/tiptap.bundle.js",
377 get(serve_tiptap_bundle_js),
378 )
379 .route(
380 "/cms-admin/static/richtext-editor.js",
381 get(serve_richtext_editor_js),
382 )
383 .route(
385 "/cms-admin/static/vendor/THIRD-PARTY-NOTICES.txt",
386 get(serve_third_party_notices),
387 )
388 .route_layer(axum::middleware::from_fn(i18n::tenant_overrides_layer))
390 .with_state(state)
391}
392
393async fn serve_third_party_notices() -> impl axum::response::IntoResponse {
397 (
398 [(
399 axum::http::header::CONTENT_TYPE,
400 axum::http::HeaderValue::from_static("text/plain; charset=utf-8"),
401 )],
402 include_str!("static/vendor/THIRD-PARTY-NOTICES.txt"),
403 )
404}
405
406const PASSWORD_RESET_KEY_PURPOSE: &str = "rcms:password-reset";
409
410pub fn with_login_required(router: Router, login_url: impl Into<String> + 'static) -> Router {
439 use axum::middleware::{from_fn, Next};
440 let login_url: Arc<str> = Arc::from(login_url.into());
441 router.layer(from_fn(
442 move |req: axum::http::Request<axum::body::Body>, next: Next| {
443 let login_url = login_url.clone();
444 async move {
445 use axum::extract::FromRequestParts as _;
446 let (mut parts, body) = req.into_parts();
447 let user = rustango::extractors::SessionUser::from_request_parts(&mut parts, &())
448 .await
449 .unwrap_or(rustango::extractors::SessionUser(None));
450 if let Some(user) = user.0 {
451 let allowed = user.is_superuser
458 || parts.uri.path().starts_with("/cms-admin/static/")
459 || matches!(
460 check_codename(&mut parts, "cms_admin.access").await,
461 AccessResult::Allowed
462 );
463 if !allowed {
464 use axum::response::IntoResponse as _;
465 return axum::response::Redirect::to("/cms-admin/no-access").into_response();
466 }
467 let req = axum::http::Request::from_parts(parts, body);
468 return next.run(req).await;
469 }
470 let original = parts
474 .uri
475 .path_and_query()
476 .map(|p| p.as_str().to_owned())
477 .unwrap_or_else(|| "/".to_owned());
478 rustango::auth_decorators::redirect_to_login(&login_url, "next", &original)
479 }
480 },
481 ))
482}
483
484pub fn with_cms_admin_access(router: Router, no_access_url: impl Into<String>) -> Router {
499 with_codename_gate(router, "cms_admin.access", no_access_url)
500}
501
502pub fn with_codename_gate(
509 router: Router,
510 codename: &'static str,
511 no_access_url: impl Into<String>,
512) -> Router {
513 use axum::middleware::{from_fn, Next};
514 use axum::response::{IntoResponse, Redirect};
515 let no_access_url: Arc<str> = Arc::from(no_access_url.into());
516 router.layer(from_fn(
517 move |req: axum::http::Request<axum::body::Body>, next: Next| {
518 let no_access_url = no_access_url.clone();
519 async move {
520 let path = req.uri().path();
521 if path == &*no_access_url || path.starts_with("/cms-admin/static/") {
522 return next.run(req).await;
523 }
524 let (mut parts, body) = req.into_parts();
525 let outcome = check_codename(&mut parts, codename).await;
526 let req = axum::http::Request::from_parts(parts, body);
527 match outcome {
528 AccessResult::Allowed | AccessResult::DeniedNoUser => next.run(req).await,
529 AccessResult::Denied => Redirect::to(&no_access_url).into_response(),
530 }
531 }
532 },
533 ))
534}
535
536enum AccessResult {
537 Allowed,
538 Denied,
539 DeniedNoUser,
542}
543
544pub(crate) async fn codename_gate(
557 tenant: &rustango::extractors::Tenant,
558 user: Option<&rustango::tenancy::auth::User>,
559 codename: &str,
560) -> Option<axum::response::Response> {
561 use axum::response::{IntoResponse, Redirect};
562 let Some(user) = user else {
563 return Some(Redirect::to("/login").into_response());
564 };
565 if user.is_superuser {
566 return None;
567 }
568 let uid = user.id.get().copied().unwrap_or_default();
569 let codes = crate::permissions::user_codenames(tenant.pool(), uid)
570 .await
571 .unwrap_or_default();
572 if codes.contains(codename) {
573 None
574 } else {
575 Some(Redirect::to("/cms-admin/no-access").into_response())
576 }
577}
578
579async fn check_codename(parts: &mut axum::http::request::Parts, codename: &str) -> AccessResult {
580 let (user, pool) = match request_user_and_pool(parts).await {
581 Ok(Some(found)) => found,
582 Ok(None) => return AccessResult::DeniedNoUser,
583 Err(()) => return AccessResult::Denied,
584 };
585 if user.is_superuser {
586 return AccessResult::Allowed;
587 }
588 let uid = user.id.get().copied().unwrap_or_default();
589 let codenames = crate::permissions::user_codenames(&pool, uid)
590 .await
591 .unwrap_or_default();
592 if codenames.contains(codename) {
593 AccessResult::Allowed
594 } else {
595 AccessResult::Denied
596 }
597}
598
599pub(crate) async fn request_user_and_pool(
604 parts: &mut axum::http::request::Parts,
605) -> Result<Option<(rustango::tenancy::auth::User, rustango::sql::Pool)>, ()> {
606 use axum::extract::FromRequestParts as _;
607 use rustango::tenancy::OrgResolver as _;
608 use std::sync::Arc;
609
610 let Some(ctx) = parts
611 .extensions
612 .get::<Arc<rustango::extractors::TenantContext>>()
613 .cloned()
614 else {
615 return Ok(None);
616 };
617 let Ok(rustango::extractors::SessionUser(Some(user))) =
620 rustango::extractors::SessionUser::from_request_parts(parts, &()).await
621 else {
622 return Ok(None);
623 };
624 let Ok(Some(org)) = ctx.resolver.resolve(parts, &ctx.pools.registry_pool()).await else {
625 return Ok(None);
626 };
627 let pool = ctx.pools.scoped_pool_dyn(&org).await.map_err(|_| ())?;
628 Ok(Some((user, pool)))
629}
630
631fn router_with_state(state: AdminState) -> Router {
632 Router::new()
633 .route("/cms-admin", get(redirect_root))
635 .route("/cms-admin/", get(redirect_root))
636 .route("/cms-admin/pages", get(handlers::page_list))
637 .route(
638 "/cms-admin/pages/new",
639 get(handlers::page_new_form).post(handlers::page_new_submit),
640 )
641 .route(
642 "/cms-admin/pages/{id}/edit",
643 get(handlers::page_edit_form).post(handlers::page_edit_submit),
644 )
645 .route(
646 "/cms-admin/pages/{id}/translate",
647 post(handlers::page_translate_submit),
648 )
649 .route(
650 "/cms-admin/pages/{id}/delete",
651 post(handlers::page_delete_submit),
652 )
653 .route(
654 "/cms-admin/pages/{id}/preview",
655 get(handlers::page_preview).post(handlers::page_preview_draft),
656 )
657 .route(
659 "/cms-admin/pages/{id}/preview-token",
660 get(handlers::page_preview_token),
661 )
662 .route(
664 "/cms-admin/pages/{id}/revert/{rev_id}",
665 post(handlers::page_revert_submit),
666 )
667 .route(
669 "/cms-admin/pages/{id}/history/diff",
670 get(handlers::history_diff),
671 )
672 .route("/cms-admin/pages/{id}/log.csv", get(handlers::page_log_csv))
674 .route(
677 "/cms-admin/pages/{id}/permissions",
678 post(handlers::page_permissions_submit),
679 )
680 .route(
682 "/cms-admin/pages/{id}/move",
683 post(handlers::page_move_submit),
684 )
685 .route(
687 "/cms-admin/pages/{id}/clone",
688 post(handlers::page_clone_submit),
689 )
690 .route(
692 "/cms-admin/pages/{id}/alias",
693 post(handlers::page_alias_submit),
694 )
695 .route(
697 "/cms-admin/pages/{id}/privacy",
698 post(handlers::page_privacy_submit),
699 )
700 .route("/cms-admin/pages/bulk", post(handlers::page_bulk_submit))
704 .route(
706 "/cms-admin/pages/{id}/unlock",
707 post(handlers::page_unlock_submit),
708 )
709 .route(
712 "/cms-admin/pages/{id}/inline/{panel}/order",
713 post(handlers::inline_cards_order),
714 )
715 .route(
716 "/cms-admin/pages/{id}/inline/{panel}/{row}",
717 get(handlers::inline_card_body).post(handlers::inline_card_save),
718 )
719 .route(
720 "/cms-admin/pages/{id}/inline/{panel}/{row}/remove",
721 post(handlers::inline_card_remove),
722 )
723 .route(
724 "/cms-admin/pages/{id}/lock-release",
725 post(handlers::page_lock_release),
726 )
727 .route(
728 "/cms-admin/pages/{id}/lock-heartbeat",
729 post(handlers::page_lock_heartbeat),
730 )
731 .route(
733 "/cms-admin/pages/{id}/autosave",
734 post(handlers::page_autosave_submit),
735 )
736 .route(
738 "/cms-admin/pages/{id}/sessions",
739 get(handlers::page_sessions_json),
740 )
741 .route(
743 "/cms-admin/pages/{id}/subscribe",
744 post(handlers::page_subscribe_submit),
745 )
746 .route(
747 "/cms-admin/pages/{id}/unsubscribe",
748 post(handlers::page_unsubscribe_submit),
749 )
750 .route(
752 "/cms-admin/pages/{id}/comments/new",
753 post(handlers::comment_new_submit),
754 )
755 .route(
756 "/cms-admin/pages/{id}/comments/{comment_id}/reply",
757 post(handlers::comment_reply_submit),
758 )
759 .route(
760 "/cms-admin/pages/{id}/comments/{comment_id}/resolve",
761 post(handlers::comment_resolve_submit),
762 )
763 .route(
764 "/cms-admin/pages/{id}/comments/{comment_id}/reopen",
765 post(handlers::comment_reopen_submit),
766 )
767 .route(
769 "/cms-admin/pages/{id}/workflow/submit",
770 post(handlers::page_workflow_submit),
771 )
772 .route(
773 "/cms-admin/pages/{id}/workflow/approve",
774 post(handlers::page_workflow_approve),
775 )
776 .route(
777 "/cms-admin/pages/{id}/workflow/reject",
778 post(handlers::page_workflow_reject),
779 )
780 .route(
781 "/cms-admin/pages/{id}/workflow/cancel",
782 post(handlers::page_workflow_cancel),
783 )
784 .route("/cms-admin/library", get(handlers::library_list))
786 .route("/cms-admin/forms", get(handlers::forms_list))
790 .route("/cms-admin/set-language", post(handlers::admin_set_language))
792 .route(
795 "/cms-admin/forms/{id}/build",
796 get(handlers::form_build_form).post(handlers::form_build_submit),
797 )
798 .route(
801 "/cms-admin/forms/{id}/preview",
802 get(handlers::form_preview).post(handlers::form_preview_draft),
803 )
804 .route(
806 "/cms-admin/forms/{id}/publish",
807 post(handlers::form_publish_submit),
808 )
809 .route(
811 "/cms-admin/forms/{id}/submissions",
812 get(handlers::form_submissions_list),
813 )
814 .route(
815 "/cms-admin/forms/{id}/submissions/export.csv",
816 get(handlers::form_submissions_csv),
817 )
818 .route(
820 "/cms-admin/forms/{id}/submissions/file/{key}",
821 get(handlers::form_submission_file),
822 )
823 .route(
824 "/cms-admin/library/new",
825 get(handlers::snippet_new_form).post(handlers::snippet_create_submit),
826 )
827 .route(
828 "/cms-admin/library/{id}/edit",
829 get(handlers::snippet_edit_form).post(handlers::snippet_edit_submit),
830 )
831 .route(
833 "/cms-admin/library/{id}/translate",
834 post(handlers::snippet_translate_submit),
835 )
836 .route(
840 "/cms-admin/library/{type_name}/bulk",
841 post(handlers::library_bulk_submit),
842 )
843 .route(
844 "/cms-admin/library/{id}/delete",
845 post(handlers::snippet_delete_submit),
846 )
847 .route(
849 "/cms-admin/library/{id}/revert/{seq}",
850 post(handlers::snippet_revert_submit),
851 )
852 .route(
854 "/cms-admin/library/{type_name}/import",
855 get(handlers::snippet_import_form).post(handlers::snippet_import_submit),
856 )
857 .route("/cms-admin/media", get(handlers::media_list))
859 .route(
861 "/cms-admin/media/{id}/edit",
862 get(handlers::media_edit_form).post(handlers::media_edit_submit),
863 )
864 .route(
866 "/cms-admin/media/{id}/crop",
867 post(handlers::media_crop_submit),
868 )
869 .route(
871 "/cms-admin/media/{id}/replace",
872 post(handlers::media_replace_submit),
873 )
874 .route(
876 "/cms-admin/media/collections",
877 get(handlers::collections_list),
878 )
879 .route(
880 "/cms-admin/media/collections/new",
881 post(handlers::collections_create),
882 )
883 .route(
884 "/cms-admin/media/collections/{id}/edit",
885 post(handlers::collections_edit),
886 )
887 .route(
888 "/cms-admin/media/collections/{id}/delete",
889 post(handlers::collections_delete),
890 )
891 .route(
892 "/cms-admin/media/bulk-move-collection",
893 post(handlers::media_bulk_move_collection),
894 )
895 .route("/cms-admin/taxonomies", get(handlers::taxonomies_index))
898 .route("/cms-admin/taxonomies/{slug}", get(handlers::category_tree))
899 .route(
900 "/cms-admin/taxonomies/{slug}/categories/new",
901 get(handlers::category_new_form).post(handlers::category_create),
902 )
903 .route(
904 "/cms-admin/taxonomies/{slug}/categories/{id}/edit",
905 get(handlers::category_edit_form).post(handlers::category_update),
906 )
907 .route(
908 "/cms-admin/taxonomies/{slug}/categories/{id}/delete",
909 post(handlers::category_delete),
910 )
911 .route(
913 "/cms-admin/taxonomies/{slug}/categories/{id}/translate",
914 post(handlers::category_translate_submit),
915 )
916 .route(
918 "/cms-admin/media/collections/{id}/permissions",
919 get(handlers::collection_permissions_form)
920 .post(handlers::collection_permissions_submit),
921 )
922 .route(
924 "/cms-admin/media/collections/{id}/privacy",
925 post(handlers::collection_privacy_submit),
926 )
927 .route(
930 "/cms-admin/media/unused",
931 get(handlers::media_unused_report),
932 )
933 .route(
934 "/cms-admin/media/unused/delete",
935 post(handlers::media_unused_bulk_delete),
936 )
937 .route(
938 "/cms-admin/media/upload",
939 get(handlers::media_upload_form).post(handlers::media_upload_submit),
940 )
941 .route(
945 "/cms-admin/media/upload-staged",
946 post(handlers::media_upload_staged)
947 .route_layer(axum::extract::DefaultBodyLimit::max(50 * 1024 * 1024)),
948 )
949 .route(
950 "/cms-admin/media/upload-staged/{id}/cancel",
951 post(handlers::media_upload_staged_cancel),
952 )
953 .route(
955 "/cms-admin/media/upload-staged/commit",
956 post(handlers::media_upload_staged_commit),
957 )
958 .route(
959 "/cms-admin/media/{id}/delete",
960 post(handlers::media_delete_submit),
961 )
962 .route("/cms-admin/documents", get(handlers::documents_list))
963 .route("/cms-admin/model/{slug}", get(handlers::model_admin_list))
965 .route("/cms-admin/report/{slug}", get(handlers::report_view))
968 .route(
972 "/cms-admin/__chooser/{slug}",
973 get(handlers::chooser_search_json),
974 )
975 .route(
979 "/cms-admin/__media-picker",
980 get(handlers::media_picker_json),
981 )
982 .route("/cms-admin/sso-providers", get(handlers::sso_provider_list))
984 .route(
985 "/cms-admin/sso-providers/new",
986 get(handlers::sso_provider_new_form).post(handlers::sso_provider_new_submit),
987 )
988 .route(
989 "/cms-admin/sso-providers/{id}/edit",
990 get(handlers::sso_provider_edit_form).post(handlers::sso_provider_edit_submit),
991 )
992 .route(
993 "/cms-admin/sso-providers/{id}/delete",
994 post(handlers::sso_provider_delete_submit),
995 )
996 .route("/cms-admin/locales", get(handlers::locale_list))
998 .route(
999 "/cms-admin/locales/new",
1000 get(handlers::locale_new_form).post(handlers::locale_new_submit),
1001 )
1002 .route(
1003 "/cms-admin/locales/{id}/edit",
1004 get(handlers::locale_edit_form).post(handlers::locale_edit_submit),
1005 )
1006 .route(
1007 "/cms-admin/locales/{id}/delete",
1008 post(handlers::locale_delete_submit),
1009 )
1010 .route("/cms-admin/search", get(handlers::admin_search))
1014 .route(
1017 "/cms-admin/site-settings",
1018 get(handlers::site_settings_list),
1019 )
1020 .route(
1021 "/cms-admin/site-settings/{scope}/edit",
1022 get(handlers::site_setting_edit_form).post(handlers::site_setting_edit_submit),
1023 )
1024 .route(
1025 "/cms-admin/site-settings/{scope}/delete",
1026 post(handlers::site_setting_delete_submit),
1027 )
1028 .route(
1030 "/cms-admin/site-settings/{scope}/translate",
1031 post(handlers::site_setting_translate_submit),
1032 )
1033 .route("/cms-admin/templates", get(template_editor::list))
1036 .route(
1037 "/cms-admin/templates/edit",
1038 get(template_editor::edit_form).post(template_editor::save),
1039 )
1040 .route("/cms-admin/templates/new", post(template_editor::create))
1041 .route(
1042 "/cms-admin/templates/validate",
1043 post(template_editor::validate),
1044 )
1045 .route("/cms-admin/templates/delete", post(template_editor::delete))
1046 .route("/cms-admin/help", get(help_center::index))
1050 .route("/cms-admin/help/{slug}", get(help_center::guide))
1051 .route("/cms-admin/site-theme", get(site_theme::index))
1052 .route("/cms-admin/site-theme/download", get(site_theme::download))
1053 .route(
1054 "/cms-admin/site-theme/upload",
1055 post(site_theme::upload).route_layer(axum::extract::DefaultBodyLimit::max(10 * 1024 * 1024)),
1056 )
1057 .route("/cms-admin/site-theme/preview", get(site_theme::preview_page))
1058 .route("/cms-admin/site-theme/install", post(site_theme::install))
1059 .route("/cms-admin/site-theme/restore", post(site_theme::restore))
1060 .route(
1063 "/cms-admin/page-types/{id}/template",
1064 get(template_editor::assign_form).post(template_editor::assign_save),
1065 )
1066 .route("/cms-admin/analytics", get(handlers::analytics_dashboard))
1067 .route(
1068 "/cms-admin/reports/aging",
1069 get(handlers::aging_pages_report),
1070 )
1071 .route(
1072 "/cms-admin/reports/aging.csv",
1073 get(handlers::aging_pages_csv),
1074 )
1075 .route(
1076 "/cms-admin/reports/locked-pages",
1077 get(handlers::locked_pages_report),
1078 )
1079 .route(
1080 "/cms-admin/reports/locked-pages.csv",
1081 get(handlers::locked_pages_csv),
1082 )
1083 .route(
1084 "/cms-admin/reports/workflows",
1085 get(handlers::workflows_report),
1086 )
1087 .route(
1088 "/cms-admin/reports/workflows.csv",
1089 get(handlers::workflows_report_csv),
1090 )
1091 .route(
1093 "/cms-admin/reports/revisions",
1094 get(handlers::revisions_report),
1095 )
1096 .route(
1097 "/cms-admin/reports/revisions/prune",
1098 post(handlers::revisions_report_prune),
1099 )
1100 .route(
1102 "/cms-admin/reports/scheduled",
1103 get(handlers::scheduled_report),
1104 )
1105 .route(
1106 "/cms-admin/reports/scheduled.csv",
1107 get(handlers::scheduled_report_csv),
1108 )
1109 .route(
1111 "/cms-admin/reports/search",
1112 get(handlers::search_promotions_report),
1113 )
1114 .route(
1115 "/cms-admin/reports/search/{id}/edit",
1116 get(handlers::search_promotion_edit_form).post(handlers::search_promotion_edit_submit),
1117 )
1118 .route("/cms-admin/workflows", get(handlers::workflows_list))
1119 .route(
1120 "/cms-admin/workflows/new",
1121 get(handlers::workflow_new_form).post(handlers::workflow_new_submit),
1122 )
1123 .route(
1124 "/cms-admin/workflows/{id}/edit",
1125 get(handlers::workflow_edit_form).post(handlers::workflow_edit_submit),
1126 )
1127 .route(
1128 "/cms-admin/workflows/{id}/delete",
1129 post(handlers::workflow_delete_submit),
1130 )
1131 .route(
1132 "/cms-admin/workflows/{id}/tasks/add",
1133 post(handlers::workflow_task_add),
1134 )
1135 .route(
1136 "/cms-admin/workflows/{id}/tasks/{task_id}/delete",
1137 post(handlers::workflow_task_delete),
1138 )
1139 .route("/cms-admin/notifications", get(notifications::list))
1144 .route("/cms-admin/notifications/new", post(notifications::create))
1145 .route(
1146 "/cms-admin/notifications/{id}/toggle",
1147 post(notifications::toggle),
1148 )
1149 .route(
1150 "/cms-admin/notifications/{id}/delete",
1151 post(notifications::delete),
1152 )
1153 .route(
1154 "/cms-admin/notifications/deliveries/{id}/retry",
1155 post(notifications::retry_delivery),
1156 )
1157 .route("/cms-admin/sites", get(sites::list))
1162 .route("/cms-admin/sites/new", post(sites::add))
1163 .route("/cms-admin/sites/root", post(sites::set_root))
1164 .route("/cms-admin/sites/toggle", post(sites::toggle))
1165 .route("/cms-admin/sites/delete", post(sites::remove))
1166 .route("/cms-admin/redirects", get(handlers::redirect_list))
1167 .route(
1168 "/cms-admin/redirects/new",
1169 get(handlers::redirect_new_form).post(handlers::redirect_new_submit),
1170 )
1171 .route(
1172 "/cms-admin/redirects/{id}/edit",
1173 get(handlers::redirect_edit_form).post(handlers::redirect_edit_submit),
1174 )
1175 .route(
1176 "/cms-admin/redirects/{id}/delete",
1177 post(handlers::redirect_delete_submit),
1178 )
1179 .route(
1181 "/cms-admin/redirects/{id}/enable",
1182 post(handlers::redirect_enable_submit),
1183 )
1184 .route(
1186 "/cms-admin/redirects/import",
1187 get(handlers::redirect_import_form).post(handlers::redirect_import_submit),
1188 )
1189 .route(
1191 "/cms-admin/redirects/export.csv",
1192 get(handlers::redirect_export_csv),
1193 )
1194 .route("/cms-admin/users", get(handlers::users_list))
1196 .route("/cms-admin/users/bulk", post(handlers::users_bulk_submit))
1198 .route(
1199 "/cms-admin/users/new",
1200 get(handlers::users_new_form).post(handlers::users_create_submit),
1201 )
1202 .route(
1203 "/cms-admin/users/{id}/edit",
1204 get(handlers::users_edit_form).post(handlers::users_edit_submit),
1205 )
1206 .route(
1207 "/cms-admin/users/{id}/deactivate",
1208 post(handlers::users_deactivate_submit),
1209 )
1210 .route("/cms-admin/security-log", get(handlers::security_log_page))
1212 .route("/cms-admin/roles", get(handlers::roles_list))
1213 .route(
1215 "/cms-admin/permissions",
1216 get(handlers::permissions_overview),
1217 )
1218 .route(
1219 "/cms-admin/roles/new",
1220 get(handlers::roles_new_form).post(handlers::roles_create_submit),
1221 )
1222 .route(
1223 "/cms-admin/roles/{id}/edit",
1224 get(handlers::roles_edit_form).post(handlers::roles_edit_submit),
1225 )
1226 .route(
1227 "/cms-admin/roles/{id}/delete",
1228 post(handlers::roles_delete_submit),
1229 )
1230 .route("/cms-admin/navigation", get(handlers::navigation_list))
1232 .route(
1233 "/cms-admin/navigation/new",
1234 post(handlers::navigation_create_submit),
1235 )
1236 .route(
1237 "/cms-admin/navigation/{id}/delete",
1238 post(handlers::navigation_delete_submit),
1239 )
1240 .route(
1241 "/cms-admin/navigation/{id}/clone",
1242 post(handlers::navigation_clone_submit),
1243 )
1244 .route(
1245 "/cms-admin/navigation/{id}/save-tree",
1246 post(handlers::navigation_save_tree_submit),
1247 )
1248 .route(
1253 "/cms-admin/navigation/{id}/seed-from-pages",
1254 post(handlers::navigation_seed_from_pages_submit),
1255 )
1256 .route(
1257 "/cms-admin/navigation/{id}/edit",
1258 get(handlers::navigation_edit_form),
1259 )
1260 .route(
1261 "/cms-admin/navigation/{id}/translate",
1262 post(handlers::navigation_translate_submit),
1263 )
1264 .route(
1265 "/cms-admin/navigation/{id}/items",
1266 post(handlers::navigation_item_create),
1267 )
1268 .route(
1269 "/cms-admin/navigation/{menu_id}/items/{id}/delete",
1270 post(handlers::navigation_item_delete),
1271 )
1272 .route("/cms-admin/history", get(handlers::history_page))
1274 .route("/cms-admin/page-types", get(handlers::page_types_dashboard))
1276 .route(
1278 "/cms-admin/page-types/new",
1279 get(handlers::page_type_new_form).post(handlers::page_type_create),
1280 )
1281 .route(
1282 "/cms-admin/page-types/{id}/edit",
1283 get(handlers::page_type_edit_form).post(handlers::page_type_update),
1284 )
1285 .route(
1286 "/cms-admin/page-types/{id}/delete",
1287 post(handlers::page_type_delete),
1288 )
1289 .route(
1291 "/cms-admin/page-types/{id}/build",
1292 get(handlers::page_type_build_form).post(handlers::page_type_build_submit),
1293 )
1294 .route(
1295 "/cms-admin/page-types/{id}/build/publish",
1296 post(handlers::page_type_publish_submit),
1297 )
1298 .route(
1300 "/cms-admin/page-types/{id}/translate",
1301 get(handlers::page_type_translate_form).post(handlers::page_type_translate_submit),
1302 )
1303 .route("/cms-admin/components", get(handlers::components_index))
1305 .route(
1306 "/cms-admin/components/new",
1307 get(handlers::component_new_form).post(handlers::component_create),
1308 )
1309 .route(
1310 "/cms-admin/components/{id}/edit",
1311 get(handlers::component_edit_form).post(handlers::component_update),
1312 )
1313 .route(
1314 "/cms-admin/components/{id}/delete",
1315 post(handlers::component_delete),
1316 )
1317 .route("/cms-admin/settings", get(handlers::settings_page))
1319 .route(
1321 "/cms-admin/settings/branding",
1322 post(handlers::settings_branding_submit),
1323 )
1324 .route(
1329 "/cms-admin/settings/theme",
1330 post(handlers::settings_theme_switch),
1331 )
1332 .route("/cms-admin/me", get(handlers::account_preferences))
1335 .route(
1337 "/cms-admin/__page-chooser",
1338 get(handlers::page_chooser_json),
1339 )
1340 .route(
1342 "/cms-admin/__snippet-chooser",
1343 get(handlers::snippet_chooser_json),
1344 )
1345 .route(
1346 "/cms-admin/__document-chooser",
1347 get(handlers::document_chooser_json),
1348 )
1349 .route(
1352 "/cms-admin/me/notifications",
1353 post(handlers::account_notifications_submit),
1354 )
1355 .route(
1357 "/cms-admin/me/profile",
1358 post(handlers::account_profile_submit),
1359 )
1360 .route(
1362 "/cms-admin/me/language",
1363 post(handlers::account_language_submit),
1364 )
1365 .route(
1367 "/cms-admin/me/show-templates",
1368 post(handlers::account_show_templates_submit),
1369 )
1370 .route("/cms-admin/me/email", post(handlers::account_email_submit))
1372 .route(
1373 "/cms-admin/me/email/confirm",
1374 get(handlers::account_email_confirm),
1375 )
1376 .route(
1377 "/cms-admin/me/password",
1378 post(handlers::account_password_submit),
1379 )
1380 .route(
1383 "/cms-admin/me/mcp-keys",
1384 post(handlers::account_mcp_key_create),
1385 )
1386 .route(
1387 "/cms-admin/me/mcp-keys/{id}/revoke",
1388 post(handlers::account_mcp_key_revoke),
1389 )
1390 .route(
1394 "/cms-admin/users/{id}/mcp-keys",
1395 post(handlers::users_mcp_key_create),
1396 )
1397 .route(
1398 "/cms-admin/users/{id}/mcp-keys/{key_id}/revoke",
1399 post(handlers::users_mcp_key_revoke),
1400 )
1401 .route(
1405 "/__cms-avatar/{user_id}",
1406 get(handlers::account_avatar_serve),
1407 )
1408 .route("/cms-admin/styleguide", get(handlers::styleguide))
1410 .route("/cms-admin/dashboard", get(handlers::dashboard))
1412 .route(
1414 "/cms-admin/dismissibles/{key}",
1415 post(handlers::dismissible_submit),
1416 )
1417 .route("/cms-admin/logout", post(handlers::cms_logout_submit))
1425 .route(
1430 "/cms-admin/x/{slug}",
1431 get(handlers::admin_page_dispatch).post(handlers::admin_page_dispatch),
1432 )
1433 .route(
1434 "/cms-admin/x/{slug}/{action}",
1435 get(handlers::admin_page_dispatch).post(handlers::admin_page_dispatch),
1436 )
1437 .route_layer(axum::middleware::from_fn(route_perms::gate))
1440 .route_layer(axum::middleware::from_fn(i18n::tenant_overrides_layer))
1442 .route_layer(axum::middleware::from_fn(crate::seed::lazy_seed_layer))
1445 .with_state(state)
1446}
1447
1448async fn redirect_root() -> axum::response::Redirect {
1449 axum::response::Redirect::permanent("/cms-admin/dashboard")
1451}
1452
1453fn immutable_asset<B: axum::response::IntoResponse>(
1458 content_type: &'static str,
1459 body: B,
1460) -> axum::response::Response {
1461 use axum::response::IntoResponse as _;
1462 (
1463 [
1464 (
1465 axum::http::header::CONTENT_TYPE,
1466 axum::http::HeaderValue::from_static(content_type),
1467 ),
1468 (
1469 axum::http::header::CACHE_CONTROL,
1470 axum::http::HeaderValue::from_static("public, max-age=31536000, immutable"),
1471 ),
1472 ],
1473 body,
1474 )
1475 .into_response()
1476}
1477
1478async fn serve_stream_editor_js() -> impl axum::response::IntoResponse {
1480 immutable_asset("text/javascript; charset=utf-8", include_str!("static/stream_editor.js"))
1481}
1482
1483async fn serve_cms_preview_js() -> impl axum::response::IntoResponse {
1487 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-preview.js"))
1488}
1489
1490async fn serve_block_tree_js() -> impl axum::response::IntoResponse {
1492 immutable_asset("text/javascript; charset=utf-8", include_str!("static/block_tree.js"))
1493}
1494
1495async fn serve_cms_ux_js() -> impl axum::response::IntoResponse {
1501 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-ux.js"))
1502}
1503
1504async fn serve_menu_builder_js() -> impl axum::response::IntoResponse {
1508 immutable_asset("text/javascript; charset=utf-8", include_str!("static/menu-builder.js"))
1509}
1510
1511async fn serve_form_builder_js() -> impl axum::response::IntoResponse {
1514 immutable_asset("text/javascript; charset=utf-8", include_str!("static/form_builder.js"))
1515}
1516
1517async fn serve_page_type_builder_js() -> impl axum::response::IntoResponse {
1518 immutable_asset("text/javascript; charset=utf-8", include_str!("static/page_type_builder.js"))
1519}
1520
1521async fn serve_page_builder_rules_js() -> impl axum::response::IntoResponse {
1522 immutable_asset("text/javascript; charset=utf-8", include_str!("static/page_builder_rules.js"))
1523}
1524
1525async fn serve_axe_core_js() -> impl axum::response::IntoResponse {
1530 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/axe-core.min.js"))
1531}
1532
1533async fn serve_cms_axe_preview_js() -> impl axum::response::IntoResponse {
1539 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-axe-preview.js"))
1540}
1541
1542async fn serve_cms_preview_guard_js() -> impl axum::response::IntoResponse {
1547 immutable_asset("text/javascript; charset=utf-8", include_str!("static/cms-preview-guard.js"))
1548}
1549
1550const ADMIN_FONT_FILES: &[(&str, &[u8])] = &[
1563 (
1564 "icons-00.woff2",
1565 include_bytes!("static/vendor/fonts/icons-00.woff2"),
1566 ),
1567 (
1568 "text-00.woff2",
1569 include_bytes!("static/vendor/fonts/text-00.woff2"),
1570 ),
1571 (
1572 "text-02.woff2",
1573 include_bytes!("static/vendor/fonts/text-02.woff2"),
1574 ),
1575 (
1576 "text-03.woff2",
1577 include_bytes!("static/vendor/fonts/text-03.woff2"),
1578 ),
1579 (
1580 "text-16.woff2",
1581 include_bytes!("static/vendor/fonts/text-16.woff2"),
1582 ),
1583 (
1584 "text-17.woff2",
1585 include_bytes!("static/vendor/fonts/text-17.woff2"),
1586 ),
1587 (
1588 "text-21.woff2",
1589 include_bytes!("static/vendor/fonts/text-21.woff2"),
1590 ),
1591 (
1592 "text-22.woff2",
1593 include_bytes!("static/vendor/fonts/text-22.woff2"),
1594 ),
1595];
1596
1597async fn serve_admin_fonts_css() -> impl axum::response::IntoResponse {
1600 immutable_asset("text/css; charset=utf-8", include_str!("static/vendor/fonts/fonts.css"))
1601}
1602
1603async fn serve_admin_font_file(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
1606 match ADMIN_FONT_FILES.iter().find(|(name, _)| *name == file) {
1607 Some((_, bytes)) => immutable_asset("font/woff2", *bytes)
1608 .into_response(),
1609 None => (axum::http::StatusCode::NOT_FOUND, "unknown font").into_response(),
1610 }
1611}
1612
1613const ADMIN_BRAND_FILES: &[(&str, &str, &[u8])] = &[
1617 ("logo-light.png", "image/png", include_bytes!("static/brand/logo-light.png")),
1618 ("logo-dark.png", "image/png", include_bytes!("static/brand/logo-dark.png")),
1619 ("icon-light.png", "image/png", include_bytes!("static/brand/icon-light.png")),
1620 ("icon-dark.png", "image/png", include_bytes!("static/brand/icon-dark.png")),
1621 ("favicon.ico", "image/x-icon", include_bytes!("static/brand/favicon.ico")),
1622 ("apple-touch-icon.png", "image/png", include_bytes!("static/brand/apple-touch-icon.png")),
1623];
1624
1625async fn serve_admin_brand_file(axum::extract::Path(file): axum::extract::Path<String>) -> Response {
1626 match ADMIN_BRAND_FILES.iter().find(|(name, _, _)| *name == file) {
1627 Some((_, content_type, bytes)) => immutable_asset(content_type, *bytes).into_response(),
1628 None => (axum::http::StatusCode::NOT_FOUND, "unknown brand file").into_response(),
1629 }
1630}
1631
1632async fn serve_tiptap_bundle_js() -> impl axum::response::IntoResponse {
1637 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/tiptap.bundle.js"))
1638}
1639
1640async fn serve_template_editor_js() -> impl axum::response::IntoResponse {
1644 immutable_asset("text/javascript; charset=utf-8", include_str!("static/template-editor.js"))
1645}
1646
1647async fn serve_codemirror_bundle_js() -> impl axum::response::IntoResponse {
1651 immutable_asset("text/javascript; charset=utf-8", include_str!("static/vendor/codemirror.bundle.js"))
1652}
1653
1654async fn serve_richtext_editor_js() -> impl axum::response::IntoResponse {
1659 immutable_asset("text/javascript; charset=utf-8", include_str!("static/richtext-editor.js"))
1660}
1661
1662const BUNDLED_CMS_CSS: &str = include_str!("static/cms.css");
1666
1667async fn serve_cms_css() -> Response {
1675 let override_path = std::path::Path::new("static/cms_admin/cms.css");
1676 if override_path.exists() {
1677 match std::fs::read_to_string(override_path) {
1678 Ok(source) => {
1679 return (
1680 [
1681 (
1682 axum::http::header::CONTENT_TYPE,
1683 axum::http::HeaderValue::from_static("text/css; charset=utf-8"),
1684 ),
1685 (
1689 axum::http::header::CACHE_CONTROL,
1690 axum::http::HeaderValue::from_static(
1691 "public, max-age=31536000, immutable",
1692 ),
1693 ),
1694 ],
1695 source,
1696 )
1697 .into_response();
1698 }
1699 Err(err) => {
1700 tracing::warn!(
1701 target: "rustango_cms::admin",
1702 error = %err,
1703 path = %override_path.display(),
1704 "failed to read cms.css override; falling back to bundled stylesheet",
1705 );
1706 }
1707 }
1708 }
1709 immutable_asset("text/css; charset=utf-8", BUNDLED_CMS_CSS)
1710 .into_response()
1711}
1712
1713fn cms_asset_version() -> String {
1727 static BUNDLED: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1728 let bundled = *BUNDLED.get_or_init(|| {
1729 let mut h: u64 = 0xcbf29ce4_84222325;
1732 let mut feed_bytes = |bytes: &[u8]| {
1733 for &b in bytes {
1734 h ^= u64::from(b);
1735 h = h.wrapping_mul(0x0000_0100_0000_01b3);
1736 }
1737 };
1738 for (_, _, bytes) in ADMIN_BRAND_FILES {
1740 feed_bytes(bytes);
1741 }
1742 let mut feed = |s: &str| feed_bytes(s.as_bytes());
1743 feed(BUNDLED_CMS_CSS);
1744 feed(include_str!("static/cms-ux.js"));
1745 feed(include_str!("static/stream_editor.js"));
1746 feed(include_str!("static/richtext-editor.js"));
1747 feed(include_str!("static/block_tree.js"));
1751 feed(include_str!("static/page_type_builder.js"));
1752 feed(include_str!("static/form_builder.js"));
1753 feed(include_str!("static/menu-builder.js"));
1754 feed(include_str!("static/cms-axe-preview.js"));
1755 feed(include_str!("static/cms-preview-guard.js"));
1756 feed(include_str!("static/cms-preview.js"));
1757 feed(include_str!("static/page_builder_rules.js"));
1758 h
1759 });
1760 if let Ok(meta) = std::fs::metadata("static/cms_admin/cms.css") {
1761 let mtime = meta
1762 .modified()
1763 .ok()
1764 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
1765 .map_or(0, |d| d.as_secs());
1766 return format!("{bundled:x}.{mtime:x}.{:x}", meta.len());
1767 }
1768 format!("{bundled:x}")
1769}
1770
1771struct CmsAssetVersionFn;
1773
1774impl tera::Function for CmsAssetVersionFn {
1775 fn call(
1776 &self,
1777 _args: &std::collections::HashMap<String, tera::Value>,
1778 ) -> tera::Result<tera::Value> {
1779 Ok(tera::Value::String(cms_asset_version()))
1780 }
1781}
1782
1783struct JsonScriptFilter;
1792
1793impl tera::Filter for JsonScriptFilter {
1794 fn filter(
1795 &self,
1796 value: &tera::Value,
1797 _args: &std::collections::HashMap<String, tera::Value>,
1798 ) -> tera::Result<tera::Value> {
1799 Ok(tera::Value::String(json_script(value)))
1800 }
1801
1802 fn is_safe(&self) -> bool {
1803 true
1804 }
1805}
1806
1807fn json_script(value: &tera::Value) -> String {
1808 serde_json::to_string(value)
1809 .unwrap_or_else(|_| "null".to_owned())
1810 .replace('<', "\\u003c")
1811 .replace('>', "\\u003e")
1812 .replace('&', "\\u0026")
1813 .replace('\'', "\\u0027")
1814}
1815
1816pub fn register_templates(tera: &mut Tera) -> Result<(), tera::Error> {
1860 crate::urls::register_tera_helpers(tera);
1861 tera.register_function("cms_asset_version", CmsAssetVersionFn);
1864 tera.register_filter("json_script", JsonScriptFilter);
1865 rustango::i18n::tera_tags::register(tera, i18n::cached_translator().clone());
1870 i18n::register_tera_bindings(tera);
1871 tera.register_function(
1883 "get_env",
1884 |_args: &std::collections::HashMap<String, tera::Value>| -> tera::Result<tera::Value> {
1885 Err(tera::Error::msg(
1886 "get_env is disabled in CMS templates for security reasons",
1887 ))
1888 },
1889 );
1890 tera.add_raw_templates(vec![
1891 (
1892 "rcms_admin/_base.html",
1893 include_str!("templates/_base.html"),
1894 ),
1895 (
1896 "rcms_admin/_auth_layout.html",
1897 include_str!("templates/_auth_layout.html"),
1898 ),
1899 (
1902 "rcms_admin/_brand_icons.html",
1903 include_str!("templates/_brand_icons.html"),
1904 ),
1905 (
1908 "rcms_admin/_list_base.html",
1909 include_str!("templates/_list_base.html"),
1910 ),
1911 (
1918 "rcms_admin/_stream_widget.html",
1919 "{% import \"rcms_admin/_widget.html\" as widget %}{{ widget::render(w=w) }}",
1920 ),
1921 (
1922 "rcms_admin/member_login.html",
1923 include_str!("templates/member_login.html"),
1924 ),
1925 (
1926 "rcms_admin/member_signup.html",
1927 include_str!("templates/member_signup.html"),
1928 ),
1929 (
1930 "rcms_admin/_mcp_keys_card.html",
1931 include_str!("templates/_mcp_keys_card.html"),
1932 ),
1933 (
1934 "rcms_admin/_pagination.html",
1935 include_str!("templates/_pagination.html"),
1936 ),
1937 (
1938 "rcms_admin/_preview_pane.html",
1939 include_str!("templates/_preview_pane.html"),
1940 ),
1941 (
1942 "rcms_admin/notifications.html",
1943 include_str!("templates/notifications.html"),
1944 ),
1945 ("rcms_admin/sites.html", include_str!("templates/sites.html")),
1946 (
1947 "rcms_admin/_widget.html",
1948 include_str!("templates/_widget.html"),
1949 ),
1950 (
1951 "rcms_admin/_inline_card.html",
1952 include_str!("templates/_inline_card.html"),
1953 ),
1954 (
1955 "rcms_admin/_inline_panel.html",
1956 include_str!("templates/_inline_panel.html"),
1957 ),
1958 (
1959 "rcms_admin/_widget_group.html",
1960 include_str!("templates/_widget_group.html"),
1961 ),
1962 (
1963 "rcms_admin/_permissions_tab.html",
1964 include_str!("templates/_permissions_tab.html"),
1965 ),
1966 (
1967 "rcms_admin/page_list.html",
1968 include_str!("templates/page_list.html"),
1969 ),
1970 (
1971 "rcms_admin/page_form.html",
1972 include_str!("templates/page_form.html"),
1973 ),
1974 (
1975 "rcms_admin/page_type_picker.html",
1976 include_str!("templates/page_type_picker.html"),
1977 ),
1978 (
1979 "rcms_admin/library_list.html",
1980 include_str!("templates/library_list.html"),
1981 ),
1982 (
1983 "rcms_admin/snippet_form.html",
1984 include_str!("templates/snippet_form.html"),
1985 ),
1986 (
1987 "rcms_admin/form_builder.html",
1988 include_str!("templates/form_builder.html"),
1989 ),
1990 (
1991 "rcms_admin/form_submissions.html",
1992 include_str!("templates/form_submissions.html"),
1993 ),
1994 (
1995 "rcms_admin/forms_list.html",
1996 include_str!("templates/forms_list.html"),
1997 ),
1998 (
1999 "rcms_admin/form_translate.html",
2000 include_str!("templates/form_translate.html"),
2001 ),
2002 (
2003 "rcms_admin/page_type_translate.html",
2004 include_str!("templates/page_type_translate.html"),
2005 ),
2006 (
2007 "rcms_admin/media_list.html",
2008 include_str!("templates/media_list.html"),
2009 ),
2010 (
2011 "rcms_admin/media_upload.html",
2012 include_str!("templates/media_upload.html"),
2013 ),
2014 (
2015 "rcms_admin/model_admin_list.html",
2016 include_str!("templates/model_admin_list.html"),
2017 ),
2018 (
2019 "rcms_admin/cms_admin_list.html",
2020 include_str!("templates/cms_admin_list.html"),
2021 ),
2022 (
2023 "rcms_admin/cms_admin_form.html",
2024 include_str!("templates/cms_admin_form.html"),
2025 ),
2026 (
2027 "rcms_admin/report.html",
2028 include_str!("templates/report.html"),
2029 ),
2030 (
2031 "rcms_admin/locale_list.html",
2032 include_str!("templates/locale_list.html"),
2033 ),
2034 (
2035 "rcms_admin/locale_form.html",
2036 include_str!("templates/locale_form.html"),
2037 ),
2038 (
2039 "rcms_admin/sso_provider_list.html",
2040 include_str!("templates/sso_provider_list.html"),
2041 ),
2042 (
2043 "rcms_admin/sso_provider_form.html",
2044 include_str!("templates/sso_provider_form.html"),
2045 ),
2046 (
2047 "rcms_admin/workflow_list.html",
2048 include_str!("templates/workflow_list.html"),
2049 ),
2050 (
2051 "rcms_admin/workflow_form.html",
2052 include_str!("templates/workflow_form.html"),
2053 ),
2054 (
2055 "rcms_admin/history_diff.html",
2056 include_str!("templates/history_diff.html"),
2057 ),
2058 (
2059 "rcms_admin/admin_search.html",
2060 include_str!("templates/admin_search.html"),
2061 ),
2062 (
2063 "rcms_admin/analytics.html",
2064 include_str!("templates/analytics.html"),
2065 ),
2066 (
2067 "rcms_admin/aging_pages.html",
2068 include_str!("templates/aging_pages.html"),
2069 ),
2070 (
2071 "rcms_admin/locked_pages.html",
2072 include_str!("templates/locked_pages.html"),
2073 ),
2074 (
2075 "rcms_admin/workflow_report.html",
2076 include_str!("templates/workflow_report.html"),
2077 ),
2078 (
2079 "rcms_admin/revisions_report.html",
2080 include_str!("templates/revisions_report.html"),
2081 ),
2082 (
2083 "rcms_admin/scheduled_report.html",
2084 include_str!("templates/scheduled_report.html"),
2085 ),
2086 (
2087 "rcms_admin/search_promotions_report.html",
2088 include_str!("templates/search_promotions_report.html"),
2089 ),
2090 (
2091 "rcms_admin/search_promotion_edit.html",
2092 include_str!("templates/search_promotion_edit.html"),
2093 ),
2094 (
2095 "rcms_admin/styleguide.html",
2096 include_str!("templates/styleguide.html"),
2097 ),
2098 (
2099 "rcms_admin/dashboard.html",
2100 include_str!("templates/dashboard.html"),
2101 ),
2102 (
2103 "rcms_admin/redirect_import.html",
2104 include_str!("templates/redirect_import.html"),
2105 ),
2106 (
2107 "rcms_admin/snippet_import.html",
2108 include_str!("templates/snippet_import.html"),
2109 ),
2110 (
2111 "rcms_admin/site_settings_list.html",
2112 include_str!("templates/site_settings_list.html"),
2113 ),
2114 (
2115 "rcms_admin/template_list.html",
2116 include_str!("templates/template_list.html"),
2117 ),
2118 (
2119 "rcms_admin/help_index.html",
2120 include_str!("templates/help_index.html"),
2121 ),
2122 (
2123 "rcms_admin/help_page.html",
2124 include_str!("templates/help_page.html"),
2125 ),
2126 (
2127 "rcms_admin/site_theme.html",
2128 include_str!("templates/site_theme.html"),
2129 ),
2130 (
2131 "rcms_admin/site_theme_preview.html",
2132 include_str!("templates/site_theme_preview.html"),
2133 ),
2134 (
2135 "rcms_admin/template_form.html",
2136 include_str!("templates/template_form.html"),
2137 ),
2138 (
2139 "rcms_admin/page_type_template_form.html",
2140 include_str!("templates/page_type_template_form.html"),
2141 ),
2142 (
2143 "rcms_admin/site_setting_form.html",
2144 include_str!("templates/site_setting_form.html"),
2145 ),
2146 (
2150 "rcms/view_password.html",
2151 include_str!("templates/view_password.html"),
2152 ),
2153 (
2154 "rcms_admin/redirect_list.html",
2155 include_str!("templates/redirect_list.html"),
2156 ),
2157 (
2158 "rcms_admin/redirect_form.html",
2159 include_str!("templates/redirect_form.html"),
2160 ),
2161 (
2162 "rcms_admin/settings.html",
2163 include_str!("templates/settings.html"),
2164 ),
2165 (
2166 "rcms_admin/history.html",
2167 include_str!("templates/history.html"),
2168 ),
2169 (
2170 "rcms_admin/navigation_list.html",
2171 include_str!("templates/navigation_list.html"),
2172 ),
2173 (
2174 "rcms_admin/navigation_edit.html",
2175 include_str!("templates/navigation_edit.html"),
2176 ),
2177 (
2178 "rcms_admin/page_types.html",
2179 include_str!("templates/page_types.html"),
2180 ),
2181 (
2182 "rcms_admin/page_type_builder.html",
2183 include_str!("templates/page_type_builder.html"),
2184 ),
2185 (
2186 "rcms_admin/components_list.html",
2187 include_str!("templates/components_list.html"),
2188 ),
2189 (
2190 "rcms_admin/schema_page.html",
2191 include_str!("templates/schema_page.html"),
2192 ),
2193 (
2194 "rcms_admin/page_type_form.html",
2195 include_str!("templates/page_type_form.html"),
2196 ),
2197 (
2198 "rcms_admin/component_builder.html",
2199 include_str!("templates/component_builder.html"),
2200 ),
2201 (
2202 "rcms_admin/users_list.html",
2203 include_str!("templates/users_list.html"),
2204 ),
2205 (
2206 "rcms_admin/security_log.html",
2207 include_str!("templates/security_log.html"),
2208 ),
2209 (
2210 "rcms_admin/user_form.html",
2211 include_str!("templates/user_form.html"),
2212 ),
2213 (
2214 "rcms_admin/roles_list.html",
2215 include_str!("templates/roles_list.html"),
2216 ),
2217 (
2218 "rcms_admin/permissions_overview.html",
2219 include_str!("templates/permissions_overview.html"),
2220 ),
2221 (
2222 "rcms_admin/role_form.html",
2223 include_str!("templates/role_form.html"),
2224 ),
2225 (
2226 "rcms_admin/media_unused.html",
2227 include_str!("templates/media_unused.html"),
2228 ),
2229 (
2230 "rcms_admin/media_edit.html",
2231 include_str!("templates/media_edit.html"),
2232 ),
2233 (
2234 "rcms_admin/collection_permissions.html",
2235 include_str!("templates/collection_permissions.html"),
2236 ),
2237 (
2238 "rcms_admin/collections_list.html",
2239 include_str!("templates/collections_list.html"),
2240 ),
2241 (
2243 "rcms_admin/taxonomies_list.html",
2244 include_str!("templates/taxonomies_list.html"),
2245 ),
2246 (
2247 "rcms_admin/category_tree.html",
2248 include_str!("templates/category_tree.html"),
2249 ),
2250 (
2251 "rcms_admin/category_form.html",
2252 include_str!("templates/category_form.html"),
2253 ),
2254 ("login.html", include_str!("templates/login.html")),
2260 (
2261 "rcms_admin/password_reset_request.html",
2262 include_str!("templates/password_reset_request.html"),
2263 ),
2264 (
2265 "rcms_admin/password_reset_sent.html",
2266 include_str!("templates/password_reset_sent.html"),
2267 ),
2268 (
2269 "rcms_admin/password_reset_confirm.html",
2270 include_str!("templates/password_reset_confirm.html"),
2271 ),
2272 (
2273 "rcms_admin/password_reset_done.html",
2274 include_str!("templates/password_reset_done.html"),
2275 ),
2276 (
2277 "rcms_admin/no_access.html",
2278 include_str!("templates/no_access.html"),
2279 ),
2280 (
2281 "rcms_admin/account_preferences.html",
2282 include_str!("templates/account_preferences.html"),
2283 ),
2284 (
2285 "rcms_admin/_breadcrumbs.html",
2286 include_str!("templates/_breadcrumbs.html"),
2287 ),
2288 (
2294 "blocks/heading.html",
2295 include_str!("templates/blocks/heading.html"),
2296 ),
2297 (
2298 "blocks/paragraph.html",
2299 include_str!("templates/blocks/paragraph.html"),
2300 ),
2301 (
2302 "blocks/image.html",
2303 include_str!("templates/blocks/image.html"),
2304 ),
2305 (
2306 "blocks/quote.html",
2307 include_str!("templates/blocks/quote.html"),
2308 ),
2309 (
2310 "blocks/embed.html",
2311 include_str!("templates/blocks/embed.html"),
2312 ),
2313 (
2314 "blocks/code.html",
2315 include_str!("templates/blocks/code.html"),
2316 ),
2317 (
2319 "blocks/text.html",
2320 include_str!("templates/blocks/text.html"),
2321 ),
2322 (
2323 "blocks/boolean.html",
2324 include_str!("templates/blocks/boolean.html"),
2325 ),
2326 (
2327 "blocks/date.html",
2328 include_str!("templates/blocks/date.html"),
2329 ),
2330 (
2331 "blocks/datetime.html",
2332 include_str!("templates/blocks/datetime.html"),
2333 ),
2334 (
2335 "blocks/email.html",
2336 include_str!("templates/blocks/email.html"),
2337 ),
2338 ("blocks/url.html", include_str!("templates/blocks/url.html")),
2339 (
2340 "blocks/integer.html",
2341 include_str!("templates/blocks/integer.html"),
2342 ),
2343 (
2344 "blocks/choice.html",
2345 include_str!("templates/blocks/choice.html"),
2346 ),
2347 (
2348 "blocks/table.html",
2349 include_str!("templates/blocks/table.html"),
2350 ),
2351 (
2353 "blocks/float.html",
2354 include_str!("templates/blocks/float.html"),
2355 ),
2356 (
2357 "blocks/decimal.html",
2358 include_str!("templates/blocks/decimal.html"),
2359 ),
2360 (
2361 "blocks/regex.html",
2362 include_str!("templates/blocks/regex.html"),
2363 ),
2364 (
2365 "blocks/rich_text.html",
2366 include_str!("templates/blocks/rich_text.html"),
2367 ),
2368 (
2369 "blocks/typed_table_row.html",
2370 include_str!("templates/blocks/typed_table_row.html"),
2371 ),
2372 (
2373 "blocks/typed_table.html",
2374 include_str!("templates/blocks/typed_table.html"),
2375 ),
2376 (
2377 "blocks/time.html",
2378 include_str!("templates/blocks/time.html"),
2379 ),
2380 (
2381 "blocks/multiple_choice.html",
2382 include_str!("templates/blocks/multiple_choice.html"),
2383 ),
2384 (
2385 "blocks/static.html",
2386 include_str!("templates/blocks/static.html"),
2387 ),
2388 (
2389 "blocks/raw_html.html",
2390 include_str!("templates/blocks/raw_html.html"),
2391 ),
2392 (
2393 "blocks/page_chooser.html",
2394 include_str!("templates/blocks/page_chooser.html"),
2395 ),
2396 (
2397 "blocks/snippet_chooser.html",
2398 include_str!("templates/blocks/snippet_chooser.html"),
2399 ),
2400 (
2401 "blocks/document_chooser.html",
2402 include_str!("templates/blocks/document_chooser.html"),
2403 ),
2404 ("blocks/cards.html", include_str!("templates/blocks/cards.html")),
2405 ("blocks/slider.html", include_str!("templates/blocks/slider.html")),
2406 ("blocks/gallery.html", include_str!("templates/blocks/gallery.html")),
2407 ])?;
2408
2409 if !tera.get_template_names().any(|n| n == "error_page.html") {
2416 tera.add_raw_template("error_page.html", include_str!("templates/error_page.html"))?;
2417 }
2418
2419 let override_root = std::path::PathBuf::from("templates/cms_admin");
2424 if override_root.is_dir() {
2425 let count = load_template_overrides(&override_root, "", tera)?;
2426 if count > 0 {
2427 tracing::info!(
2428 target: "rustango_cms::admin",
2429 count,
2430 path = %override_root.display(),
2431 "loaded admin template overrides",
2432 );
2433 }
2434 }
2435 Ok(())
2436}
2437
2438fn load_template_overrides(
2450 dir: &std::path::Path,
2451 prefix: &str,
2452 tera: &mut Tera,
2453) -> Result<usize, tera::Error> {
2454 let mut count = 0;
2455 let entries = std::fs::read_dir(dir)
2456 .map_err(|e| tera::Error::msg(format!("read_dir {}: {e}", dir.display())))?;
2457 for entry in entries {
2458 let entry = entry
2459 .map_err(|e| tera::Error::msg(format!("read_dir entry in {}: {e}", dir.display())))?;
2460 let path = entry.path();
2461 let name = match entry.file_name().into_string() {
2462 Ok(n) => n,
2463 Err(_) => continue,
2464 };
2465 if path.is_dir() {
2466 let nested_prefix = if prefix.is_empty() {
2467 name.clone()
2468 } else {
2469 format!("{prefix}/{name}")
2470 };
2471 count += load_template_overrides(&path, &nested_prefix, tera)?;
2472 } else if path.extension().and_then(|e| e.to_str()) == Some("html") {
2473 let template_name = derive_override_template_name(prefix, &name);
2474 let source = std::fs::read_to_string(&path)
2475 .map_err(|e| tera::Error::msg(format!("read {}: {e}", path.display())))?;
2476 tera.add_raw_template(&template_name, &source)?;
2477 tracing::info!(
2478 target: "rustango_cms::admin",
2479 path = %path.display(),
2480 template = %template_name,
2481 "registered admin template override",
2482 );
2483 count += 1;
2484 }
2485 }
2486 Ok(count)
2487}
2488
2489fn derive_override_template_name(prefix: &str, file_name: &str) -> String {
2495 if prefix.is_empty() {
2496 match file_name {
2500 "_auth_layout.html" => "rcms_admin/_auth_layout.html".to_owned(),
2501 other => other.to_owned(),
2502 }
2503 } else {
2504 format!("{prefix}/{file_name}")
2505 }
2506}
2507
2508#[derive(Debug, thiserror::Error)]
2511pub(crate) enum AdminError {
2512 #[error(transparent)]
2513 Tree(#[from] TreeError),
2514 #[error(transparent)]
2515 Exec(#[from] rustango::sql::ExecError),
2516 #[error(transparent)]
2517 Sqlx(#[from] rustango::sql::sqlx::Error),
2518 #[error(transparent)]
2519 Tera(#[from] tera::Error),
2520 #[error("page {0} not found")]
2521 NotFound(i64),
2522 #[error("upload failed: {0}")]
2523 Upload(String),
2524 #[error("{0}")]
2525 Validation(String),
2526}
2527
2528impl IntoResponse for AdminError {
2529 fn into_response(self) -> Response {
2530 let status = match &self {
2531 AdminError::NotFound(_) => StatusCode::NOT_FOUND,
2532 AdminError::Tree(TreeError::DisallowedChildType { .. })
2533 | AdminError::Tree(TreeError::DisallowedParentType { .. })
2534 | AdminError::Tree(TreeError::CycleAttempt) => StatusCode::BAD_REQUEST,
2535 AdminError::Upload(_) => StatusCode::BAD_REQUEST,
2536 AdminError::Validation(_) => StatusCode::BAD_REQUEST,
2537 _ => StatusCode::INTERNAL_SERVER_ERROR,
2538 };
2539 let mut chain = self.to_string();
2540 let mut src: Option<&dyn std::error::Error> = std::error::Error::source(&self);
2541 while let Some(s) = src {
2542 chain.push_str("\n caused by: ");
2543 chain.push_str(&s.to_string());
2544 src = s.source();
2545 }
2546 if status != StatusCode::INTERNAL_SERVER_ERROR {
2547 return (status, chain).into_response();
2549 }
2550 let reference = crate::mcp::mint_uuid4();
2554 tracing::error!(target: "rustango_cms::admin", error_ref = %reference, "{chain}");
2555 (status, format!("Internal server error (ref {reference})")).into_response()
2556 }
2557}
2558
2559#[derive(Debug, Deserialize)]
2561pub struct PageForm {
2562 pub title: String,
2563 pub slug: String,
2564 pub page_type_id: i64,
2565 pub status: String,
2566 #[serde(rename = "_action", default)]
2571 pub action: String,
2572 #[serde(default)]
2573 pub seo_title: String,
2574 #[serde(default)]
2575 pub seo_description: String,
2576 #[serde(default)]
2577 pub robots_index: Option<String>,
2578 #[serde(default)]
2579 pub sitemap_priority: Option<f32>,
2580 #[serde(default)]
2584 pub show_in_menus: Option<String>,
2585 #[serde(default)]
2589 pub parent_id: Option<i64>,
2590 #[serde(default, deserialize_with = "deserialize_present_optional_i64")]
2595 pub theme_id: Option<Option<i64>>,
2596 #[serde(default)]
2602 pub go_live_at: Option<String>,
2603 #[serde(default)]
2605 pub expire_at: Option<String>,
2606 #[serde(default)]
2611 pub preview_path: String,
2612 #[serde(default)]
2615 pub template_override: String,
2616 #[serde(default)]
2620 pub og_title: String,
2621 #[serde(default)]
2622 pub og_description: String,
2623 #[serde(default, deserialize_with = "deserialize_optional_i64")]
2624 pub og_image_media_id: Option<i64>,
2625 #[serde(default)]
2626 pub twitter_card: Option<String>,
2627 #[serde(default)]
2630 pub tags: Option<String>,
2631 #[serde(default)]
2633 pub categories: Option<String>,
2634}
2635
2636pub(crate) fn deserialize_optional_i64<'de, D>(deserializer: D) -> Result<Option<i64>, D::Error>
2640where
2641 D: serde::Deserializer<'de>,
2642{
2643 use serde::Deserialize as _;
2644 let s = String::deserialize(deserializer)?;
2645 if s.is_empty() || s == "0" {
2646 return Ok(None);
2647 }
2648 s.parse::<i64>().map(Some).map_err(serde::de::Error::custom)
2649}
2650
2651fn deserialize_present_optional_i64<'de, D>(deserializer: D) -> Result<Option<Option<i64>>, D::Error>
2654where
2655 D: serde::Deserializer<'de>,
2656{
2657 deserialize_optional_i64(deserializer).map(Some)
2658}
2659
2660impl PageForm {
2661 fn parsed_status(&self) -> PageStatus {
2667 PageStatus::parse_editable(&self.status).unwrap_or(PageStatus::Draft)
2668 }
2669
2670 fn parsed_robots_index(&self) -> bool {
2673 self.robots_index.is_some()
2674 }
2675
2676 fn parsed_sitemap_priority(&self) -> f32 {
2677 self.sitemap_priority.unwrap_or(0.5)
2678 }
2679
2680 fn parsed_show_in_menus(&self) -> bool {
2681 self.show_in_menus.is_some()
2682 }
2683
2684 fn parsed_go_live_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
2690 parse_datetime_local(self.go_live_at.as_deref())
2691 }
2692
2693 fn parsed_expire_at(&self) -> Option<chrono::DateTime<chrono::Utc>> {
2694 parse_datetime_local(self.expire_at.as_deref())
2695 }
2696
2697 fn go_live_at_in_minutes(&self) -> bool {
2699 datetime_input_in_minutes(self.go_live_at.as_deref())
2700 }
2701
2702 fn expire_at_in_minutes(&self) -> bool {
2704 datetime_input_in_minutes(self.expire_at.as_deref())
2705 }
2706}
2707
2708fn datetime_input_in_minutes(raw: Option<&str>) -> bool {
2712 let Some(raw) = raw.map(str::trim) else {
2713 return false;
2714 };
2715 let raw = raw.strip_suffix('Z').unwrap_or(raw);
2716 chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M").is_ok()
2717}
2718
2719fn parse_datetime_local(raw: Option<&str>) -> Option<chrono::DateTime<chrono::Utc>> {
2720 let raw = raw?.trim();
2721 if raw.is_empty() {
2722 return None;
2723 }
2724 if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(raw) {
2727 return Some(dt.with_timezone(&chrono::Utc));
2728 }
2729 if let Some(utc) = raw.strip_suffix('Z') {
2730 return parse_datetime_local(Some(utc));
2731 }
2732 chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M")
2735 .or_else(|_| chrono::NaiveDateTime::parse_from_str(raw, "%Y-%m-%dT%H:%M:%S"))
2736 .ok()
2737 .map(|naive| chrono::DateTime::<chrono::Utc>::from_naive_utc_and_offset(naive, chrono::Utc))
2738}
2739
2740#[cfg(test)]
2741mod datetime_input_tests {
2742 use super::parse_datetime_local;
2743
2744 #[test]
2747 fn utc_offset_and_bare_values_parse_to_the_same_instant() {
2748 let want = chrono::DateTime::parse_from_rfc3339("2026-12-01T12:00:00Z")
2749 .unwrap()
2750 .with_timezone(&chrono::Utc);
2751 for raw in ["2026-12-01T12:00Z", "2026-12-01T12:00:00Z", "2026-12-01T09:00:00-03:00", "2026-12-01T12:00", " 2026-12-01T12:00:00 "] {
2752 assert_eq!(parse_datetime_local(Some(raw)), Some(want), "{raw}");
2753 }
2754 assert_eq!(parse_datetime_local(Some("")), None);
2755 assert_eq!(parse_datetime_local(Some("tomorrow")), None);
2756 }
2757
2758 #[test]
2760 fn minute_precision_is_read_from_the_posted_text() {
2761 use super::datetime_input_in_minutes;
2762 for raw in ["2026-12-01T12:00", "2026-12-01T12:00Z", " 2026-12-01T12:00 "] {
2763 assert!(datetime_input_in_minutes(Some(raw)), "{raw}");
2764 }
2765 for raw in ["2026-12-01T12:00:00Z", "2026-12-01T12:00:00", "2026-12-01T09:00:00-03:00", ""] {
2766 assert!(!datetime_input_in_minutes(Some(raw)), "{raw}");
2767 }
2768 assert!(!datetime_input_in_minutes(None));
2769 }
2770}
2771
2772#[cfg(test)]
2773mod admin_error_tests {
2774 use super::AdminError;
2775 use axum::response::IntoResponse as _;
2776
2777 async fn body(e: AdminError) -> (u16, String) {
2778 let resp = e.into_response();
2779 let status = resp.status().as_u16();
2780 let bytes = axum::body::to_bytes(resp.into_body(), 1 << 16).await.expect("body");
2781 (status, String::from_utf8(bytes.to_vec()).expect("utf8"))
2782 }
2783
2784 #[tokio::test]
2787 async fn server_errors_hide_their_cause_and_client_errors_do_not() {
2788 let tera_err = tera::Tera::one_off("{{ secret_column | nope }}", &tera::Context::new(), false)
2789 .expect_err("bad template");
2790 let (status, text) = body(AdminError::Tera(tera_err)).await;
2791 assert_eq!(status, 500);
2792 assert!(text.starts_with("Internal server error (ref "), "{text}");
2793 assert!(!text.contains("secret_column") && !text.contains("nope"), "{text}");
2794
2795 let (status, text) = body(AdminError::Validation("slug is taken".into())).await;
2796 assert_eq!(status, 400);
2797 assert!(text.contains("slug is taken"));
2798 }
2799}
2800
2801#[cfg(test)]
2802mod template_shape_tests {
2803 #[test]
2806 fn json_script_cannot_close_the_script_element() {
2807 let hostile = serde_json::json!([{
2808 "name": "</script><script>alert('x')</script> & <!--",
2809 }]);
2810 let mut tera = tera::Tera::default();
2811 super::register_templates(&mut tera).expect("register");
2812 tera.add_raw_template("t", "<script>const X = {{ v | json_script }};</script>")
2813 .expect("template");
2814 let mut ctx = tera::Context::new();
2815 ctx.insert("v", &hostile);
2816 let out = tera.render("t", &ctx).expect("render");
2817 let body = out
2818 .strip_prefix("<script>const X = ")
2819 .and_then(|r| r.strip_suffix(";</script>"))
2820 .expect("one script element");
2821 assert!(!body.contains('<') && !body.contains('>') && !body.contains('\''), "{body}");
2822 let back: serde_json::Value = serde_json::from_str(body).expect("still JSON");
2823 assert_eq!(back, hostile);
2824 }
2825
2826 #[test]
2829 fn no_admin_template_inlines_raw_json() {
2830 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin/templates");
2831 let offenders: Vec<String> = std::fs::read_dir(&dir)
2832 .expect("read templates dir")
2833 .filter_map(|e| {
2834 let path = e.expect("dir entry").path();
2835 let src = std::fs::read_to_string(&path).ok()?;
2836 src.contains("json_encode | safe")
2837 .then(|| path.file_name().unwrap().to_string_lossy().to_string())
2838 })
2839 .collect();
2840 assert!(offenders.is_empty(), "use `| json_script` instead: {offenders:?}");
2841 }
2842
2843 #[test]
2854 fn page_descriptions_come_from_the_shared_intro_card() {
2855 let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/admin/templates");
2856 let mut offenders = Vec::new();
2857 let mut checked = 0;
2858 for entry in std::fs::read_dir(&dir).expect("read templates dir") {
2859 let path = entry.expect("dir entry").path();
2860 if path.extension().and_then(|e| e.to_str()) != Some("html") {
2861 continue;
2862 }
2863 let src = std::fs::read_to_string(&path).expect("read template");
2864 let name = path.file_name().unwrap().to_string_lossy().to_string();
2865 if src.contains("rcms_admin/_list_base.html") {
2866 checked += 1;
2868 continue;
2869 }
2870 let Some(rest) = src.split_once("{% block content %}") else {
2871 continue;
2872 };
2873 checked += 1;
2874 let head = rest.1.trim_start();
2875 if head.starts_with("<p class=\"rcms-hint") {
2876 offenders.push(format!(
2877 "{name}: bare <p class=\"rcms-hint\"> opens the content \
2878 column — extend rcms_admin/_list_base.html and put the \
2879 prose in {{% block description %}}"
2880 ));
2881 } else if rest
2882 .1
2883 .contains("<div class=\"rcms-card\">\n <p class=\"rcms-hint")
2884 {
2885 offenders.push(format!(
2889 "{name}: hand-rolled intro card — extend \
2890 rcms_admin/_list_base.html instead"
2891 ));
2892 }
2893 }
2894 assert!(
2895 checked > 40,
2896 "expected to scan most admin templates, scanned {checked} — \
2897 the `{{% block content %}}` probe is broken"
2898 );
2899 assert!(
2900 offenders.is_empty(),
2901 "{} page(s) don't use the shared intro card:\n{}",
2902 offenders.len(),
2903 offenders.join("\n")
2904 );
2905 }
2906
2907 #[test]
2916 fn get_env_is_disabled_in_the_render_engine() {
2917 let secret = std::env::var("CARGO_PKG_NAME").expect("cargo sets CARGO_PKG_NAME");
2918 let mut tera = tera::Tera::default();
2919 super::register_templates(&mut tera).expect("register_templates");
2920 tera.add_raw_template("ssti.html", r#"{{ get_env(name="CARGO_PKG_NAME") }}"#)
2921 .expect("add template");
2922 match tera.render("ssti.html", &tera::Context::new()) {
2923 Err(_) => {}
2925 Ok(out) => assert!(
2928 !out.contains(&secret),
2929 "get_env leaked the process environment into a template: {out}"
2930 ),
2931 }
2932 }
2933}