BlueGit

ict rusty-teams

Files

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

tenants.rs

tenants.rs 2.6 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 /// The account's user id in this tenant; a guest has its own id in every tenant.
15 pub user_id: Option<String>,
16}
17
18/// Every tenant of the account, home tenant first.
19pub async fn list_tenants(session: &Session) -> Result<Vec<Tenant>> {
20 let url =
21 format!("https://teams.cloud.microsoft/api/mt/{DEFAULT_MT_REGION}/beta/users/tenants");
22 let answer = session
23 .request(Method::Get, &url, &spaces_scope(), None)
24 .await?;
25 parse_tenants(&answer.body)
26 .ok_or_else(|| Error::UnexpectedAnswer(format!("{url}: no tenant list")))
27}
28
29fn parse_tenants(body: &Value) -> Option<Vec<Tenant>> {
30 let mut tenants: Vec<Tenant> = body
31 .as_array()?
32 .iter()
33 .filter_map(|entry| {
34 Some(Tenant {
35 id: entry["tenantId"].as_str()?.to_ascii_lowercase(),
36 name: entry["tenantName"].as_str()?.to_owned(),
37 guest: entry["userType"]
38 .as_str()
39 .is_some_and(|kind| kind.eq_ignore_ascii_case("guest")),
40 user_id: entry["userId"].as_str().map(str::to_ascii_lowercase),
41 })
42 })
43 .collect();
44 tenants.sort_by_key(|tenant| tenant.guest);
45 Some(tenants)
46}
47
48#[cfg(test)]
49mod tests {
50 use super::*;
51 use serde_json::json;
52
53 #[test]
54 fn lists_the_home_tenant_first_and_marks_guest_tenants() {
55 let body = json!([
56 {"tenantId": "BBBB-GUEST", "tenantName": "Guest Org", "userType": "guest", "userId": "AB-12"},
57 {"tenantId": "aaaa-home", "tenantName": "Home Org", "userType": "member"},
58 {"tenantName": "no id"},
59 ]);
60 assert_eq!(
61 parse_tenants(&body).unwrap(),
62 vec![
63 Tenant {
64 id: "aaaa-home".into(),
65 name: "Home Org".into(),
66 guest: false,
67 user_id: None,
68 },
69 Tenant {
70 id: "bbbb-guest".into(),
71 name: "Guest Org".into(),
72 guest: true,
73 user_id: Some("ab-12".into()),
74 },
75 ]
76 );
77 assert_eq!(parse_tenants(&json!({"error": 1})), None);
78 }
79}