Skip to main content

renox_admin/
settings.rs

1//! Settings pages: a form for a group of settings kept in the database
2//! (`renox::settings`), added with [`Admin::settings`](crate::Admin::settings).
3//! The form comes from the fields [`AdminSettings::fields`] declares; saving
4//! runs the group's own rules and goes through `AppState::save_settings`,
5//! so the change is audited and emits `SettingsChanged`.
6
7use std::collections::BTreeSet;
8use std::marker::PhantomData;
9use std::sync::Arc;
10
11use renox::axum::Extension;
12use renox::axum::body::{Body, Bytes};
13use renox::axum::extract::{FromRequest, Request};
14use renox::axum::http::header::CONTENT_TYPE;
15use renox::prelude::*;
16use renox::serde_json::{Map, Value};
17use renox::settings::SettingsGroup;
18
19use crate::field::FieldKind;
20use crate::panel::{Panel, fields_view, money_names, parse_pairs, read_form, to_json};
21use crate::texts::Texts;
22use crate::{Field, panel};
23
24/// A group of settings the admin panel can edit: the fields of its form,
25/// and who may open or change it.
26///
27/// ```
28/// use renox::prelude::*;
29/// use renox::settings::SettingsGroup;
30/// use renox_admin::{Admin, AdminSettings, Field};
31///
32/// #[derive(serde::Serialize, serde::Deserialize, Validate, Default, Clone)]
33/// struct Company {
34///     #[validate(required, max(120))]
35///     name: String,
36///     tax_number: Option<String>,
37///     registered_on: Option<String>,
38/// }
39///
40/// impl SettingsGroup for Company {
41///     const KEY: &'static str = "company";
42/// }
43///
44/// impl AdminSettings for Company {
45///     fn fields() -> Vec<Field> {
46///         vec![
47///             Field::text("name", "Company name").required(),
48///             Field::text("tax_number", "Tax number"),
49///             // Shown, but only changed by a seed file or `settings:set`.
50///             Field::text("registered_on", "Registered on").readonly_on_edit(),
51///         ]
52///     }
53///
54///     fn allows(user: &AuthUser, ability: &str) -> bool {
55///         ability == "view" || user.has_role("owner") // owners change it
56///     }
57/// }
58///
59/// # let _ =
60/// Admin::new().authorize(|user| user.has_role("staff")).settings::<Company>("Company")
61/// # ;
62/// ```
63pub trait AdminSettings: SettingsGroup {
64    /// The form's fields, named like the group's struct fields. A field
65    /// marked [`readonly_on_edit`](Field::readonly_on_edit) is shown but its
66    /// stored value is kept whatever is sent.
67    fn fields() -> Vec<Field>;
68
69    /// Whether `user` may do `ability` on the page: `"view"` (open it) or
70    /// `"update"` (save it). Everyone the panel lets in may by default.
71    fn allows(user: &AuthUser, ability: &str) -> bool {
72        let _ = (user, ability);
73        true
74    }
75}
76
77/// A settings page as the panel lists it, whatever its group.
78pub(crate) trait SettingsPage: Send + Sync {
79    fn key(&self) -> &str;
80    fn label(&self) -> &str;
81    fn visible(&self, user: &AuthUser) -> bool;
82    /// Declares the group (`App::settings`) so the commands know it too.
83    fn declare(&self, registry: &mut Registry);
84    fn routes(&self, panel: Arc<Panel>) -> Routes;
85}
86
87pub(crate) struct Page<S> {
88    label: String,
89    group: PhantomData<fn() -> S>,
90}
91
92impl<S> Page<S> {
93    pub(crate) fn new(label: &str) -> Self {
94        Self {
95            label: label.to_owned(),
96            group: PhantomData,
97        }
98    }
99}
100
101impl<S: AdminSettings> SettingsPage for Page<S> {
102    fn key(&self) -> &str {
103        S::KEY
104    }
105
106    fn label(&self) -> &str {
107        &self.label
108    }
109
110    fn visible(&self, user: &AuthUser) -> bool {
111        S::allows(user, "view")
112    }
113
114    fn declare(&self, registry: &mut Registry) {
115        registry.settings::<S>();
116    }
117
118    fn routes(&self, panel: Arc<Panel>) -> Routes {
119        let path = format!("/settings/{}", S::KEY);
120        Routes::new()
121            .get(&path, show::<S>)
122            .name(&format!("settings.{}.show", S::KEY))
123            .put(&path, update::<S>)
124            .name(&format!("settings.{}.update", S::KEY))
125            .route_layer(Extension(Ctx::<S> {
126                panel,
127                label: self.label.clone(),
128                group: PhantomData,
129            }))
130            .require_auth()
131    }
132}
133
134/// What a settings page's handlers share.
135struct Ctx<S> {
136    panel: Arc<Panel>,
137    label: String,
138    group: PhantomData<fn() -> S>,
139}
140
141impl<S> Clone for Ctx<S> {
142    fn clone(&self) -> Self {
143        Self {
144            panel: self.panel.clone(),
145            label: self.label.clone(),
146            group: PhantomData,
147        }
148    }
149}
150
151impl<S: AdminSettings> Ctx<S> {
152    fn url(&self) -> String {
153        format!("{}/settings/{}", self.panel.path, S::KEY)
154    }
155
156    /// The panel lets `user` in and the group's policy allows `ability`.
157    fn authorize(&self, user: &AuthUser, ability: &str) -> Result {
158        self.panel.check(user)?;
159        if S::allows(user, ability) {
160            Ok(())
161        } else {
162            Err(Error::Forbidden)
163        }
164    }
165}
166
167async fn show<S: AdminSettings>(
168    Extension(cx): Extension<Ctx<S>>,
169    State(state): State<AppState>,
170    user: AuthUser,
171) -> Result<View> {
172    cx.authorize(&user, "view")?;
173    let texts = Texts::new(&state);
174    let settings = state.settings::<S>().await?;
175    let info = state.settings_info::<S>().await?;
176    let mut fields = S::fields();
177    // A sealed group never prints its values: the fields start empty, and a
178    // hint says whether they are set.
179    let record = if S::ENCRYPTED {
180        let hint = match &info {
181            Some(info) => texts.get(
182                "sealed_set",
183                &[(
184                    "when",
185                    &info.updated_at.format("%Y-%m-%d %H:%M UTC").to_string(),
186                )],
187            ),
188            None => texts.get("sealed_unset", &[]),
189        };
190        fields = fields
191            .into_iter()
192            .map(|field| match field.kind() {
193                FieldKind::Checkbox | FieldKind::Toggle => field,
194                _ => field.hint(&hint),
195            })
196            .collect();
197        Value::Null
198    } else {
199        to_json(&*settings)?
200    };
201    let key = format!("settings/{}", S::KEY);
202    let views = fields_view(fields, &state, Some(&record), &texts, S::KEY, &[]).await?;
203    let mut values = Map::new();
204    let label = texts.label("settings", &cx.label);
205    values.insert("title".into(), Value::String(label.clone()));
206    values.insert("fields".into(), to_json(&views)?);
207    values.insert("action".into(), Value::String(cx.url()));
208    values.insert("method".into(), Value::String("PUT".into()));
209    values.insert(
210        "submit_label".into(),
211        Value::String(texts.get("save_changes", &[])),
212    );
213    values.insert("sealed".into(), Value::Bool(S::ENCRYPTED));
214    values.insert("editable".into(), Value::Bool(S::allows(&user, "update")));
215    values.insert(
216        "admin".into(),
217        to_json(&cx.panel.frame(&state, &user, Some(&key), &texts))?,
218    );
219    Ok(view("renox-admin/settings.html", Value::Object(values)))
220}
221
222async fn update<S: AdminSettings>(
223    Extension(cx): Extension<Ctx<S>>,
224    State(state): State<AppState>,
225    user: AuthUser,
226    htmx: Htmx,
227    req: Request,
228) -> Result<Response> {
229    cx.authorize(&user, "update")?;
230    let texts = Texts::new(&state);
231    let current = to_json(&*state.settings::<S>().await?)?;
232    let fields = S::fields();
233    let (req, sent) = match buffered(&state, req).await {
234        Ok(read) => read,
235        Err(answer) => return Ok(*answer),
236    };
237    // What the form must not change: read-only fields, and (in a sealed
238    // group, where the page shows nothing) fields left empty.
239    let mut fixed = Vec::new();
240    for field in &fields {
241        let bool_field = matches!(field.kind(), FieldKind::Checkbox | FieldKind::Toggle);
242        let keep = field.is_readonly_on_edit()
243            || (S::ENCRYPTED && !bool_field && !sent.contains(field.name()));
244        if keep {
245            fixed.push((
246                field.name().to_owned(),
247                scalar_text(current.get(field.name())),
248            ));
249        }
250    }
251    let form: S = match read_form(&state, req, &money_names(&fields), &fixed).await {
252        Ok(form) => form,
253        Err(answer) => return Ok(*answer),
254    };
255    state.save_settings(&form, Some(&user)).await?;
256    let label = texts.label("settings", &cx.label);
257    let toast = Toast::success(texts.get("saved", &[("label", &label)]));
258    Ok(panel::done(&htmx, toast, &cx.url()))
259}
260
261/// A stored value as the text a form would have sent.
262fn scalar_text(value: Option<&Value>) -> String {
263    match value {
264        None | Some(Value::Null) => String::new(),
265        Some(Value::String(text)) => text.clone(),
266        Some(other) => other.to_string(),
267    }
268}
269
270/// Reads the body so the page can tell which fields were filled in, then
271/// puts it back for the form reader.
272async fn buffered(
273    state: &AppState,
274    req: Request,
275) -> std::result::Result<(Request, BTreeSet<String>), Box<Response>> {
276    let kind = req
277        .headers()
278        .get(CONTENT_TYPE)
279        .and_then(|v| v.to_str().ok())
280        .unwrap_or("")
281        .to_ascii_lowercase();
282    let (parts, body) = req.into_parts();
283    let bytes = Bytes::from_request(Request::from_parts(parts.clone(), body), state)
284        .await
285        .map_err(|rejection| Box::new(rejection.into_response()))?;
286    let mut sent = BTreeSet::new();
287    if kind.starts_with("application/json") {
288        if let Ok(Value::Object(object)) = renox::serde_json::from_slice::<Value>(&bytes) {
289            for (name, value) in object {
290                if !matches!(&value, Value::Null) && value.as_str() != Some("") {
291                    sent.insert(name);
292                }
293            }
294        }
295    } else {
296        for (name, value) in parse_pairs(&bytes) {
297            if !value.is_empty() {
298                sent.insert(name);
299            }
300        }
301    }
302    Ok((Request::from_parts(parts, Body::from(bytes)), sent))
303}