Skip to main content

spoolframe_types/
role.rs

1//! A user's role on a server: what clients and the web UI show and
2//! switch on.
3
4use serde::{Deserialize, Serialize};
5
6#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
7#[cfg_attr(feature = "uniffi", derive(uniffi::Enum))]
8#[serde(rename_all = "snake_case")]
9pub enum Role {
10    /// Manages other users and the server.
11    Admin,
12    /// Watches, and manages only their own account.
13    #[default]
14    Consumer,
15    /// A role this build does not know, from a newer server. Treat it as
16    /// the least it could be: no more than a consumer.
17    #[serde(other)]
18    Unknown,
19}
20
21impl Role {
22    /// The name on the wire.
23    pub fn as_str(self) -> &'static str {
24        match self {
25            Role::Admin => "admin",
26            Role::Consumer => "consumer",
27            Role::Unknown => "unknown",
28        }
29    }
30
31    pub fn is_admin(self) -> bool {
32        self == Role::Admin
33    }
34}
35
36impl std::str::FromStr for Role {
37    type Err = String;
38
39    /// `admin` or `consumer`, as the CLI takes them.
40    fn from_str(s: &str) -> Result<Self, Self::Err> {
41        match s.trim().to_ascii_lowercase().as_str() {
42            "admin" => Ok(Role::Admin),
43            "consumer" => Ok(Role::Consumer),
44            other => Err(format!("{other:?} is not a role: use admin or consumer")),
45        }
46    }
47}
48
49impl std::fmt::Display for Role {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        f.write_str(self.as_str())
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn a_role_from_a_newer_server_is_unknown() {
61        let role: Role = serde_json::from_str("\"moderator\"").unwrap();
62        assert_eq!(role, Role::Unknown);
63        assert!(!role.is_admin());
64    }
65
66    #[test]
67    fn roles_read_as_the_cli_writes_them() {
68        assert_eq!("Admin".parse::<Role>(), Ok(Role::Admin));
69        assert_eq!("consumer".parse::<Role>(), Ok(Role::Consumer));
70        assert!("unknown".parse::<Role>().is_err());
71    }
72}