//! The Flow variables panel (hub spec §13.2, oxygenhub#102) shared by //! the administration, organisation and repository settings pages: the //! level's own variables and the ones it inherits. use crate::auth::Viewer; use crate::db::accounts; use crate::levels::At; use crate::variables::{self, Seen}; use crate::Shared; use serde::Deserialize; #[derive(Deserialize)] pub struct VariableForm { #[serde(rename = "_csrf")] pub csrf_token: String, #[serde(default)] action: String, #[serde(default)] name: String, #[serde(default)] value: String, } /// Everything the panel shows. pub struct Panel { /// The level's own variables. pub own: Vec, /// The ones the levels above provide, outermost first. pub inherited: Vec, } pub async fn panel(app: &Shared, at: &At) -> sqlx::Result { let (own, inherited): (Vec<_>, Vec<_>) = variables::seen(&app.db, at.scope, &at.owner).await?.into_iter().partition(|v| v.from.is_empty()); Ok(Panel { own, inherited }) } /// Apply the panel's form: `Ok(notice)` or `Err(message for the user)`. pub async fn apply(app: &Shared, viewer: &Viewer, at: &At, f: VariableForm) -> sqlx::Result> { let name = f.name.trim(); if !variables::name_ok(name) { return Ok(Err( "A variable's name is a letter or _, then letters, digits and _, up to 64, and not FLOW_… (Flow sets those).".into() )); } Ok(Ok(match f.action.as_str() { "set" => { let value = f.value.replace("\r\n", "\n"); if !variables::value_ok(&value) { return Ok(Err(format!("A value is up to {} characters of text.", variables::MAX_VALUE))); } let own = variables::list(&app.db, at.scope).await?; if own.len() >= variables::MAX_PER_LEVEL && !own.iter().any(|v| v.name == name) { return Ok(Err(format!("Up to {} variables here.", variables::MAX_PER_LEVEL))); } variables::set(&app.db, at.scope, name, &value).await?; accounts::audit(&app.db, viewer.account(), "flow.variable.set", &at.label, name).await.ok(); format!("{name} set.") } "delete" => { if !variables::delete(&app.db, at.scope, name).await? { return Ok(Err(format!("There is no variable {name} here."))); } accounts::audit(&app.db, viewer.account(), "flow.variable.deleted", &at.label, name).await.ok(); format!("{name} removed.") } _ => return Ok(Err("Unknown action.".into())), })) }