1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum UserRole {
PlatformAdmin,
FunctionOwner,
DataOwnerManager(String),
DataOwner(String),
Invalid,
}
impl Default for UserRole {
fn default() -> Self {
UserRole::Invalid
}
}
impl UserRole {
pub fn new(role: &str, attribute: &str) -> Self {
match role {
"PlatformAdmin" => UserRole::PlatformAdmin,
"FunctionOwner" => UserRole::FunctionOwner,
"DataOwnerManager" => UserRole::DataOwnerManager(attribute.to_owned()),
"DataOwner" => UserRole::DataOwner(attribute.to_owned()),
_ => UserRole::Invalid,
}
}
#[allow(clippy::should_implement_trait)]
pub fn from_str(role: &str) -> UserRole {
match role {
"PlatformAdmin" => UserRole::PlatformAdmin,
"FunctionOwner" => UserRole::FunctionOwner,
_ => {
if let Some(a) = role.strip_prefix("DataOwner-") {
UserRole::DataOwner(a.to_owned())
} else if let Some(a) = role.strip_prefix("DataOwnerManager-") {
UserRole::DataOwnerManager(a.to_owned())
} else {
UserRole::Invalid
}
}
}
}
pub fn is_platform_admin(&self) -> bool {
matches!(self, UserRole::PlatformAdmin)
}
pub fn is_function_owner(&self) -> bool {
matches!(self, UserRole::FunctionOwner)
}
pub fn is_data_owner(&self) -> bool {
matches!(self, UserRole::DataOwnerManager(_)) || matches!(self, UserRole::DataOwner(_))
}
}
impl fmt::Display for UserRole {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
UserRole::PlatformAdmin => write!(f, "PlatformAdmin"),
UserRole::FunctionOwner => write!(f, "FunctionOwner"),
UserRole::DataOwnerManager(s) => write!(f, "DataOwnerManager-{}", s),
UserRole::DataOwner(s) => write!(f, "DataOwner-{}", s),
UserRole::Invalid => write!(f, "Invalid"),
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct UserAuthClaims {
pub sub: String,
pub role: String,
pub iss: String,
pub exp: u64,
}
impl UserAuthClaims {
pub fn get_role(&self) -> UserRole {
UserRole::from_str(&self.role)
}
}
impl std::fmt::Display for UserAuthClaims {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{{ user: {}, role: {:?} }}", self.sub, self.get_role())
}
}