ws_auth/identity/
mod.rs

1use crate::claims::{claim_types, Claim};
2use serde_json::{json, Map, Value};
3
4#[cfg(feature = "oauth2")]
5use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
6
7#[derive(Debug, Clone)]
8pub struct ClaimsIdentity {
9    pub claims: Vec<Claim>,
10    pub upn: String,
11}
12
13impl ClaimsIdentity {
14    pub fn new(upn: &str) -> ClaimsIdentity {
15        ClaimsIdentity {
16            claims: Vec::new(),
17            upn: String::from(upn),
18        }
19    }
20
21    pub fn add_claim(&mut self, claim_type: &str, value: Value) {
22        self.claims.push(Claim::new(claim_type, value));
23    }
24
25    pub fn is_in_role(&mut self, role: &str) -> bool {
26        for claim in self.claims.iter() {
27            if claim.claim_type == claim_types::ROLE && claim.value.as_str().unwrap() == role {
28                return true;
29            }
30        }
31
32        return false;
33    }
34
35    pub fn as_claims_map(&mut self) -> Map<String, Value> {
36        let mut claims: Map<String, Value> = Map::new();
37
38        for claim in self.claims.iter() {
39            if claims.contains_key(&claim.claim_type) {
40                let result = claims.get_key_value(&claim.claim_type);
41                let value = result.unwrap();
42
43                if !value.1.is_array() {
44                    let value = claims.remove_entry(&claim.claim_type).unwrap().to_owned();
45                    claims.insert(claim.claim_type.to_owned(), json!([value.1, claim.value]));
46                } else {
47                    let mut value = claims.remove_entry(&claim.claim_type).unwrap().to_owned();
48                    let array_value = value.1.as_array_mut().unwrap();
49                    array_value.insert(array_value.len(), claim.value.to_owned());
50                    claims.insert(claim.claim_type.to_owned(), json!(array_value));
51                }
52            } else {
53                claims.insert(claim.claim_type.to_owned(), claim.value.to_owned());
54            }
55        }
56
57        return claims;
58    }
59
60    #[cfg(feature = "oauth2")]
61    pub fn as_jwt(&mut self, signing_key: EncodingKey) -> String {
62        encode(
63            &Header::new(Algorithm::RS256),
64            &self.as_claims_map(),
65            &signing_key,
66        )
67        .unwrap()
68    }
69}