| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | | use crate::auth::Viewer; |
| 6 | | use crate::db::accounts; |
| 7 | | use crate::levels::At; |
| 8 | | use crate::variables::{self, Seen}; |
| 9 | | use crate::Shared; |
| 10 | | use serde::Deserialize; |
| 11 | |
|
| 12 | | #[derive(Deserialize)] |
| 13 | | pub struct VariableForm { |
| 14 | | #[serde(rename = "_csrf")] |
| 15 | | pub csrf_token: String, |
| 16 | | #[serde(default)] |
| 17 | | action: String, |
| 18 | | #[serde(default)] |
| 19 | | name: String, |
| 20 | | #[serde(default)] |
| 21 | | value: String, |
| 22 | | } |
| 23 | |
|
| 24 | |
|
| 25 | | pub struct Panel { |
| 26 | | |
| 27 | | pub own: Vec<Seen>, |
| 28 | | |
| 29 | | pub inherited: Vec<Seen>, |
| 30 | | } |
| 31 | |
|
| 32 | 260× | pub async fn panel(app: &Shared, at: &At) -> sqlx::Result<Panel> { |
| 33 | 260× | let (own, inherited): (Vec<_>, Vec<_>) = |
| 34 | 260× | variables::seen(&app.db, at.scope, &at.owner).await?.into_iter().partition(|v| v.from.is_empty()); |
| 35 | 260× | Ok(Panel { own, inherited }) |
| 36 | 260× | } |
| 37 | |
|
| 38 | |
|
| 39 | 4× | pub async fn apply(app: &Shared, viewer: &Viewer, at: &At, f: VariableForm) -> sqlx::Result<Result<String, String>> { |
| 40 | 4× | let name = f.name.trim(); |
| 41 | 4× | if !variables::name_ok(name) { |
| 42 | 1× | return Ok(Err( |
| 43 | 1× | "A variable's name is a letter or _, then letters, digits and _, up to 64, and not FLOW_… (Flow sets those).".into() |
| 44 | 1× | )); |
| 45 | 3× | } |
| 46 | 3× | Ok(Ok(match f.action.as_str() { |
| 47 | 3× | "set" => { |
| 48 | 2× | let value = f.value.replace("\r\n", "\n"); |
| 49 | 2× | if !variables::value_ok(&value) { |
| 50 | 0× | return Ok(Err(format!("A value is up to {} characters of text.", variables::MAX_VALUE))); |
| 51 | 2× | } |
| 52 | 2× | let own = variables::list(&app.db, at.scope).await?; |
| 53 | 2× | if own.len() >= variables::MAX_PER_LEVEL && !own.iter().any(|v| v.name == name) { |
| 54 | 0× | return Ok(Err(format!("Up to {} variables here.", variables::MAX_PER_LEVEL))); |
| 55 | 2× | } |
| 56 | 2× | variables::set(&app.db, at.scope, name, &value).await?; |
| 57 | 2× | accounts::audit(&app.db, viewer.account(), "flow.variable.set", &at.label, name).await.ok(); |
| 58 | 2× | format!("{name} set.") |
| 59 | | } |
| 60 | 1× | "delete" => { |
| 61 | 1× | if !variables::delete(&app.db, at.scope, name).await? { |
| 62 | 0× | return Ok(Err(format!("There is no variable {name} here."))); |
| 63 | 1× | } |
| 64 | 1× | accounts::audit(&app.db, viewer.account(), "flow.variable.deleted", &at.label, name).await.ok(); |
| 65 | 1× | format!("{name} removed.") |
| 66 | | } |
| 67 | 0× | _ => return Ok(Err("Unknown action.".into())), |
| 68 | | })) |
| 69 | 4× | } |