| 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 |
pub async fn panel(app: &Shared, at: &At) -> sqlx::Result<Panel> { |
| 33 |
let (own, inherited): (Vec<_>, Vec<_>) = |
| 34 |
variables::seen(&app.db, at.scope, &at.owner).await?.into_iter().partition(|v| v.from.is_empty()); |
| 35 |
Ok(Panel { own, inherited }) |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
pub async fn apply(app: &Shared, viewer: &Viewer, at: &At, f: VariableForm) -> sqlx::Result<Result<String, String>> { |
| 40 |
let name = f.name.trim(); |
| 41 |
if !variables::name_ok(name) { |
| 42 |
return Ok(Err( |
| 43 |
"A variable's name is a letter or _, then letters, digits and _, up to 64, and not FLOW_… (Flow sets those).".into() |
| 44 |
)); |
| 45 |
} |
| 46 |
Ok(Ok(match f.action.as_str() { |
| 47 |
"set" => { |
| 48 |
let value = f.value.replace("\r\n", "\n"); |
| 49 |
if !variables::value_ok(&value) { |
| 50 |
return Ok(Err(format!("A value is up to {} characters of text.", variables::MAX_VALUE))); |
| 51 |
} |
| 52 |
let own = variables::list(&app.db, at.scope).await?; |
| 53 |
if own.len() >= variables::MAX_PER_LEVEL && !own.iter().any(|v| v.name == name) { |
| 54 |
return Ok(Err(format!("Up to {} variables here.", variables::MAX_PER_LEVEL))); |
| 55 |
} |
| 56 |
variables::set(&app.db, at.scope, name, &value).await?; |
| 57 |
accounts::audit(&app.db, viewer.account(), "flow.variable.set", &at.label, name).await.ok(); |
| 58 |
format!("{name} set.") |
| 59 |
} |
| 60 |
"delete" => { |
| 61 |
if !variables::delete(&app.db, at.scope, name).await? { |
| 62 |
return Ok(Err(format!("There is no variable {name} here."))); |
| 63 |
} |
| 64 |
accounts::audit(&app.db, viewer.account(), "flow.variable.deleted", &at.label, name).await.ok(); |
| 65 |
format!("{name} removed.") |
| 66 |
} |
| 67 |
_ => return Ok(Err("Unknown action.".into())), |
| 68 |
})) |
| 69 |
} |