kegani 0.1.0

A developer-friendly, ergonomic, production-ready Rust web framework
Documentation
//! JWT claims for Kegani
//!
//! Defines the structure of JWT claims.

use serde::{Deserialize, Serialize};

/// JWT claims
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Claims {
    /// Subject (usually user ID)
    pub subject: String,
    /// User roles/permissions
    #[serde(default)]
    pub roles: Vec<String>,
    /// Additional custom claims
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra: Option<std::collections::HashMap<String, serde_json::Value>>,
}

impl Claims {
    /// Create new claims for a user
    pub fn new(subject: &str) -> Self {
        Self {
            subject: subject.to_string(),
            roles: vec![],
            extra: None,
        }
    }

    /// Add a role
    pub fn with_role(mut self, role: &str) -> Self {
        self.roles.push(role.to_string());
        self
    }

    /// Add multiple roles
    pub fn with_roles(mut self, roles: Vec<&str>) -> Self {
        self.roles.extend(roles.into_iter().map(String::from));
        self
    }

    /// Check if has a specific role
    pub fn has_role(&self, role: &str) -> bool {
        self.roles.iter().any(|r| r == role)
    }
}

impl Default for Claims {
    fn default() -> Self {
        Self::new("anonymous")
    }
}