BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / tenants.rs

tenants.rs

tenants.rs 2.3 KiB Download Raw
1//! The organizations the signed-in account belongs to, as the Teams org switcher lists them.
2use serde_json::Value;
3use session::{Method, Session};
4
5use crate::cards::{DEFAULT_MT_REGION, spaces_scope};
6use crate::error::{Error, Result};
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Tenant {
10 pub id: String,
11 pub name: String,
12 /// The account is a guest here; its home tenant is the one with `guest == false`.
13 pub guest: bool,
14}
15
16/// Every tenant of the account, home tenant first.
17pub async fn list_tenants(session: &Session) -> Result<Vec<Tenant>> {
18 let url = format!("https://teams.cloud.microsoft/api/mt/{DEFAULT_MT_REGION}/beta/users/tenants");
19 let answer = session
20 .request(Method::Get, &url, &spaces_scope(), None)
21 .await?;
22 parse_tenants(&answer.body)
23 .ok_or_else(|| Error::UnexpectedAnswer(format!("{url}: no tenant list")))
24}
25
26fn parse_tenants(body: &Value) -> Option<Vec<Tenant>> {
27 let mut tenants: Vec<Tenant> = body
28 .as_array()?
29 .iter()
30 .filter_map(|entry| {
31 Some(Tenant {
32 id: entry["tenantId"].as_str()?.to_ascii_lowercase(),
33 name: entry["tenantName"].as_str()?.to_owned(),
34 guest: entry["userType"]
35 .as_str()
36 .is_some_and(|kind| kind.eq_ignore_ascii_case("guest")),
37 })
38 })
39 .collect();
40 tenants.sort_by_key(|tenant| tenant.guest);
41 Some(tenants)
42}
43
44#[cfg(test)]
45mod tests {
46 use super::*;
47 use serde_json::json;
48
49 #[test]
50 fn lists_the_home_tenant_first_and_marks_guest_tenants() {
51 let body = json!([
52 {"tenantId": "BBBB-GUEST", "tenantName": "Guest Org", "userType": "guest"},
53 {"tenantId": "aaaa-home", "tenantName": "Home Org", "userType": "member"},
54 {"tenantName": "no id"},
55 ]);
56 assert_eq!(
57 parse_tenants(&body).unwrap(),
58 vec![
59 Tenant {
60 id: "aaaa-home".into(),
61 name: "Home Org".into(),
62 guest: false
63 },
64 Tenant {
65 id: "bbbb-guest".into(),
66 name: "Guest Org".into(),
67 guest: true
68 },
69 ]
70 );
71 assert_eq!(parse_tenants(&json!({"error": 1})), None);
72 }
73}