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