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
use serde_json::{json, Map, Value};
pub struct AuthenticationContext {}
mod claim_types {
pub const ROLE: &str = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role";
}
impl AuthenticationContext {
pub fn new() -> AuthenticationContext {
AuthenticationContext {}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Claim {
pub claim_type: String,
pub value: Value,
}
impl Claim {
pub fn new(claim_type: &str, value: Value) -> Claim {
let claim_type_str = String::from(claim_type);
Claim {
claim_type: claim_type_str,
value: value,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ClaimsPrincipal {
pub claims: Vec<Claim>,
}
impl ClaimsPrincipal {
pub fn new() -> ClaimsPrincipal {
ClaimsPrincipal { claims: Vec::new() }
}
pub fn add_claim(&mut self, claim_type: &str, value: Value) {
self.claims.push(Claim::new(claim_type, value));
}
pub fn is_in_role(&mut self, role: &str) -> bool {
for claim in self.claims.iter() {
if claim.claim_type == claim_types::ROLE && claim.value.as_str().unwrap() == role {
return true;
}
}
return false;
}
pub fn as_claims_map(&mut self) -> Map<String, Value> {
let mut claims: Map<String, Value> = Map::new();
for claim in self.claims.iter() {
if claims.contains_key(&claim.claim_type) {
let result = claims.get_key_value(&claim.claim_type);
let value = result.unwrap();
if !value.1.is_array() {
let value = claims.remove_entry(&claim.claim_type).unwrap().to_owned();
claims.insert(claim.claim_type.to_owned(), json!([value.1, claim.value]));
} else {
let mut value = claims.remove_entry(&claim.claim_type).unwrap().to_owned();
let array_value = value.1.as_array_mut().unwrap();
array_value.insert(array_value.len(), claim.value.to_owned());
claims.insert(claim.claim_type.to_owned(), json!(array_value));
}
} else {
claims.insert(claim.claim_type.to_owned(), claim.value.to_owned());
}
}
return claims;
}
}