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(all(feature = "server", feature = "storage-seaorm"))]
87use crate::comma_separated_value::CommaSeparatedValue;
88use serde::{Deserialize, Serialize};
89#[cfg(all(feature = "server", feature = "storage-seaorm"))]
90use std::str::FromStr;
91
92/// Pre-defined roles with hierarchical access control.
93///
94/// These roles are arranged in a hierarchy where higher roles automatically
95/// inherit access from lower roles when using `AccessPolicy::require_role_or_supervisor()`.
96///
97/// **Hierarchy (highest to lowest):**
98/// - `Admin` - Full system access
99/// - `Moderator` - Content moderation and user management
100/// - `Reporter` - Read access with reporting capabilities
101/// - `User` - Basic user access
102///
103/** Updated example imports to reflect current public modules */
104/// # Example Usage
105/// ```rust
106/// use axum_gate::prelude::{Role, Group};
107/// use axum_gate::authz::AccessPolicy;
108///
109/// // Grant access to Moderators and all supervisor roles (Admin)
110/// let policy = AccessPolicy::<Role, Group>::require_role_or_supervisor(Role::Moderator);
111///
112/// // Grant access to specific roles only
113/// let policy = AccessPolicy::<Role, Group>::require_role(Role::Admin)
114/// .or_require_role(Role::Moderator);
115/// ```
116#[derive(
117 Debug,
118 Default,
119 Clone,
120 Copy,
121 Eq,
122 PartialEq,
123 Ord,
124 PartialOrd,
125 Serialize,
126 Deserialize,
127 strum::Display,
128 strum::EnumString,
129)]
130pub enum Role {
131 /// Basic user role with standard application access.
132 ///
133 /// Users have access to core application features but limited
134 /// administrative capabilities.
135 #[default]
136 User,
137 /// Reporter role with read access and reporting capabilities.
138 ///
139 /// Reporters can typically view system information, generate reports,
140 /// and access analytics data.
141 Reporter,
142 /// Moderator role with elevated privileges for content and user management.
143 ///
144 /// Moderators can typically manage content, moderate discussions,
145 /// and have elevated access to user-facing features.
146 Moderator,
147 /// Administrator role with the highest level of access.
148 ///
149 /// Administrators typically have full system access and can perform
150 /// any operation within the application.
151 Admin,
152}
153
154impl AccessHierarchy for Role {}
155
156#[cfg(all(feature = "server", feature = "storage-seaorm"))]
157impl CommaSeparatedValue for Vec<Role> {
158 fn from_csv(value: &str) -> Result<Self, String> {
159 let mut role_str = value.split(',').collect::<Vec<&str>>();
160 let mut roles = Vec::with_capacity(role_str.len());
161 while let Some(r) = role_str.pop() {
162 roles.push(Role::from_str(r).map_err(|e| e.to_string())?);
163 }
164 Ok(roles)
165 }
166
167 fn into_csv(self) -> String {
168 self.into_iter()
169 .map(|g| g.to_string())
170 .collect::<Vec<String>>()
171 .join(",")
172 }
173}