pub mod audit;
pub mod auth;
pub mod client_identity;
#[cfg(feature = "cache")]
pub mod nonce;
pub mod permission_check;
pub mod rate_limit;
pub mod request_id;
pub mod request_log;
pub mod role;
pub mod security_headers;
#[cfg(feature = "cache")]
pub use auth::{session_resolver, SessionResolverState};
pub use audit::{AuditLayer, AuditRule, AuditService};
pub use auth::{AuthLayer, AuthService};
pub use client_identity::{ClientIdentityLayer, ClientIdentityService, ClientIp, RequestStart};
#[cfg(feature = "cache")]
pub use crate::idempotency::idempotent_run;
#[cfg(feature = "cache")]
pub use nonce::{nonce, NonceState};
pub use permission_check::{PermissionCheckLayer, PermissionCheckService, PermissionRule};
pub use rate_limit::{IpWindow, RateLimitLayer, RateLimitService};
pub use request_id::{RequestIdLayer, RequestIdService};
pub use request_log::{RequestLogLayer, RequestLogService};
pub use role::{RequireRoleLayer, RequireRoleService};
pub use security_headers::{SecurityHeadersLayer, SecurityHeadersService};
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use wordval_core::api::ApiError;
use crate::middleware::auth::PathPattern;
pub(crate) trait RuleKey {
fn pattern(&self) -> &PathPattern;
fn methods(&self) -> &[String];
fn is_guard(&self) -> bool;
fn specificity(&self) -> (usize, usize);
}
pub(crate) fn rule_specificity(path: &str) -> (usize, usize) {
let mut segments = 0usize;
let mut statics = 0usize;
for s in path.split('/').filter(|s| !s.is_empty()) {
segments += 1;
if !(s.starts_with('{') && s.ends_with('}')) && s != "*" {
statics += 1;
}
}
(segments, statics)
}
pub(crate) fn best_rule<'a, T: RuleKey>(rules: &'a [T], path: &str, method: &str) -> Option<&'a T> {
let best = best_rule_for_method(rules, path, method);
if !method.eq_ignore_ascii_case("HEAD") {
return best;
}
if best.is_some_and(|r| r.is_guard()) {
return best;
}
let get = best_rule_for_method(rules, path, "GET");
match (best, get) {
(_, Some(get)) if get.is_guard() => Some(get),
(Some(best), _) => Some(best),
(None, get) => get,
}
}
fn best_rule_for_method<'a, T: RuleKey>(
rules: &'a [T],
path: &str,
method: &str,
) -> Option<&'a T> {
let mut best: Option<&T> = None;
for r in rules {
if !r.pattern().matches_normalized(path) {
continue;
}
if !r.methods().is_empty() && !r.methods().iter().any(|m| m.eq_ignore_ascii_case(method)) {
continue;
}
best = Some(match best {
None => r,
Some(b) => match (r.is_guard(), b.is_guard()) {
(true, false) => r,
(false, true) => b,
_ => {
if r.specificity() > b.specificity() {
r
} else {
b
}
}
},
});
}
best
}
pub(crate) fn error_response(err: ApiError) -> Response {
err.into_response()
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CurrentUser {
pub id: i64,
pub username: String,
pub roles: Vec<String>,
pub permissions: Vec<String>,
#[serde(default)]
pub is_admin: bool,
#[serde(default)]
pub tenant_id: Option<i64>,
#[serde(default)]
pub store_id: Option<i64>,
}
impl CurrentUser {
pub fn has_role(&self, role: &str) -> bool {
self.roles.iter().any(|r| r == role)
}
pub fn has_perm(&self, perm: &str) -> bool {
self.permissions.iter().any(|p| p == perm)
}
pub fn is_admin_user(&self) -> bool {
self.is_admin || self.permissions.iter().any(|p| p == "*" || p == "*:*:*")
}
pub fn is_authorized(&self, permission: &str) -> bool {
self.is_admin_user() || self.has_perm(permission)
}
}
#[cfg(feature = "cache")]
#[allow(clippy::too_many_arguments)]
pub async fn create_session(
cache: &wordval_cache::SharedCache,
user_id: i64,
username: &str,
roles: &[String],
permissions: &[String],
is_admin: bool,
tenant_id: Option<i64>,
store_id: Option<i64>,
ttl_secs: u64,
) -> Result<String, wordval_core::api::ApiError> {
use wordval_cache::Cache;
use wordval_core::api::ApiError;
let token = wordval_utils::Sid::uuid();
let session = CurrentUser {
id: user_id,
username: username.to_string(),
roles: roles.to_vec(),
permissions: permissions.to_vec(),
is_admin,
tenant_id,
store_id,
};
cache
.set_ex(&format!("session:{}", token), &session, ttl_secs)
.await
.map_err(|e| ApiError::internal(format!("创建会话失败: {}", e)))?;
Ok(token)
}
#[cfg(feature = "cache")]
pub async fn destroy_session(
cache: &wordval_cache::SharedCache,
token: &str,
) -> Result<(), wordval_core::api::ApiError> {
use wordval_cache::Cache;
use wordval_core::api::ApiError;
cache
.del(&format!("session:{}", token))
.await
.map_err(|e| ApiError::internal(format!("销毁会话失败: {}", e)))
}
#[cfg(feature = "cache")]
pub async fn refresh_session(
cache: &wordval_cache::SharedCache,
token: &str,
ttl_secs: u64,
) -> Result<(), wordval_core::api::ApiError> {
use wordval_cache::Cache;
use wordval_core::api::ApiError;
let key = format!("session:{}", token);
let session = cache
.get::<CurrentUser>(&key)
.await
.map_err(|e| ApiError::internal(format!("续期会话失败: {}", e)))?
.ok_or_else(|| {
ApiError::unauthorized(wordval_core::error_registry::error_message_of(
wordval_core::error_registry::ErrorCode::Unauthorized,
))
})?;
cache
.set_ex(&key, &session, ttl_secs)
.await
.map_err(|e| ApiError::internal(format!("续期会话失败: {}", e)))
}