use crate::claims::{claim_types, Claim};
use serde_json::{json, Map, Value};
#[cfg(feature = "oauth2")]
use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
#[derive(Debug, Clone)]
pub struct ClaimsIdentity {
pub claims: Vec<Claim>,
pub upn: String,
}
impl ClaimsIdentity {
pub fn new(upn: &str) -> ClaimsIdentity {
ClaimsIdentity {
claims: Vec::new(),
upn: String::from(upn),
}
}
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;
}
#[cfg(feature = "oauth2")]
pub fn as_jwt(&mut self, signing_key: EncodingKey) -> String {
encode(
&Header::new(Algorithm::RS256),
&self.as_claims_map(),
&signing_key,
)
.unwrap()
}
}