BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-base / src / orgs.rs

orgs.rs

ea9903e4 History
orgs.rs 3.8 KiB Download Raw
1//! The organizations of the signed-in account and which one the window shows.
2//!
3//! Lives in its own file beside the caches, because it decides which cache to open.
4//! The home tenant keeps `cache.sqlite3`; a guest tenant gets `cache-<tenant id>.sqlite3`.
5use std::path::{Path, PathBuf};
6
7use serde::{Deserialize, Serialize};
8
9pub const ORGS_FILE: &str = "orgs.json";
10const HOME_DATABASE: &str = "cache.sqlite3";
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
13pub struct Org {
14 pub id: String,
15 pub name: String,
16 pub guest: bool,
17}
18
19#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Orgs {
21 /// Tenant id of the org the window shows; `None` is the home tenant.
22 pub active: Option<String>,
23 pub list: Vec<Org>,
24}
25
26impl Orgs {
27 pub fn path() -> Option<PathBuf> {
28 crate::support::local_data_dir().map(|root| root.join(ORGS_FILE))
29 }
30
31 /// A missing or unreadable file is the home tenant with no known orgs.
32 pub fn load(path: &Path) -> Orgs {
33 std::fs::read(path)
34 .ok()
35 .and_then(|bytes| serde_json::from_slice(&bytes).ok())
36 .unwrap_or_default()
37 }
38
39 pub fn save(&self, path: &Path) -> std::io::Result<()> {
40 let bytes = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;
41 std::fs::write(path, bytes)
42 }
43
44 /// The active org when it is a guest tenant, the only case that needs its own tokens and cache.
45 pub fn active_guest(&self) -> Option<&Org> {
46 let active = self.active.as_deref()?;
47 self.list
48 .iter()
49 .find(|org| org.guest && org.id == active && is_tenant_id(&org.id))
50 }
51
52 pub fn is_active(&self, org: &Org) -> bool {
53 match self.active_guest() {
54 Some(active) => active.id == org.id,
55 None => !org.guest,
56 }
57 }
58
59 pub fn database_file(&self) -> String {
60 match self.active_guest() {
61 Some(org) => format!("cache-{}.sqlite3", org.id),
62 None => HOME_DATABASE.to_owned(),
63 }
64 }
65
66 /// Takes the account's current org list; an active org that is gone falls back to home.
67 pub fn replace_list(&mut self, list: Vec<Org>) {
68 self.list = list;
69 if self.active_guest().is_none() {
70 self.active = None;
71 }
72 }
73
74 pub fn activate(&mut self, org: &Org) {
75 self.active = org.guest.then(|| org.id.clone());
76 }
77}
78
79/// Tenant ids are GUIDs; anything else must not end up in a file name.
80fn is_tenant_id(id: &str) -> bool {
81 !id.is_empty() && id.chars().all(|character| character.is_ascii_hexdigit() || character == '-')
82}
83
84#[cfg(test)]
85mod tests {
86 use super::*;
87
88 fn org(id: &str, guest: bool) -> Org {
89 Org {
90 id: id.into(),
91 name: id.into(),
92 guest,
93 }
94 }
95
96 #[test]
97 fn a_guest_org_gets_its_own_cache_and_home_keeps_the_old_one() {
98 let mut orgs = Orgs {
99 active: None,
100 list: vec![org("aaaa-01", false), org("bbbb-02", true)],
101 };
102 assert_eq!(orgs.database_file(), "cache.sqlite3");
103 assert!(orgs.is_active(&orgs.list[0].clone()));
104 orgs.activate(&orgs.list[1].clone());
105 assert_eq!(orgs.database_file(), "cache-bbbb-02.sqlite3");
106 assert!(orgs.is_active(&orgs.list[1].clone()));
107 orgs.activate(&orgs.list[0].clone());
108 assert_eq!(orgs.active, None);
109 }
110
111 #[test]
112 fn an_unknown_or_unsafe_active_org_is_the_home_tenant() {
113 let mut orgs = Orgs {
114 active: Some("../evil".into()),
115 list: vec![org("../evil", true)],
116 };
117 assert_eq!(orgs.database_file(), "cache.sqlite3");
118 orgs.active = Some("bbbb-02".into());
119 orgs.replace_list(vec![org("aaaa-01", false)]);
120 assert_eq!(orgs.active, None);
121 }
122}