use super::roles::Role;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum TokenType {
Auth,
Admin, Refresh,
Password,
Elevated,
None,
}
impl TokenType {
pub fn to_str(&self) -> &str {
match self {
TokenType::Auth => "auth",
TokenType::Admin => "admin",
TokenType::Refresh => "refresh",
TokenType::Password => "password",
TokenType::Elevated => "elevated",
TokenType::None => "",
}
}
pub fn to_string(&self) -> String {
self.to_str().to_owned()
}
pub fn from_str(data: &str) -> Self {
match data {
"auth" => Self::Auth,
"admin" => Self::Admin,
"refresh" => Self::Refresh,
"password" => Self::Password,
"elevated" => Self::Elevated,
_ => Self::None,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PasswdClaims {
pub sub: String, pub exp: u64, pub kind: TokenType,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Claims {
pub sub: String, pub role: Role, pub org_id: String, pub exp: u64, pub kind: TokenType,
}
impl Claims {
pub fn to_map(&self) -> HashMap<String, String> {
let mut map = HashMap::new();
map.insert("sub".into(), self.sub.clone());
map.insert("org_id".into(), self.org_id.clone());
map.insert("role".into(), self.role.to_str().to_owned());
map.insert("exp".into(), self.exp.to_string());
map.insert("type".into(), self.kind.to_string());
map
}
pub fn from_map(mut map: HashMap<String, String>) -> Result<Self, String> {
let sub = map
.remove("sub")
.ok_or_else(|| "Missing `sub` in claims map".to_string())?;
let org_id = map
.remove("org_id")
.ok_or_else(|| "Missing `org_id` in claims map".to_string())?;
let role_str = map
.remove("role")
.ok_or_else(|| "Missing `role` in claims map".to_string())?;
let exp_str = map
.remove("exp")
.ok_or_else(|| "Missing `exp` in claims map".to_string())?;
let kind_str = map
.remove("type")
.ok_or_else(|| "Missing `kind` in claims map".to_string())?;
let exp = exp_str
.parse::<u64>()
.map_err(|e| format!("Failed to parse `exp`: {}", e))?;
let role = Role::from_str(&role_str);
let kind = TokenType::from_str(&kind_str);
Ok(Claims {
sub,
org_id,
role,
exp,
kind,
})
}
}