eidetica/auth/types/
conversions.rs1use super::permissions::{KeyStatus, Permission};
7use crate::auth::errors::AuthError;
8
9impl From<Permission> for String {
10 fn from(permission: Permission) -> Self {
11 match permission {
12 Permission::Read => "read".to_string(),
13 Permission::Write(priority) => format!("write:{priority}"),
14 Permission::Admin(priority) => format!("admin:{priority}"),
15 }
16 }
17}
18
19impl TryFrom<String> for Permission {
20 type Error = AuthError;
21
22 fn try_from(s: String) -> Result<Self, Self::Error> {
23 let parts = s.split(':').collect::<Vec<&str>>();
24 match parts[0] {
25 "read" => Ok(Permission::Read),
26 "write" => {
27 if parts.len() != 2 {
28 return Err(AuthError::PermissionRequiresPriority {
29 permission_type: "Write".to_string(),
30 });
31 }
32 let priority =
33 parts[1]
34 .parse::<u32>()
35 .map_err(|_| AuthError::InvalidPriorityValue {
36 value: parts[1].to_string(),
37 })?;
38 Ok(Permission::Write(priority))
39 }
40 "admin" => {
41 if parts.len() != 2 {
42 return Err(AuthError::PermissionRequiresPriority {
43 permission_type: "Admin".to_string(),
44 });
45 }
46 let priority =
47 parts[1]
48 .parse::<u32>()
49 .map_err(|_| AuthError::InvalidPriorityValue {
50 value: parts[1].to_string(),
51 })?;
52 Ok(Permission::Admin(priority))
53 }
54 _ => Err(AuthError::InvalidPermissionString { value: s }),
55 }
56 }
57}
58
59impl From<KeyStatus> for String {
60 fn from(status: KeyStatus) -> Self {
61 match status {
62 KeyStatus::Active => "active".to_string(),
63 KeyStatus::Revoked => "revoked".to_string(),
64 }
65 }
66}
67
68impl TryFrom<String> for KeyStatus {
69 type Error = AuthError;
70
71 fn try_from(s: String) -> Result<Self, Self::Error> {
72 match s.as_str() {
73 "active" => Ok(KeyStatus::Active),
74 "revoked" => Ok(KeyStatus::Revoked),
75 _ => Err(AuthError::InvalidKeyStatus { value: s }),
76 }
77 }
78}