rustango_cms/admin/admin_page.rs
1//! Extension point for **custom admin pages**.
2//!
3//! Authors building on top of `rustango-cms` register a unit-struct
4//! handler via [`crate::register_admin_page!`] and it appears as a
5//! sidebar entry under its declared [`SidebarSection`]. All registered
6//! handlers route through a single dispatcher mounted at
7//! `/cms-admin/x/{slug}`; no per-page router scaffolding to maintain.
8//!
9//! Custom pages inherit the bundled admin chrome — they extend
10//! [`rcms_admin/_base.html`](../templates/_base.html) and get the
11//! sidebar, topbar, action-bar slot, flash banners, theme tokens,
12//! and every class from [`cms.css`](../static/cms.css) for free.
13//!
14//! ## Example
15//!
16//! ```ignore
17//! use axum::response::Response;
18//! use async_trait::async_trait;
19//! use rustango_cms::admin::admin_page::{AdminPageCtx, AdminPageHandler, SidebarSection};
20//!
21//! #[derive(Default)]
22//! pub struct ReportsDashboard;
23//!
24//! #[async_trait]
25//! impl AdminPageHandler for ReportsDashboard {
26//! fn slug(&self) -> &'static str { "reports" } // → /cms-admin/x/reports
27//! fn label(&self) -> &'static str { "Reports" }
28//! fn icon(&self) -> Option<&'static str> { Some("insights") }
29//! fn section(&self) -> SidebarSection { SidebarSection::Site }
30//! async fn render(&self, ctx: AdminPageCtx<'_>) -> Response {
31//! // Build a Tera context, render `reports.html` (host-registered),
32//! // return the response.
33//! todo!()
34//! }
35//! }
36//!
37//! rustango_cms::register_admin_page!(ReportsDashboard);
38//! ```
39
40use std::collections::HashMap;
41use std::sync::Arc;
42
43use axum::http::{HeaderMap, StatusCode, Uri};
44use axum::response::{IntoResponse, Response};
45use rustango::extractors::Tenant;
46pub use rustango::messages::Level as MessageLevel;
47
48use crate::permissions::Action;
49
50/// Where the custom page's sidebar entry lands. Built-ins:
51/// `Content`, `Site`, `Settings`. Use `Custom(&'static str)` to spin
52/// up a new section heading on demand (e.g. `Custom("Tools")`).
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum SidebarSection {
55 Content,
56 Site,
57 Settings,
58 Custom(&'static str),
59}
60
61impl SidebarSection {
62 /// Human-readable section heading (also the bucket key when
63 /// `_base.html` groups custom pages for rendering).
64 #[must_use]
65 pub fn label(&self) -> &'static str {
66 match self {
67 Self::Content => "Content",
68 Self::Site => "Site",
69 Self::Settings => "Settings",
70 Self::Custom(name) => name,
71 }
72 }
73}
74
75/// Request-scoped context handed to every custom admin page.
76/// References rather than owns so the handler doesn't have to clone
77/// the Tera instance / per-tenant pool.
78pub struct AdminPageCtx<'a> {
79 pub tera: &'a Arc<tera::Tera>,
80 pub tenant: &'a Tenant,
81 pub headers: &'a HeaderMap,
82 /// The signed-in user, which the dispatcher has already resolved.
83 ///
84 /// Without it a custom page can know only that *somebody* is logged
85 /// in, so it cannot gate on a codename — and a page that manages
86 /// anything sensitive has to. It is also what
87 /// [`crate::admin::handlers::add_chrome`] needs to fill in the
88 /// per-user half of the sidebar.
89 pub user: Option<&'a rustango::tenancy::auth::User>,
90 /// The request URI, for the query string (`?id=7`, `?q=…`).
91 pub uri: &'a Uri,
92 /// The path segment after the slug: `edit` for
93 /// `/cms-admin/x/<slug>/edit`, `None` for the page itself.
94 pub action: Option<&'a str>,
95}
96
97impl AdminPageCtx<'_> {
98 /// The query string as a map. A repeated key keeps its last value.
99 #[must_use]
100 pub fn query(&self) -> HashMap<String, String> {
101 self.uri
102 .query()
103 .and_then(|q| serde_urlencoded::from_str(q).ok())
104 .unwrap_or_default()
105 }
106
107 /// One query-string value, trimmed; `None` when absent or blank.
108 #[must_use]
109 pub fn query_param(&self, name: &str) -> Option<String> {
110 self.query()
111 .remove(name)
112 .map(|v| v.trim().to_owned())
113 .filter(|v| !v.is_empty())
114 }
115
116 /// Render `template` inside the admin chrome. Adds what every admin
117 /// screen needs to `ctx`: the sidebar (with this page marked active),
118 /// the signed-in user, branding, the admin theme, the admin language,
119 /// `csrf_token` and pending flash `messages`. A template error renders a 500.
120 pub async fn render(&self, template: &str, ctx: &mut tera::Context) -> Response {
121 let slug = self.slug();
122 super::handlers::add_chrome(ctx, self.tenant, &format!("custom:{slug}"), self.user).await;
123 super::handlers::add_admin_theme(ctx, self.tenant.pool()).await;
124 ctx.insert("admin_page_slug", &slug);
125 match super::handlers::render_tera(self.tera, self.headers, template, ctx) {
126 Ok(resp) => resp,
127 Err(e) => e.into_response(),
128 }
129 }
130
131 /// `303 See Other` to `to`, with a flash message the next admin page
132 /// shows. The message is translated for the admin language when the
133 /// catalogs have it.
134 #[must_use]
135 pub fn redirect(&self, to: &str, level: MessageLevel, message: &str) -> Response {
136 let body = super::i18n::tr(self.headers, message, &[]);
137 rustango::messages::redirect_with_message(
138 super::handlers::messages_secret(),
139 self.headers,
140 level,
141 &body,
142 to,
143 )
144 }
145
146 /// Whether the signed-in user holds `codename`. Superusers hold every
147 /// codename; no user holds none.
148 pub async fn has_perm(&self, codename: &str) -> bool {
149 let Some(user) = self.user else { return false };
150 user.is_superuser
151 || crate::permissions::user_codenames(self.tenant.pool(), user.id.get().copied().unwrap_or_default())
152 .await
153 .is_ok_and(|codes| codes.iter().any(|c| c == codename))
154 }
155
156 /// `/cms-admin/x/<slug>`, the URL of this page.
157 #[must_use]
158 pub fn page_url(&self) -> String {
159 format!("/cms-admin/x/{}", self.slug())
160 }
161
162 fn slug(&self) -> &str {
163 self.uri
164 .path()
165 .strip_prefix("/cms-admin/x/")
166 .and_then(|rest| rest.split('/').next())
167 .unwrap_or_default()
168 }
169}
170
171/// A posted `application/x-www-form-urlencoded` body, in field order.
172/// Repeated names (checkbox lists, multi-selects) keep every value.
173#[derive(Debug, Clone, Default)]
174pub struct AdminForm {
175 pairs: Vec<(String, String)>,
176}
177
178impl AdminForm {
179 /// Parse a urlencoded body. Malformed input gives an empty form.
180 #[must_use]
181 pub fn parse(body: &[u8]) -> Self {
182 Self { pairs: serde_urlencoded::from_bytes(body).unwrap_or_default() }
183 }
184
185 /// The last value posted under `name`, as sent.
186 #[must_use]
187 pub fn get(&self, name: &str) -> Option<&str> {
188 self.pairs.iter().rev().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
189 }
190
191 /// The value under `name`, trimmed; empty when absent.
192 #[must_use]
193 pub fn text(&self, name: &str) -> String {
194 self.get(name).map(str::trim).unwrap_or_default().to_owned()
195 }
196
197 /// The trimmed value, or `None` when absent or blank.
198 #[must_use]
199 pub fn opt_text(&self, name: &str) -> Option<String> {
200 Some(self.text(name)).filter(|v| !v.is_empty())
201 }
202
203 /// A checkbox: `on`, `true`, `1` or `yes` is checked.
204 #[must_use]
205 pub fn checked(&self, name: &str) -> bool {
206 matches!(self.get(name).map(str::trim), Some("on" | "true" | "1" | "yes"))
207 }
208
209 /// The value parsed as an integer; `None` when absent, blank or not a number.
210 #[must_use]
211 pub fn int(&self, name: &str) -> Option<i64> {
212 self.get(name).and_then(|v| v.trim().parse().ok())
213 }
214
215 /// The value parsed as a decimal number.
216 #[must_use]
217 pub fn float(&self, name: &str) -> Option<f64> {
218 self.get(name).and_then(|v| v.trim().parse().ok())
219 }
220
221 /// Every value posted under `name`, in order.
222 #[must_use]
223 pub fn all(&self, name: &str) -> Vec<&str> {
224 self.pairs.iter().filter(|(k, _)| k == name).map(|(_, v)| v.as_str()).collect()
225 }
226
227 /// Every value under `name` that parses as an integer.
228 #[must_use]
229 pub fn ints(&self, name: &str) -> Vec<i64> {
230 self.all(name).into_iter().filter_map(|v| v.trim().parse().ok()).collect()
231 }
232
233 /// The form as a map: the last value of each name.
234 #[must_use]
235 pub fn to_map(&self) -> HashMap<String, String> {
236 self.pairs.iter().cloned().collect()
237 }
238
239 /// The raw `(name, value)` pairs.
240 #[must_use]
241 pub fn pairs(&self) -> &[(String, String)] {
242 &self.pairs
243 }
244}
245
246/// Trait every custom admin page implements. Compiled-in via the
247/// `inventory` registry — see [`crate::register_admin_page!`].
248#[async_trait::async_trait]
249pub trait AdminPageHandler: Send + Sync + 'static {
250 /// URL slug. The page mounts at `/cms-admin/x/<slug>`. Must
251 /// stay stable; bookmarks / links reference this value.
252 fn slug(&self) -> &'static str;
253
254 /// Visible label rendered in the sidebar.
255 fn label(&self) -> &'static str;
256
257 /// Optional Material-symbols icon name (e.g. `"insights"`,
258 /// `"bug_report"`).
259 fn icon(&self) -> Option<&'static str> {
260 None
261 }
262
263 /// Which sidebar section the entry lives under. Defaults to a
264 /// generic `Custom("Tools")` bucket so out-of-the-box behaviour
265 /// keeps third-party pages visually separated from built-ins.
266 fn section(&self) -> SidebarSection {
267 SidebarSection::Custom("Tools")
268 }
269
270 /// Sibling order within the section (ascending). Defaults to 100
271 /// so most third-party pages slot in between built-ins (which use
272 /// lower numbers) without needing to think about ordering.
273 fn sort_order(&self) -> i32 {
274 100
275 }
276
277 /// Codename prefix to surface this page in the role permissions
278 /// matrix. Returning `Some("acme_reports")` adds a
279 /// "Custom admin pages → `<label>`" row with `view` + `edit`
280 /// columns, granting / revoking codenames `acme_reports.view`
281 /// and `acme_reports.edit`. Default `None` means the page is
282 /// not access-controlled by the matrix — hosts can still gate
283 /// inside `render()` manually.
284 fn permission_resource(&self) -> Option<&'static str> {
285 None
286 }
287
288 /// The matrix columns for [`Self::permission_resource`], and so the
289 /// codenames the dispatcher checks. The default, view + edit, gates
290 /// `GET` on `<resource>.view` and every `POST` on `<resource>.edit`.
291 /// Including [`Action::Add`] or [`Action::Delete`] makes a `POST` to
292 /// the `new` or `delete` action need `.add` or `.delete` instead.
293 fn permission_actions(&self) -> &'static [Action] {
294 &[Action::View, Action::Edit]
295 }
296
297 /// Render the page. The implementation owns its template + form
298 /// dispatch (handlers usually render via Tera with the bundled
299 /// chrome by extending `rcms_admin/_base.html`).
300 async fn render(&self, ctx: AdminPageCtx<'_>) -> Response;
301
302 /// Handle a form posted to `/cms-admin/x/<slug>` or
303 /// `/cms-admin/x/<slug>/<action>` (see [`AdminPageCtx::action`]).
304 /// The dispatcher has already checked the login, the CSRF token and
305 /// the codename (see [`Self::permission_actions`]). The usual reply
306 /// is [`AdminPageCtx::redirect`]. The default answers
307 /// `405 Method Not Allowed`.
308 async fn post(&self, _ctx: AdminPageCtx<'_>, _form: AdminForm) -> Response {
309 StatusCode::METHOD_NOT_ALLOWED.into_response()
310 }
311}
312
313/// The codename a request to admin page `slug` needs, or `None` when
314/// the page declares no [`AdminPageHandler::permission_resource`] (or
315/// no page has that slug: the dispatcher answers 404).
316#[must_use]
317pub fn required_codename(slug: &str, reads: bool, action: Option<&str>) -> Option<String> {
318 let handler = find_admin_page(slug)?;
319 let resource = handler.permission_resource()?;
320 let declared = handler.permission_actions();
321 let verb = if reads {
322 Action::View
323 } else {
324 match action {
325 Some("delete") if declared.contains(&Action::Delete) => Action::Delete,
326 Some("new") if declared.contains(&Action::Add) => Action::Add,
327 _ => Action::Edit,
328 }
329 };
330 Some(format!("{resource}.{}", verb.as_str()))
331}
332
333/// Registration entry submitted via `inventory::submit!` by the
334/// `register_admin_page!` macro. Mirrors `PageTypeHandlerRegistration`.
335pub struct AdminPageHandlerRegistration {
336 pub factory: fn() -> Box<dyn AdminPageHandler>,
337}
338
339inventory::collect!(AdminPageHandlerRegistration);
340
341/// Iterator over every registered handler. Used by the sidebar
342/// enumeration in `add_chrome()` and by the route dispatcher.
343pub fn registered_admin_pages() -> impl Iterator<Item = Box<dyn AdminPageHandler>> {
344 inventory::iter::<AdminPageHandlerRegistration>
345 .into_iter()
346 .map(|r| (r.factory)())
347}
348
349/// Find a registered handler by `slug`. Returns `None` for unknown
350/// slugs — the dispatch route maps that to a 404.
351#[must_use]
352pub fn find_admin_page(slug: &str) -> Option<Box<dyn AdminPageHandler>> {
353 registered_admin_pages().find(|h| h.slug() == slug)
354}