axum_gate/
roles.rs

1//! Pre-defined hierarchical role system for access control.
2//!
3//! This module provides a built-in role system with four levels arranged in a hierarchy
4//! where higher roles inherit access from lower roles. The hierarchy is:
5//!
6//! **Admin > Moderator > Reporter > User**
7//!
8//! # Role Hierarchy
9//!
10//! When using `AccessPolicy::require_role_or_supervisor()`, higher roles automatically
11//! inherit access from lower roles:
12//!
13//! ```rust
14//! use axum_gate::prelude::Role;
15//! use axum_gate::authz::AccessPolicy;
16//! use axum_gate::prelude::Group;
17//!
18//! // Allow User role and all supervisor roles (Reporter, Moderator, Admin)
19//! let policy = AccessPolicy::<Role, Group>::require_role_or_supervisor(Role::User);
20//!
21//! // Allow only Moderator role and supervisor roles (Admin)
22//! let policy = AccessPolicy::<Role, Group>::require_role_or_supervisor(Role::Moderator);
23//!
24//! // Allow only Admin role (no supervisors above Admin)
25//! let policy = AccessPolicy::<Role, Group>::require_role_or_supervisor(Role::Admin);
26//! ```
27//!
28//! # Using Roles with Gates
29//!
30//! ```rust
31//! use axum_gate::prelude::*;
32//! use axum_gate::authz::AccessPolicy;
33//! use axum_gate::codecs::jwt::{JsonWebToken, JwtClaims};
34//! use axum_gate::accounts::Account;
35//! use std::sync::Arc;
36//!
37//! # let jwt_codec = Arc::new(JsonWebToken::<JwtClaims<Account<Role, Group>>>::default());
38//! // Exact role match (only Admin)
39//! let admin_gate = Gate::cookie("my-app", Arc::clone(&jwt_codec))
40//!     .with_policy(AccessPolicy::<Role, Group>::require_role(Role::Admin));
41//!
42//! // Multiple specific roles
43//! let staff_gate = Gate::cookie("my-app", Arc::clone(&jwt_codec))
44//!     .with_policy(
45//!         AccessPolicy::<Role, Group>::require_role(Role::Admin)
46//!             .or_require_role(Role::Moderator)
47//!     );
48//!
49//! // Hierarchical access (User + all supervisors)
50//! let user_gate = Gate::cookie("my-app", jwt_codec)
51//!     .with_policy(AccessPolicy::<Role, Group>::require_role_or_supervisor(Role::User));
52//! ```
53//!
54//! # Creating Custom Roles
55//!
56//! Create your own role hierarchy by implementing the required traits:
57//!
58//! ```rust
59//! use serde::{Deserialize, Serialize};
60//! use axum_gate::authz::AccessHierarchy;
61//!
62//! #[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
63//! enum CompanyRole {
64//!     #[default]
65//!     Employee,      // Lowest privilege
66//!     TeamLead,
67//!     Manager,
68//!     Director,      // Highest privilege
69//! }
70//!
71//! impl std::fmt::Display for CompanyRole {
72//!     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73//!         match self {
74//!             CompanyRole::Employee => write!(f, "Employee"),
75//!             CompanyRole::TeamLead => write!(f, "TeamLead"),
76//!             CompanyRole::Manager => write!(f, "Manager"),
77//!             CompanyRole::Director => write!(f, "Director"),
78//!         }
79//!     }
80//! }
81//!
82//! impl AccessHierarchy for CompanyRole {}
83//! ```
84
85use crate::authz::AccessHierarchy;
86#[cfg(feature = "storage-seaorm")]
87use crate::comma_separated_value::CommaSeparatedValue;
88
89#[cfg(feature = "storage-seaorm")]
90use std::str::FromStr;
91
92use serde::{Deserialize, Serialize};
93
94/// Pre-defined roles with hierarchical access control.
95///
96/// These roles are arranged in a hierarchy where higher roles automatically
97/// inherit access from lower roles when using `AccessPolicy::require_role_or_supervisor()`.
98///
99/// **Hierarchy (highest to lowest):**
100/// - `Admin` - Full system access
101/// - `Moderator` - Content moderation and user management
102/// - `Reporter` - Read access with reporting capabilities
103/// - `User` - Basic user access
104///
105/** Updated example imports to reflect current public modules */
106/// # Example Usage
107/// ```rust
108/// use axum_gate::prelude::{Role, Group};
109/// use axum_gate::authz::AccessPolicy;
110///
111/// // Grant access to Moderators and all supervisor roles (Admin)
112/// let policy = AccessPolicy::<Role, Group>::require_role_or_supervisor(Role::Moderator);
113///
114/// // Grant access to specific roles only
115/// let policy = AccessPolicy::<Role, Group>::require_role(Role::Admin)
116///     .or_require_role(Role::Moderator);
117/// ```
118#[derive(
119    Debug,
120    Default,
121    Clone,
122    Copy,
123    Eq,
124    PartialEq,
125    Ord,
126    PartialOrd,
127    Serialize,
128    Deserialize,
129    strum::Display,
130    strum::EnumString,
131)]
132pub enum Role {
133    /// Basic user role with standard application access.
134    ///
135    /// Users have access to core application features but limited
136    /// administrative capabilities.
137    #[default]
138    User,
139    /// Reporter role with read access and reporting capabilities.
140    ///
141    /// Reporters can typically view system information, generate reports,
142    /// and access analytics data.
143    Reporter,
144    /// Moderator role with elevated privileges for content and user management.
145    ///
146    /// Moderators can typically manage content, moderate discussions,
147    /// and have elevated access to user-facing features.
148    Moderator,
149    /// Administrator role with the highest level of access.
150    ///
151    /// Administrators typically have full system access and can perform
152    /// any operation within the application.
153    Admin,
154}
155
156impl AccessHierarchy for Role {}
157
158#[cfg(feature = "storage-seaorm")]
159impl CommaSeparatedValue for Vec<Role> {
160    fn from_csv(value: &str) -> Result<Self, String> {
161        let mut role_str = value.split(',').collect::<Vec<&str>>();
162        let mut roles = Vec::with_capacity(role_str.len());
163        while let Some(r) = role_str.pop() {
164            roles.push(Role::from_str(r).map_err(|e| e.to_string())?);
165        }
166        Ok(roles)
167    }
168
169    fn into_csv(self) -> String {
170        self.into_iter()
171            .map(|g| g.to_string())
172            .collect::<Vec<String>>()
173            .join(",")
174    }
175}