pub const BUILTIN_ACTION_NAMES: &[&str] = &["add", "put", "del", "get", "select", "table"];
#[cfg(feature = "mysql")]
use crate::action::builtin::TableAction;
#[cfg(feature = "mysql")]
use crate::action::builtin::{AddAction, DelAction, GetAction, PutAction, SelectAction};
use crate::action::{Action, ActionContext, ApiResponse, User};
use crate::error::BaseError;
use crate::table::TableConfig;
use std::collections::HashMap;
use std::sync::Arc;
pub struct ModuleRouter {
module_name: String,
display_name: String,
table_config: Option<Arc<TableConfig>>,
actions: HashMap<String, Box<dyn Action>>,
default_permissions: Vec<String>,
}
impl ModuleRouter {
pub fn new(module_name: impl Into<String>, display_name: impl Into<String>) -> Self {
Self {
module_name: module_name.into(),
display_name: display_name.into(),
table_config: None,
actions: HashMap::new(),
default_permissions: Vec::new(),
}
}
pub fn with_table_config(mut self, config: Arc<TableConfig>) -> Self {
self.table_config = Some(config);
self
}
pub fn table_config(self, config: Arc<TableConfig>) -> Self {
self.with_table_config(config)
}
pub fn default_permissions(mut self, permissions: Vec<String>) -> Self {
self.default_permissions = permissions;
self
}
pub fn register_action<A: Action + 'static>(mut self, action: A) -> Self {
let name = action.name().to_string();
self.actions.insert(name, Box::new(action));
self
}
#[cfg(feature = "mysql")]
pub fn register_builtin_actions(mut self) -> Result<Self, BaseError> {
let table_config = self
.table_config
.as_ref()
.ok_or(BaseError::TableConfigNotSet)?
.clone();
for action_name in BUILTIN_ACTION_NAMES {
let action: Box<dyn Action> = match *action_name {
"add" => Box::new(AddAction::new(table_config.clone())),
"put" => Box::new(PutAction::new(table_config.clone())),
"del" => Box::new(DelAction::new(table_config.clone())),
"get" => Box::new(GetAction::new(table_config.clone())),
"select" => Box::new(SelectAction::new(table_config.clone())),
"table" => Box::new(TableAction::new(table_config.clone())),
_ => continue,
};
self.actions.insert(action_name.to_string(), action);
}
Ok(self)
}
pub async fn dispatch(
&self,
action_name: &str,
mut context: ActionContext,
) -> Result<ApiResponse, BaseError> {
let action = self
.actions
.get(action_name)
.ok_or_else(|| BaseError::ActionNotFound(action_name.to_string()))?;
if let Some(table_config) = &self.table_config {
context = context.with_table_config(table_config.clone());
}
if action.is_public() {
return action.execute(context).await;
}
let user = context
.user
.as_ref()
.ok_or_else(|| BaseError::Unauthorized("需要登录".to_string()))?;
if !self.default_permissions.is_empty()
&& !self.check_permissions(user, &self.default_permissions)
{
return Err(BaseError::PermissionDenied(format!(
"缺少模块权限: {:?}",
self.default_permissions
)));
}
let action_permissions = action.permissions();
if !action_permissions.is_empty() {
let permission_names: Vec<String> = action_permissions
.iter()
.map(|p| p.name().to_string())
.collect();
if !self.check_permissions(user, &permission_names) {
return Err(BaseError::PermissionDenied(format!(
"缺少 Action 权限: {:?}",
permission_names
)));
}
}
action.execute(context).await
}
pub async fn dispatch_with_global(
&self,
action_name: &str,
request: crate::action::Request,
) -> Result<ApiResponse, BaseError> {
let context = ActionContext::new_with_global_tools(request)?;
self.dispatch(action_name, context).await
}
fn check_permissions(&self, user: &User, required_permissions: &[String]) -> bool {
required_permissions
.iter()
.all(|perm| user.has_permission(perm))
}
pub fn module_name(&self) -> &str {
&self.module_name
}
pub fn display_name(&self) -> &str {
&self.display_name
}
pub fn action_names(&self) -> Vec<String> {
self.actions.keys().cloned().collect()
}
pub fn get_table_config(&self) -> Option<&Arc<TableConfig>> {
self.table_config.as_ref()
}
}