repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/entities/casbin_rule.rs | server/model/src/admin/entities/casbin_rule.rs | //! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "casbin_rule")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i64,
#[sea_orm(column_type = "Text")]
pub ptype: String,
#[sea_orm(column_type = "Text", nullable)]
pub v0: Option<String>,
#[sea_orm(column_type = "Text", nullable)]
pub v1: Option<String>,
#[sea_orm(column_type = "Text", nullable)]
pub v2: Option<String>,
#[sea_orm(column_type = "Text", nullable)]
pub v3: Option<String>,
#[sea_orm(column_type = "Text", nullable)]
pub v4: Option<String>,
#[sea_orm(column_type = "Text", nullable)]
pub v5: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/entities/mod.rs | server/model/src/admin/entities/mod.rs | //! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
pub mod prelude;
pub mod casbin_rule;
pub mod sea_orm_active_enums;
pub mod sys_access_key;
pub mod sys_domain;
pub mod sys_endpoint;
pub mod sys_login_log;
pub mod sys_menu;
pub mod sys_operation_log;
pub mod sys_organization;
pub mod sys_role;
pub mod sys_role_menu;
pub mod sys_tokens;
pub mod sys_user;
pub mod sys_user_role;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/entities/sys_endpoint.rs | server/model/src/admin/entities/sys_endpoint.rs | //! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::Serialize;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize)]
#[sea_orm(table_name = "sys_endpoint")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub id: String,
#[sea_orm(column_type = "Text")]
pub path: String,
#[sea_orm(column_type = "Text")]
pub method: String,
#[sea_orm(column_type = "Text")]
pub action: String,
#[sea_orm(column_type = "Text")]
pub resource: String,
#[sea_orm(column_type = "Text")]
pub controller: String,
#[sea_orm(column_type = "Text", nullable)]
pub summary: Option<String>,
pub created_at: DateTime,
pub updated_at: Option<DateTime>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/entities/sys_tokens.rs | server/model/src/admin/entities/sys_tokens.rs | //! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "sys_tokens")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub id: String,
#[sea_orm(column_type = "Text")]
pub access_token: String,
#[sea_orm(column_type = "Text")]
pub refresh_token: String,
#[sea_orm(column_type = "Text")]
pub status: String,
#[sea_orm(column_type = "Text")]
pub user_id: String,
#[sea_orm(column_type = "Text")]
pub username: String,
#[sea_orm(column_type = "Text")]
pub domain: String,
pub login_time: DateTime,
#[sea_orm(column_type = "Text")]
pub ip: String,
pub port: Option<i32>,
#[sea_orm(column_type = "Text")]
pub address: String,
#[sea_orm(column_type = "Text")]
pub user_agent: String,
#[sea_orm(column_type = "Text")]
pub request_id: String,
#[sea_orm(column_type = "Text")]
pub r#type: String,
pub created_at: DateTime,
#[sea_orm(column_type = "Text")]
pub created_by: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/entities/sys_role_menu.rs | server/model/src/admin/entities/sys_role_menu.rs | //! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "sys_role_menu")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub role_id: String,
#[sea_orm(primary_key, auto_increment = false)]
pub menu_id: i32,
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub domain: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::sys_menu::Entity",
from = "Column::MenuId",
to = "super::sys_menu::Column::Id"
)]
SysMenu,
#[sea_orm(
belongs_to = "super::sys_role::Entity",
from = "Column::RoleId",
to = "super::sys_role::Column::Id"
)]
SysRole,
}
impl Related<super::sys_menu::Entity> for Entity {
fn to() -> RelationDef {
Relation::SysMenu.def()
}
}
impl Related<super::sys_role::Entity> for Entity {
fn to() -> RelationDef {
Relation::SysRole.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/entities/sys_menu.rs | server/model/src/admin/entities/sys_menu.rs | //! `SeaORM` Entity, @generated by sea-orm-codegen 1.0.0
use sea_orm::entity::prelude::*;
use serde::Serialize;
use super::sea_orm_active_enums::{MenuType, Status};
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize)]
#[sea_orm(table_name = "sys_menu")]
pub struct Model {
#[sea_orm(primary_key)]
pub id: i32,
pub menu_type: MenuType,
pub menu_name: String,
pub icon_type: Option<i32>,
pub icon: Option<String>,
#[sea_orm(unique)]
pub route_name: String,
pub route_path: String,
pub component: String,
pub path_param: Option<String>,
pub status: Status,
pub active_menu: Option<String>,
pub hide_in_menu: Option<bool>,
#[sea_orm(column_type = "Text")]
pub pid: String,
pub sequence: i32,
pub i18n_key: Option<String>,
pub keep_alive: Option<bool>,
pub constant: bool,
pub href: Option<String>,
pub multi_tab: Option<bool>,
pub created_at: DateTime,
#[sea_orm(column_type = "Text")]
pub created_by: String,
pub updated_at: Option<DateTime>,
#[sea_orm(column_type = "Text", nullable)]
pub updated_by: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(has_many = "super::sys_role_menu::Entity")]
SysRoleMenu,
}
impl Related<super::sys_role_menu::Entity> for Entity {
fn to() -> RelationDef {
Relation::SysRoleMenu.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/entities/sys_user_role.rs | server/model/src/admin/entities/sys_user_role.rs | //! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
#[sea_orm(table_name = "sys_user_role")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub user_id: String,
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub role_id: String,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
#[sea_orm(
belongs_to = "super::sys_user::Entity",
from = "Column::UserId",
to = "super::sys_user::Column::Id"
)]
SysUser,
#[sea_orm(
belongs_to = "super::sys_role::Entity",
from = "Column::RoleId",
to = "super::sys_role::Column::Id"
)]
SysRole,
}
impl Related<super::sys_user::Entity> for Entity {
fn to() -> RelationDef {
Relation::SysUser.def()
}
}
impl Related<super::sys_role::Entity> for Entity {
fn to() -> RelationDef {
Relation::SysRole.def()
}
}
impl ActiveModelBehavior for ActiveModel {}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/entities/sys_organization.rs | server/model/src/admin/entities/sys_organization.rs | //! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.0
use sea_orm::entity::prelude::*;
use serde::Serialize;
use super::sea_orm_active_enums::Status;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq, Serialize)]
#[sea_orm(table_name = "sys_organization")]
pub struct Model {
#[sea_orm(primary_key, auto_increment = false, column_type = "Text")]
pub id: String,
#[sea_orm(column_type = "Text", unique)]
pub code: String,
#[sea_orm(column_type = "Text")]
pub name: String,
#[sea_orm(column_type = "Text", nullable)]
pub description: Option<String>,
#[sea_orm(column_type = "Text")]
pub pid: String,
pub status: Status,
pub created_at: DateTime,
#[sea_orm(column_type = "Text")]
pub created_by: String,
pub updated_at: Option<DateTime>,
#[sea_orm(column_type = "Text", nullable)]
pub updated_by: Option<String>,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_access_key.rs | server/model/src/admin/input/sys_access_key.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
use validator::Validate;
use crate::admin::entities::sea_orm_active_enums::Status;
#[derive(Debug, Serialize, Deserialize)]
pub struct AccessKeyPageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
#[derive(Deserialize, Validate)]
pub struct AccessKeyInput {
pub domain: String,
pub status: Status,
#[validate(length(max = 200, message = "Description must not exceed 200 characters"))]
pub description: Option<String>,
}
pub type CreateAccessKeyInput = AccessKeyInput;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_authorization.rs | server/model/src/admin/input/sys_authorization.rs | use serde::{Deserialize, Serialize};
use validator::Validate;
#[derive(Debug, Deserialize, Serialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct AssignPermissionDto {
#[validate(length(min = 1, message = "domain cannot be empty"))]
pub domain: String,
#[validate(length(min = 1, message = "Role ID cannot be empty"))]
pub role_id: String,
#[validate(length(min = 1, message = "Permissions array cannot be empty"))]
pub permissions: Vec<String>,
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct AssignRouteDto {
#[validate(length(min = 1, message = "domain cannot be empty"))]
pub domain: String,
#[validate(length(min = 1, message = "Role ID cannot be empty"))]
pub role_id: String,
#[validate(length(min = 1, message = "Routes array cannot be empty"))]
pub route_ids: Vec<i32>,
}
#[derive(Debug, Deserialize, Serialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct AssignUserDto {
#[validate(length(min = 1, message = "Role ID cannot be empty"))]
pub role_id: String,
#[validate(length(min = 1, message = "Users array cannot be empty"))]
pub user_ids: Vec<String>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_operation_log.rs | server/model/src/admin/input/sys_operation_log.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
#[derive(Debug, Serialize, Deserialize)]
pub struct OperationLogPageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_user.rs | server/model/src/admin/input/sys_user.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
use validator::Validate;
use crate::admin::entities::sea_orm_active_enums::Status;
#[derive(Debug, Serialize, Deserialize)]
pub struct UserPageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
#[derive(Deserialize, Validate)]
#[serde(rename_all = "camelCase")]
pub struct UserInput {
pub domain: String,
#[validate(length(
min = 1,
max = 50,
message = "Username must be between 1 and 50 characters"
))]
pub username: String,
#[validate(length(
min = 6,
max = 100,
message = "Password must be between 6 and 100 characters"
))]
pub password: String,
#[validate(length(
min = 1,
max = 50,
message = "Nick name must be between 1 and 50 characters"
))]
pub nick_name: String,
pub avatar: Option<String>,
#[validate(email(message = "Invalid email format"))]
pub email: Option<String>,
#[validate(length(max = 20, message = "Phone number must not exceed 20 characters"))]
pub phone_number: Option<String>,
pub status: Status,
}
pub type CreateUserInput = UserInput;
#[derive(Deserialize, Validate)]
pub struct UpdateUserInput {
pub id: String,
#[serde(flatten)]
pub user: UserInput,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_role.rs | server/model/src/admin/input/sys_role.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
use validator::Validate;
use crate::admin::entities::sea_orm_active_enums::Status;
#[derive(Debug, Serialize, Deserialize)]
pub struct RolePageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
#[derive(Deserialize, Validate)]
pub struct RoleInput {
pub pid: String,
#[validate(length(
min = 1,
max = 50,
message = "Code must be between 1 and 50 characters"
))]
pub code: String,
#[validate(length(
min = 1,
max = 50,
message = "Name must be between 1 and 50 characters"
))]
pub name: String,
pub status: Status,
#[validate(length(max = 200, message = "Description must not exceed 200 characters"))]
pub description: Option<String>,
}
pub type CreateRoleInput = RoleInput;
#[derive(Deserialize, Validate)]
pub struct UpdateRoleInput {
pub id: String,
#[serde(flatten)]
pub role: RoleInput,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_login_log.rs | server/model/src/admin/input/sys_login_log.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
#[derive(Debug, Serialize, Deserialize)]
pub struct LoginLogPageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_domain.rs | server/model/src/admin/input/sys_domain.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
use validator::Validate;
#[derive(Debug, Serialize, Deserialize)]
pub struct DomainPageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
#[derive(Deserialize, Validate)]
pub struct DomainInput {
#[validate(length(
min = 1,
max = 50,
message = "Code must be between 1 and 50 characters"
))]
pub code: String,
#[validate(length(
min = 1,
max = 100,
message = "Name must be between 1 and 100 characters"
))]
pub name: String,
#[validate(length(max = 500, message = "Description must not exceed 500 characters"))]
pub description: Option<String>,
}
pub type CreateDomainInput = DomainInput;
#[derive(Deserialize, Validate)]
pub struct UpdateDomainInput {
pub id: String,
#[serde(flatten)]
pub domain: DomainInput,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/mod.rs | server/model/src/admin/input/mod.rs | pub use sys_access_key::{AccessKeyPageRequest, CreateAccessKeyInput};
pub use sys_authentication::LoginInput;
pub use sys_authorization::{AssignPermissionDto, AssignRouteDto, AssignUserDto};
pub use sys_domain::{CreateDomainInput, DomainPageRequest, UpdateDomainInput};
pub use sys_endpoint::EndpointPageRequest;
pub use sys_login_log::LoginLogPageRequest;
pub use sys_menu::{CreateMenuInput, UpdateMenuInput};
pub use sys_operation_log::OperationLogPageRequest;
pub use sys_organization::OrganizationPageRequest;
pub use sys_role::{CreateRoleInput, RolePageRequest, UpdateRoleInput};
pub use sys_user::{CreateUserInput, UpdateUserInput, UserPageRequest};
mod sys_access_key;
mod sys_authentication;
mod sys_authorization;
mod sys_domain;
mod sys_endpoint;
mod sys_login_log;
mod sys_menu;
mod sys_operation_log;
mod sys_organization;
mod sys_role;
mod sys_user;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_endpoint.rs | server/model/src/admin/input/sys_endpoint.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
#[derive(Debug, Serialize, Deserialize)]
pub struct EndpointPageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_menu.rs | server/model/src/admin/input/sys_menu.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
use validator::Validate;
use crate::admin::entities::sea_orm_active_enums::{MenuType, Status};
#[derive(Debug, Serialize, Deserialize)]
pub struct MenuPageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
#[derive(Deserialize, Validate)]
pub struct MenuInput {
pub menu_type: MenuType,
#[validate(length(
min = 1,
max = 100,
message = "Menu name must be between 1 and 100 characters"
))]
pub menu_name: String,
pub icon_type: Option<i32>,
#[validate(length(max = 100, message = "Icon must not exceed 100 characters"))]
pub icon: Option<String>,
#[validate(length(
min = 1,
max = 100,
message = "Route name must be between 1 and 100 characters"
))]
pub route_name: String,
#[validate(length(
min = 1,
max = 200,
message = "Route path must be between 1 and 200 characters"
))]
pub route_path: String,
#[validate(length(
min = 1,
max = 200,
message = "Component must be between 1 and 200 characters"
))]
pub component: String,
#[validate(length(max = 100, message = "Path param must not exceed 100 characters"))]
pub path_param: Option<String>,
pub status: Status,
#[validate(length(max = 100, message = "Active menu must not exceed 100 characters"))]
pub active_menu: Option<String>,
pub hide_in_menu: Option<bool>,
#[validate(length(min = 1, max = 50, message = "PID must be between 1 and 50 characters"))]
pub pid: String,
pub sequence: i32,
#[validate(length(max = 100, message = "i18n key must not exceed 100 characters"))]
pub i18n_key: Option<String>,
pub keep_alive: Option<bool>,
pub constant: bool,
#[validate(length(max = 200, message = "Href must not exceed 200 characters"))]
pub href: Option<String>,
pub multi_tab: Option<bool>,
}
pub type CreateMenuInput = MenuInput;
#[derive(Deserialize, Validate)]
pub struct UpdateMenuInput {
pub id: i32,
#[serde(flatten)]
pub menu: MenuInput,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_authentication.rs | server/model/src/admin/input/sys_authentication.rs | use serde::Deserialize;
use validator::Validate;
#[derive(Deserialize, Validate)]
pub struct LoginInput {
#[validate(length(min = 5, message = "Username cannot be empty"))]
pub identifier: String,
#[validate(length(min = 6, message = "Password cannot be empty"))]
pub password: String,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/input/sys_organization.rs | server/model/src/admin/input/sys_organization.rs | use serde::{Deserialize, Serialize};
use server_core::web::page::PageRequest;
#[derive(Debug, Serialize, Deserialize)]
pub struct OrganizationPageRequest {
#[serde(flatten)]
pub page_details: PageRequest,
pub keywords: Option<String>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/output/sys_user.rs | server/model/src/admin/output/sys_user.rs | use chrono::NaiveDateTime;
use sea_orm::FromQueryResult;
use serde::Serialize;
use crate::admin::entities::{sea_orm_active_enums::Status, sys_user::Model as SysUserModel};
#[derive(Debug, FromQueryResult)]
pub struct UserWithDomainAndOrgOutput {
pub id: String,
pub domain: String,
pub username: String,
pub password: String,
pub nick_name: String,
pub avatar: Option<String>,
pub domain_code: String,
pub domain_name: String,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UserWithoutPassword {
pub id: String,
pub domain: String,
pub username: String,
pub nick_name: String,
pub avatar: Option<String>,
pub email: Option<String>,
pub phone_number: Option<String>,
pub status: Status,
pub created_at: NaiveDateTime,
pub created_by: String,
pub updated_at: Option<NaiveDateTime>,
pub updated_by: Option<String>,
}
impl From<SysUserModel> for UserWithoutPassword {
fn from(model: SysUserModel) -> Self {
Self {
id: model.id,
domain: model.domain,
username: model.username,
nick_name: model.nick_name,
avatar: model.avatar,
email: model.email,
phone_number: model.phone_number,
status: model.status,
created_at: model.created_at,
created_by: model.created_by,
updated_at: model.updated_at,
updated_by: model.updated_by,
}
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/output/sys_domain.rs | server/model/src/admin/output/sys_domain.rs | use sea_orm::FromQueryResult;
#[derive(Debug, FromQueryResult)]
pub struct DomainOutput {
pub id: String,
pub code: String,
pub name: String,
pub description: Option<String>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/output/mod.rs | server/model/src/admin/output/mod.rs | pub use sys_authentication::{AuthOutput, UserInfoOutput, UserRoute};
pub use sys_domain::DomainOutput;
pub use sys_endpoint::EndpointTree;
pub use sys_menu::{MenuRoute, MenuTree, RouteMeta};
pub use sys_user::{UserWithDomainAndOrgOutput, UserWithoutPassword};
mod sys_authentication;
mod sys_domain;
mod sys_endpoint;
mod sys_menu;
mod sys_user;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/output/sys_endpoint.rs | server/model/src/admin/output/sys_endpoint.rs | use serde::Serialize;
#[derive(Debug, Serialize, Clone)]
pub struct EndpointTree {
pub id: String,
pub path: String,
pub method: String,
pub action: String,
pub resource: String,
pub controller: String,
pub summary: Option<String>,
pub children: Option<Vec<EndpointTree>>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/output/sys_menu.rs | server/model/src/admin/output/sys_menu.rs | use chrono::NaiveDateTime;
use serde::Serialize;
use crate::admin::entities::sea_orm_active_enums::{MenuType, Status};
#[derive(Debug, Serialize, Clone)]
pub struct MenuRoute {
pub name: String,
pub path: String,
pub component: String,
pub meta: RouteMeta,
#[serde(skip_serializing_if = "Option::is_none")]
pub children: Option<Vec<MenuRoute>>,
pub id: i32,
pub pid: String,
}
#[derive(Debug, Serialize, Clone)]
pub struct RouteMeta {
pub title: String,
#[serde(skip_serializing_if = "Option::is_none", rename = "i18nKey")]
pub i18n_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "keepAlive")]
pub keep_alive: Option<bool>,
pub constant: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
pub order: i32,
#[serde(skip_serializing_if = "Option::is_none")]
pub href: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "hideInMenu")]
pub hide_in_menu: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none", rename = "activeMenu")]
pub active_menu: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "multiTab")]
pub multi_tab: Option<bool>,
}
#[derive(Debug, Serialize, Clone)]
pub struct MenuTree {
pub id: i32,
pub pid: String,
#[serde(rename = "menuType")]
pub menu_type: MenuType,
#[serde(rename = "menuName")]
pub menu_name: String,
#[serde(skip_serializing_if = "Option::is_none", rename = "iconType")]
pub icon_type: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub icon: Option<String>,
#[serde(rename = "routeName")]
pub route_name: String,
#[serde(rename = "routePath")]
pub route_path: String,
pub component: String,
#[serde(skip_serializing_if = "Option::is_none", rename = "pathParam")]
pub path_param: Option<String>,
pub status: Status,
#[serde(skip_serializing_if = "Option::is_none", rename = "activeMenu")]
pub active_menu: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "hideInMenu")]
pub hide_in_menu: Option<bool>,
pub sequence: i32,
#[serde(skip_serializing_if = "Option::is_none", rename = "i18nKey")]
pub i18n_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "keepAlive")]
pub keep_alive: Option<bool>,
pub constant: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub href: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", rename = "multiTab")]
pub multi_tab: Option<bool>,
#[serde(rename = "createdAt")]
pub created_at: NaiveDateTime,
#[serde(rename = "createdBy")]
pub created_by: String,
#[serde(skip_serializing_if = "Option::is_none", rename = "updatedAt")]
pub updated_at: Option<NaiveDateTime>,
#[serde(skip_serializing_if = "Option::is_none", rename = "updatedBy")]
pub updated_by: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub children: Option<Vec<MenuTree>>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/model/src/admin/output/sys_authentication.rs | server/model/src/admin/output/sys_authentication.rs | use serde::Serialize;
use super::MenuRoute;
#[derive(Clone, Debug, Serialize)]
pub struct AuthOutput {
pub token: String,
// 为了复用soybean-admin-nestjs前端,暂时弃用
// pub access_token: String,
pub refresh_token: String,
}
#[derive(Debug, Serialize)]
pub struct UserInfoOutput {
#[serde(rename = "userId")]
pub user_id: String,
#[serde(rename = "userName")]
pub user_name: String,
pub roles: Vec<String>,
}
#[derive(Debug, Serialize)]
pub struct UserRoute {
pub routes: Vec<MenuRoute>,
pub home: String,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/middleware/src/lib.rs | server/middleware/src/lib.rs | mod jwt;
pub use jwt::jwt_auth_middleware;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/middleware/src/jwt.rs | server/middleware/src/jwt.rs | use axum::{
body::Body, extract::Request, http::StatusCode, middleware::Next, response::IntoResponse,
};
use axum_casbin::CasbinVals;
use headers::{authorization::Bearer, Authorization, HeaderMapExt};
use server_core::web::{auth::User, jwt::JwtUtils, res::Res};
pub async fn jwt_auth_middleware(
mut req: Request<Body>,
next: Next,
audience: &str,
) -> impl IntoResponse {
let token = match req.headers().typed_get::<Authorization<Bearer>>() {
Some(auth) => auth.token().to_string(),
None => {
return Res::<String>::new_error(
StatusCode::UNAUTHORIZED.as_u16(),
"No token provided or invalid token type",
)
.into_response();
},
};
match JwtUtils::validate_token(&token, audience).await {
Ok(data) => {
let claims = data.claims;
let user = User::from(claims);
let vals = CasbinVals {
subject: user.subject(),
domain: Option::from(user.domain()),
};
req.extensions_mut().insert(user);
req.extensions_mut().insert(vals);
next.run(req).await.into_response()
},
Err(err) => {
Res::<String>::new_error(StatusCode::UNAUTHORIZED.as_u16(), err.to_string().as_str())
.into_response()
},
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/casbin_initialization.rs | server/initialize/src/casbin_initialization.rs | use std::error::Error;
use axum_casbin::CasbinAxumLayer;
use casbin::DefaultModel;
use sea_orm::Database;
use sea_orm_adapter::SeaOrmAdapter;
use crate::project_info;
pub async fn initialize_casbin(
model_path: &str,
db_url: &str,
) -> Result<CasbinAxumLayer, Box<dyn Error>> {
project_info!("Initializing Casbin with model: {}", model_path);
let model = DefaultModel::from_file(model_path).await?;
let db = Database::connect(db_url).await?;
let adapter = SeaOrmAdapter::new(db).await?;
let casbin_axum_layer = CasbinAxumLayer::new(model, adapter).await?;
project_info!("Casbin initialization completed successfully");
Ok(casbin_axum_layer)
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/access_key_initialization.rs | server/initialize/src/access_key_initialization.rs | use server_global::project_info;
use server_service::admin::{SysAccessKeyService, TAccessKeyService};
pub async fn initialize_access_key() {
let access_key_service = SysAccessKeyService;
let _ = access_key_service.initialize_access_key().await;
project_info!("Access key initialization completed successfully")
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/lib.rs | server/initialize/src/lib.rs | pub use access_key_initialization::initialize_access_key;
pub use aws_s3_initialization::{init_primary_s3, init_s3_pools};
pub use casbin_initialization::initialize_casbin;
pub use config_initialization::{
initialize_config, initialize_config_from_env_only, initialize_config_with_env,
initialize_config_with_multi_instance_env,
};
pub use db_initialization::{init_db_pools, init_primary_connection};
pub use event_channel_initialization::initialize_event_channel;
pub use ip2region_initialization::init_xdb;
pub use jwt_initialization::initialize_keys_and_validation;
pub use log_tracing_init::initialize_log_tracing;
pub use mongo_initialization::{init_mongo_pools, init_primary_mongo};
pub use redis_initialization::{init_primary_redis, init_redis_pools};
pub use router_initialization::initialize_admin_router;
pub use server_global::{project_error, project_info};
pub use server_initialization::get_server_address;
mod access_key_initialization;
mod aws_s3_initialization;
mod casbin_initialization;
mod config_initialization;
mod db_initialization;
mod event_channel_initialization;
mod ip2region_initialization;
mod jwt_initialization;
mod log_tracing_init;
mod mongo_initialization;
mod redis_initialization;
mod router_initialization;
mod server_initialization;
// TODO: axum_test_helpers不兼容axum 0.8.x
// #[cfg(test)]
// mod tests {
// use std::{
// convert::Infallible,
// task::{Context, Poll},
// };
// use axum::{body::HttpBody, response::Response, routing::get, BoxError, Router};
// use axum_casbin::CasbinVals;
// use axum_test_helpers::TestClient;
// use bytes::Bytes;
// use casbin::{function_map::key_match2, CoreApi};
// use futures::future::BoxFuture;
// use http::{Request, StatusCode};
// use log::LevelFilter;
// use server_config::DatabaseConfig;
// use server_global::global;
// use simplelog::{Config as LogConfig, SimpleLogger};
// use tower::Service;
// use super::*;
// static INIT: std::sync::Once = std::sync::Once::new();
// fn init_logger() {
// INIT.call_once(|| {
// SimpleLogger::init(LevelFilter::Info, LogConfig::default()).unwrap();
// });
// }
// #[tokio::test]
// async fn test_initialize_config() {
// init_logger();
// initialize_config("../resources/application-test.yaml").await;
// let db_config = global::get_config::<DatabaseConfig>().await.unwrap();
// assert_eq!(db_config.url, "postgres://user:password@localhost/db");
// }
// #[tokio::test]
// async fn test_initialize_casbin() {
// init_logger();
// let result = initialize_casbin(
// "../resources/rbac_model.conf",
// "postgres://postgres:123456@localhost:5432/soybean-admin-rust-backend",
// )
// .await;
// assert!(result.is_ok());
// }
// #[tokio::test]
// async fn test_initialize_casbin_with_axum() {
// init_logger();
// let casbin_middleware = initialize_casbin(
// "../resources/rbac_model.conf",
// "postgres://postgres:123456@localhost:5432/soybean-admin-rust-backend",
// )
// .await
// .unwrap();
// casbin_middleware
// .write()
// .await
// .get_role_manager()
// .write()
// .matching_fn(Some(key_match2), None);
// let app = Router::new()
// .route("/pen/1", get(handler))
// .route("/pen/2", get(handler))
// .route("/book/:id", get(handler))
// .layer(casbin_middleware)
// .layer(FakeAuthLayer);
// let client = TestClient::new(app);
// let resp_pen_1 = client.get("/pen/1").await;
// assert_eq!(resp_pen_1.status(), StatusCode::OK);
// let resp_book = client.get("/book/2").await;
// assert_eq!(resp_book.status(), StatusCode::OK);
// let resp_pen_2 = client.get("/pen/2").await;
// assert_eq!(resp_pen_2.status(), StatusCode::FORBIDDEN);
// }
// async fn handler() -> &'static str {
// "Hello, world!"
// }
// #[derive(Clone)]
// struct FakeAuthLayer;
// impl<S> tower::Layer<S> for FakeAuthLayer {
// type Service = FakeAuthMiddleware<S>;
// fn layer(&self, inner: S) -> Self::Service {
// FakeAuthMiddleware { inner }
// }
// }
// #[derive(Clone)]
// struct FakeAuthMiddleware<S> {
// inner: S,
// }
// impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for FakeAuthMiddleware<S>
// where
// S: Service<Request<ReqBody>, Response = Response<ResBody>, Error = Infallible>
// + Clone
// + Send
// + 'static,
// S::Future: Send + 'static,
// ReqBody: Send + 'static,
// Infallible: From<<S as Service<Request<ReqBody>>>::Error>,
// ResBody: HttpBody<Data = Bytes> + Send + 'static,
// ResBody::Error: Into<BoxError>,
// {
// type Error = S::Error;
// // `BoxFuture` is a type alias for `Pin<Box<dyn Future + Send + 'a>>`
// type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
// type Response = S::Response;
// fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
// self.inner.poll_ready(cx)
// }
// fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
// let not_ready_inner = self.inner.clone();
// let mut inner = std::mem::replace(&mut self.inner, not_ready_inner);
// Box::pin(async move {
// let vals = CasbinVals {
// subject: vec!["alice".to_string()],
// domain: None,
// };
// req.extensions_mut().insert(vals);
// inner.call(req).await
// })
// }
// }
// }
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/event_channel_initialization.rs | server/initialize/src/event_channel_initialization.rs | use server_constant::definition::consts::SystemEvent;
use server_global::global;
pub async fn initialize_event_channel() {
use server_service::admin::{
api_key_validate_listener, auth_login_listener, jwt_created_listener,
sys_operation_log_listener,
};
global::register_event_listeners(
Box::new(|rx| Box::pin(jwt_created_listener(rx))),
&[
(
SystemEvent::AuthLoggedInEvent.to_string(),
Box::new(|rx| Box::pin(auth_login_listener(rx))),
),
(
SystemEvent::AuditOperationLoggedEvent.to_string(),
Box::new(|rx| Box::pin(sys_operation_log_listener(rx))),
),
(
SystemEvent::AuthApiKeyValidatedEvent.to_string(),
Box::new(|rx| Box::pin(api_key_validate_listener(rx))),
),
],
)
.await;
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/mongo_initialization.rs | server/initialize/src/mongo_initialization.rs | #![allow(dead_code)]
use mongodb::Client;
use server_config::{MongoConfig, MongoInstancesConfig, OptionalConfigs};
use server_global::global::{get_config, GLOBAL_MONGO_POOL, GLOBAL_PRIMARY_MONGO};
use std::{process, sync::Arc};
use crate::{project_error, project_info};
/// 初始化主MongoDB
pub async fn init_primary_mongo() {
if let Some(config) = get_config::<MongoConfig>().await {
match Client::with_uri_str(&config.uri).await {
Ok(client) => {
if let Err(e) = client.list_database_names().await {
project_error!("Failed to connect to MongoDB: {}", e);
process::exit(1);
}
*GLOBAL_PRIMARY_MONGO.write().await = Some(Arc::new(client));
project_info!("Primary MongoDB connection initialized");
},
Err(e) => {
project_error!("Failed to create initialize primary MongoDB: {}", e);
process::exit(1);
},
}
}
}
/// 初始化所有 MongoDB 连接
pub async fn init_mongo_pools() {
if let Some(mongo_instances_config) =
get_config::<OptionalConfigs<MongoInstancesConfig>>().await
{
if let Some(mongo_instances) = &mongo_instances_config.configs {
let _ = init_mongo_pool(Some(mongo_instances.clone())).await;
}
}
}
pub async fn init_mongo_pool(
mongo_instances_config: Option<Vec<MongoInstancesConfig>>,
) -> Result<(), String> {
if let Some(mongo_instances) = mongo_instances_config {
for mongo_instance in mongo_instances {
init_mongo_connection(&mongo_instance.name, &mongo_instance.mongo).await?;
}
}
Ok(())
}
async fn init_mongo_connection(name: &str, config: &MongoConfig) -> Result<(), String> {
match Client::with_uri_str(&config.uri).await {
Ok(client) => {
if let Err(e) = client.list_database_names().await {
let error_msg = format!("Failed to connect to MongoDB '{}': {}", name, e);
project_error!("{}", error_msg);
return Err(error_msg);
}
GLOBAL_MONGO_POOL
.write()
.await
.insert(name.to_string(), Arc::new(client));
project_info!("MongoDB '{}' initialized", name);
Ok(())
},
Err(e) => {
let error_msg = format!("Failed to initialize MongoDB '{}': {}", name, e);
project_error!("{}", error_msg);
Err(error_msg)
},
}
}
pub async fn get_primary_mongo() -> Option<Arc<Client>> {
GLOBAL_PRIMARY_MONGO.read().await.clone()
}
pub async fn get_mongo_pool_connection(name: &str) -> Option<Arc<Client>> {
GLOBAL_MONGO_POOL.read().await.get(name).cloned()
}
pub async fn add_or_update_mongo_pool(name: &str, config: &MongoConfig) -> Result<(), String> {
init_mongo_connection(name, config).await
}
pub async fn remove_mongo_pool(name: &str) -> Result<(), String> {
let mut mongo_pool = GLOBAL_MONGO_POOL.write().await;
mongo_pool
.remove(name)
.ok_or_else(|| format!("MongoDB connection '{}' not found", name))?;
project_info!("MongoDB connection '{}' removed", name);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::initialize_config;
use log::LevelFilter;
use mongodb::bson::{doc, Document};
use simple_logger::SimpleLogger;
use tokio::sync::Mutex;
static INITIALIZED: Mutex<Option<Arc<()>>> = Mutex::const_new(None);
fn setup_logger() {
let _ = SimpleLogger::new().with_level(LevelFilter::Info).init();
}
async fn init() {
let mut initialized = INITIALIZED.lock().await;
if initialized.is_none() {
initialize_config("../resources/application.yaml").await;
*initialized = Some(Arc::new(()));
}
}
async fn test_mongo_operations(client: &Client) -> Result<(), String> {
let db = client.database("test");
let collection = db.collection::<Document>("test_collection");
// 插入测试文档
let doc = doc! {
"test_key": "test_value",
"number": 42
};
collection
.insert_one(doc.clone())
.await
.map_err(|e| format!("Failed to insert document: {}", e))?;
// 查询文档
let result = collection
.find_one(doc! { "test_key": "test_value" })
.await
.map_err(|e| format!("Failed to find document: {}", e))?;
assert!(result.is_some(), "Document not found");
// 删除文档
collection
.delete_one(doc! { "test_key": "test_value" })
.await
.map_err(|e| format!("Failed to delete document: {}", e))?;
Ok(())
}
#[tokio::test]
async fn test_primary_mongo_connection() {
setup_logger();
init().await;
init_primary_mongo().await;
let client = get_primary_mongo().await;
assert!(
client.is_some(),
"Primary MongoDB connection does not exist"
);
if let Some(client) = client {
let result = test_mongo_operations(&client).await;
assert!(
result.is_ok(),
"MongoDB operations test failed: {:?}",
result.err()
);
}
}
#[tokio::test]
async fn test_mongo_pool_operations() {
setup_logger();
init().await;
let test_config = MongoInstancesConfig {
name: "test_mongo".to_string(),
mongo: MongoConfig {
uri: "mongodb://localhost:27017".to_string(),
},
};
let result = init_mongo_pool(Some(vec![test_config.clone()])).await;
assert!(
result.is_ok(),
"Failed to initialize MongoDB pool: {:?}",
result.err()
);
// 测试连接池连接
let pool_connection = get_mongo_pool_connection("test_mongo").await;
assert!(pool_connection.is_some(), "Pool connection not found");
if let Some(client) = pool_connection {
let result = test_mongo_operations(&client).await;
assert!(
result.is_ok(),
"MongoDB pool operations test failed: {:?}",
result.err()
);
}
// 测试添加新连接
let add_result = add_or_update_mongo_pool("test_new", &test_config.mongo).await;
assert!(add_result.is_ok(), "Failed to add MongoDB connection");
// 测试移除连接
let remove_result = remove_mongo_pool("test_new").await;
assert!(remove_result.is_ok(), "Failed to remove MongoDB connection");
let connection_after_removal = get_mongo_pool_connection("test_new").await;
assert!(
connection_after_removal.is_none(),
"MongoDB connection still exists after removal"
);
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/db_initialization.rs | server/initialize/src/db_initialization.rs | #![allow(dead_code)]
use std::{process, sync::Arc, time::Duration};
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use server_config::{DatabaseConfig, DatabasesInstancesConfig, OptionalConfigs};
use server_global::global::{get_config, GLOBAL_DB_POOL, GLOBAL_PRIMARY_DB};
use crate::{project_error, project_info};
pub async fn init_primary_connection() {
let db_config = get_config::<DatabaseConfig>().await.unwrap();
let opt = build_connect_options(&db_config);
match Database::connect(opt).await {
Ok(db) => {
*GLOBAL_PRIMARY_DB.write().await = Some(Arc::new(db));
project_info!("Primary database connection initialized");
},
Err(e) => {
project_error!("Failed to connect to primary database: {}", e);
process::exit(1);
},
}
}
/// 初始化多数据库连接
pub async fn init_db_pools() {
if let Some(databases_instances_config) =
get_config::<OptionalConfigs<DatabasesInstancesConfig>>().await
{
if let Some(databases_instances) = &databases_instances_config.configs {
let _ = init_db_pool_connections(Some(databases_instances.clone())).await;
}
}
}
pub async fn init_db_pool_connections(
databases_config: Option<Vec<DatabasesInstancesConfig>>,
) -> Result<(), String> {
if let Some(dbs) = databases_config {
for db_config in dbs {
init_db_connection(&db_config.name, &db_config.database).await?;
}
}
Ok(())
}
async fn init_db_connection(name: &str, db_config: &DatabaseConfig) -> Result<(), String> {
let opt = build_connect_options(db_config);
match Database::connect(opt).await {
Ok(db) => {
GLOBAL_DB_POOL
.write()
.await
.insert(name.to_string(), Arc::new(db));
project_info!("Database '{}' initialized", name);
Ok(())
},
Err(e) => {
let error_msg = format!("Failed to connect to database '{}': {}", name, e);
project_error!("{}", error_msg);
Err(error_msg)
},
}
}
fn build_connect_options(db_config: &DatabaseConfig) -> ConnectOptions {
let mut opt = ConnectOptions::new(db_config.url.clone());
opt.max_connections(db_config.max_connections)
.min_connections(db_config.min_connections)
.connect_timeout(Duration::from_secs(db_config.connect_timeout))
.idle_timeout(Duration::from_secs(db_config.idle_timeout))
.sqlx_logging(false);
opt
}
pub async fn get_primary_db_connection() -> Option<Arc<DatabaseConnection>> {
GLOBAL_PRIMARY_DB.read().await.clone()
}
pub async fn get_db_pool_connection(name: &str) -> Option<Arc<DatabaseConnection>> {
GLOBAL_DB_POOL.read().await.get(name).cloned()
}
pub async fn add_or_update_db_pool_connection(
name: &str,
db_config: &DatabaseConfig,
) -> Result<(), String> {
init_db_connection(name, db_config).await
}
pub async fn remove_db_pool_connection(name: &str) -> Result<(), String> {
let mut db_pool = GLOBAL_DB_POOL.write().await;
db_pool
.remove(name)
.ok_or_else(|| "Connection not found".to_string())?;
project_info!("Database connection '{}' removed", name);
Ok(())
}
#[cfg(test)]
mod tests {
use log::LevelFilter;
use server_config::Config;
use server_global::global::get_config;
use simple_logger::SimpleLogger;
use tokio::sync::Mutex;
use super::*;
use crate::initialize_config;
fn setup_logger() {
let _ = SimpleLogger::new().with_level(LevelFilter::Info).init();
}
static INITIALIZED: Mutex<Option<Arc<()>>> = Mutex::const_new(None);
async fn init() {
let mut initialized = INITIALIZED.lock().await;
if initialized.is_none() {
initialize_config("../resources/application.yaml").await;
*initialized = Some(Arc::new(()));
}
}
#[tokio::test]
async fn test_primary_connection_persistence() {
setup_logger();
init().await;
init_primary_connection().await;
let connection = get_primary_db_connection().await;
assert!(
connection.is_some(),
"Master database connection does not exist"
);
}
#[tokio::test]
async fn test_db_pool_connection() {
setup_logger();
init().await;
let config = get_config::<Config>().await.unwrap().as_ref().clone();
let result = init_db_pool_connections(config.database_instances).await;
assert!(
result.is_ok(),
"Failed to initialize db_pool connections: {:?}",
result.err()
);
let db_config = DatabaseConfig {
url: "postgres://postgres:123456@localhost:5432/soybean-admin-rust-backend".to_string(),
max_connections: 50,
min_connections: 5,
connect_timeout: 15,
idle_timeout: 600,
};
let add_result = add_or_update_db_pool_connection("test_connection", &db_config).await;
assert!(add_result.is_ok(), "Failed to add database connection");
let connection = get_db_pool_connection("test_connection").await;
assert!(
connection.is_some(),
"Database connection 'test_connection' does not exist"
);
println!("Added and retrieved database connection successfully.");
println!(
"Current pool size after addition: {}",
GLOBAL_DB_POOL.read().await.len()
);
let remove_result = remove_db_pool_connection("test_connection").await;
assert!(
remove_result.is_ok(),
"Failed to remove database connection"
);
let connection_after_removal = get_db_pool_connection("test_connection").await;
assert!(
connection_after_removal.is_none(),
"Database connection 'test_connection' still exists after removal"
);
println!(
"Current pool size after removal: {}",
GLOBAL_DB_POOL.read().await.len()
);
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/server_initialization.rs | server/initialize/src/server_initialization.rs | use std::error::Error;
use server_config::ServerConfig;
use server_global::global;
use crate::project_info;
pub async fn get_server_address() -> Result<String, Box<dyn Error>> {
let server_config = global::get_config::<ServerConfig>().await.unwrap();
let addr = format!("{}:{}", server_config.host, server_config.port);
project_info!("Server address configured: {}", addr);
Ok(addr)
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/redis_initialization.rs | server/initialize/src/redis_initialization.rs | #![allow(dead_code)]
use redis::{cluster::ClusterClient, Client};
use server_config::{OptionalConfigs, RedisConfig, RedisInstancesConfig, RedisMode};
use server_global::global::{get_config, RedisConnection, GLOBAL_PRIMARY_REDIS, GLOBAL_REDIS_POOL};
use std::{process, sync::Arc};
use crate::{project_error, project_info};
/// 初始化主Redis
pub async fn init_primary_redis() {
if let Some(config) = get_config::<RedisConfig>().await {
match create_redis_connection(&config).await {
Ok(connection) => {
*GLOBAL_PRIMARY_REDIS.write().await = Some(connection);
project_info!(
"Primary Redis connection initialized ({})",
if config.mode == RedisMode::Cluster {
"Cluster mode"
} else {
"Single mode"
}
);
},
Err(e) => {
project_error!("Failed to initialize primary Redis: {}", e);
process::exit(1);
},
}
}
}
async fn create_redis_connection(config: &RedisConfig) -> Result<RedisConnection, String> {
if config.mode == RedisMode::Cluster {
create_cluster_connection(config).await
} else {
create_single_connection(config).await
}
}
async fn create_single_connection(config: &RedisConfig) -> Result<RedisConnection, String> {
let url = config
.get_url()
.ok_or_else(|| "URL is required for single mode Redis".to_string())?;
let client = redis::Client::open(url.as_str())
.map_err(|e| format!("Failed to create Redis client: {}", e))?;
test_single_connection(&client).await?;
Ok(RedisConnection::Single(Arc::new(client)))
}
async fn test_single_connection(client: &Client) -> Result<(), String> {
let mut con = client
.get_multiplexed_async_connection()
.await
.map_err(|e| format!("Failed to create connection manager: {}", e))?;
let _: String = redis::cmd("PING")
.query_async(&mut con)
.await
.map_err(|e| format!("Failed to connect to Redis: {}", e))?;
Ok(())
}
async fn create_cluster_connection(config: &RedisConfig) -> Result<RedisConnection, String> {
let urls = config
.get_urls()
.ok_or_else(|| "URLs are required for cluster mode".to_string())?;
if urls.is_empty() {
return Err("Cluster mode requires at least one URL".to_string());
}
let client =
redis::cluster::ClusterClient::new(urls.iter().map(|s| s.as_str()).collect::<Vec<_>>())
.map_err(|e| format!("Failed to create Redis cluster client: {}", e))?;
test_cluster_connection(&client).await?;
Ok(RedisConnection::Cluster(Arc::new(client)))
}
async fn test_cluster_connection(client: &ClusterClient) -> Result<(), String> {
let mut con = client
.get_async_connection()
.await
.map_err(|e| format!("Failed to connect to Redis cluster: {}", e))?;
let _: String = redis::cmd("PING")
.query_async(&mut con)
.await
.map_err(|e| format!("Failed to connect to Redis: {}", e))?;
Ok(())
}
pub async fn init_redis_pool(
redis_instances_config: Option<Vec<RedisInstancesConfig>>,
) -> Result<(), String> {
if let Some(redis_instances) = redis_instances_config {
for redis_instance in redis_instances {
init_redis_connection(&redis_instance.name, &redis_instance.redis).await?;
}
}
Ok(())
}
async fn init_redis_connection(name: &str, config: &RedisConfig) -> Result<(), String> {
match create_redis_connection(config).await {
Ok(connection) => {
GLOBAL_REDIS_POOL
.write()
.await
.insert(name.to_string(), connection);
project_info!("Redis '{}' initialized", name);
Ok(())
},
Err(e) => {
let error_msg = format!("Failed to initialize Redis '{}': {}", name, e);
project_error!("{}", error_msg);
Err(error_msg)
},
}
}
/// 初始化所有 Redis 连接
pub async fn init_redis_pools() {
if let Some(redis_instances_config) =
get_config::<OptionalConfigs<RedisInstancesConfig>>().await
{
if let Some(redis_instances) = &redis_instances_config.configs {
let _ = init_redis_pool(Some(redis_instances.clone())).await;
}
}
}
pub async fn get_primary_redis() -> Option<RedisConnection> {
GLOBAL_PRIMARY_REDIS.read().await.clone()
}
pub async fn get_redis_pool_connection(name: &str) -> Option<RedisConnection> {
GLOBAL_REDIS_POOL.read().await.get(name).cloned()
}
pub async fn add_or_update_redis_pool(name: &str, config: &RedisConfig) -> Result<(), String> {
init_redis_connection(name, config).await
}
pub async fn remove_redis_pool(name: &str) -> Result<(), String> {
let mut redis_pool = GLOBAL_REDIS_POOL.write().await;
redis_pool
.remove(name)
.ok_or_else(|| format!("Redis connection '{}' not found", name))?;
project_info!("Redis connection '{}' removed", name);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::initialize_config;
use log::LevelFilter;
use redis::AsyncCommands;
use simple_logger::SimpleLogger;
use tokio::sync::Mutex;
static INITIALIZED: Mutex<Option<Arc<()>>> = Mutex::const_new(None);
fn setup_logger() {
let _ = SimpleLogger::new().with_level(LevelFilter::Info).init();
}
async fn init() {
let mut initialized = INITIALIZED.lock().await;
if initialized.is_none() {
initialize_config("../resources/application.yaml").await;
*initialized = Some(Arc::new(()));
}
}
async fn test_redis_operations(connection: &RedisConnection) -> Result<(), String> {
match connection {
RedisConnection::Single(client) => {
let mut con = client
.get_multiplexed_async_connection()
.await
.map_err(|e| format!("Failed to get connection: {}", e))?;
test_redis_basic_operations(&mut con).await
},
RedisConnection::Cluster(client) => {
let mut con = client
.get_async_connection()
.await
.map_err(|e| format!("Failed to get cluster connection: {}", e))?;
test_redis_basic_operations(&mut con).await
},
}
}
#[allow(dependency_on_unit_never_type_fallback)]
async fn test_redis_basic_operations<C: AsyncCommands>(con: &mut C) -> Result<(), String> {
let test_key = "test_key";
let test_value = "test_value";
con.set(test_key, test_value)
.await
.map_err(|e| format!("Failed to set value: {}", e))?;
project_info!("Successfully set value: {} = {}", test_key, test_value);
let value: String = con
.get(test_key)
.await
.map_err(|e| format!("Failed to get value: {}", e))?;
assert_eq!(value, test_value, "Retrieved value does not match");
project_info!("Successfully retrieved value: {} = {}", test_key, value);
let deleted: bool = con
.del(test_key)
.await
.map_err(|e| format!("Failed to delete key: {}", e))?;
assert!(deleted, "Key was not deleted");
project_info!("Successfully deleted key: {}", test_key);
Ok(())
}
#[tokio::test]
async fn test_primary_redis_connection() {
setup_logger();
init().await;
init_primary_redis().await;
let connection = get_primary_redis().await;
assert!(
connection.is_some(),
"Primary Redis connection does not exist"
);
if let Some(conn) = connection {
let result = test_redis_operations(&conn).await;
assert!(
result.is_ok(),
"Redis operations test failed: {:?}",
result.err()
);
}
}
#[tokio::test]
async fn test_redis_pool_connection() {
setup_logger();
init().await;
let single_config = server_config::RedisInstancesConfig {
name: "test_single".to_string(),
redis: RedisConfig {
mode: RedisMode::Single,
url: Some("redis://:123456@bytebytebrew.local:26379/11".to_string()),
urls: None,
},
};
let result = init_redis_pool(Some(vec![single_config.clone()])).await;
assert!(
result.is_ok(),
"Failed to initialize Redis pool: {:?}",
result.err()
);
// 测试单机连接
let single_connection = get_redis_pool_connection("test_single").await;
if let Some(conn) = single_connection {
let result = test_redis_operations(&conn).await;
assert!(
result.is_ok(),
"Single Redis operations test failed: {:?}",
result.err()
);
project_info!("Single Redis connection test passed");
}
// 测试添加新连接
let add_result = add_or_update_redis_pool("test_new", &single_config.redis).await;
assert!(add_result.is_ok(), "Failed to add Redis connection");
let new_connection = get_redis_pool_connection("test_new").await;
assert!(
new_connection.is_some(),
"New Redis connection does not exist"
);
if let Some(conn) = new_connection {
let result = test_redis_operations(&conn).await;
assert!(
result.is_ok(),
"New Redis connection test failed: {:?}",
result.err()
);
project_info!("New Redis connection test passed");
}
project_info!(
"Current pool size: {}",
GLOBAL_REDIS_POOL.read().await.len()
);
// 测试移除连接
let remove_result = remove_redis_pool("test_new").await;
assert!(remove_result.is_ok(), "Failed to remove Redis connection");
let connection_after_removal = get_redis_pool_connection("test_new").await;
assert!(
connection_after_removal.is_none(),
"Redis connection still exists after removal"
);
project_info!(
"Current pool size after removal: {}",
GLOBAL_REDIS_POOL.read().await.len()
);
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/router_initialization.rs | server/initialize/src/router_initialization.rs | use std::sync::Arc;
use axum::{body::Body, http::StatusCode, response::IntoResponse, Extension, Router};
use axum_casbin::CasbinAxumLayer;
use chrono::Local;
use http::Request;
use server_config::Config;
use server_constant::definition::Audience;
use server_core::sign::{
api_key_middleware, protect_route, ApiKeySource, ApiKeyValidation, ComplexApiKeyConfig,
SimpleApiKeyConfig, ValidatorType,
};
use server_core::web::{RequestId, RequestIdLayer};
use server_global::global::{clear_routes, get_collected_routes, get_config};
use server_middleware::jwt_auth_middleware;
use server_router::admin::{
SysAccessKeyRouter, SysAuthenticationRouter, SysDomainRouter, SysEndpointRouter,
SysLoginLogRouter, SysMenuRouter, SysOperationLogRouter, SysOrganizationRouter, SysRoleRouter,
SysSandboxRouter, SysUserRouter,
};
use server_service::{
admin::{
SysAccessKeyService, SysAuthService, SysAuthorizationService, SysDomainService,
SysEndpointService, SysLoginLogService, SysMenuService, SysOperationLogService,
SysOrganizationService, SysRoleService, SysUserService, TEndpointService,
},
SysEndpoint,
};
use tower_http::trace::TraceLayer;
use tracing::info_span;
use crate::{initialize_casbin, project_error, project_info};
#[derive(Clone)]
pub enum Services<T: Send + Sync + 'static> {
None(std::marker::PhantomData<T>),
Single(Arc<T>),
}
async fn apply_layers<T: Send + Sync + 'static>(
router: Router,
services: Services<T>,
need_casbin: bool,
need_auth: bool,
api_validation: Option<ApiKeyValidation>,
casbin: Option<CasbinAxumLayer>,
audience: Audience,
) -> Router {
let mut router = match services {
Services::None(_) => router,
Services::Single(service) => router.layer(Extension(service)),
};
router = router
.layer(
TraceLayer::new_for_http().make_span_with(|request: &Request<Body>| {
let request_id = request
.extensions()
.get::<RequestId>()
.map(ToString::to_string)
.unwrap_or_else(|| "unknown".into());
info_span!(
"[soybean-admin-rust] >>>>>> request",
id = %request_id,
method = %request.method(),
uri = %request.uri(),
)
}),
)
.layer(RequestIdLayer);
if need_casbin {
if let Some(casbin) = casbin {
router = router.layer(Extension(casbin.clone())).layer(casbin);
}
}
if let Some(validation) = api_validation {
router = router.layer(axum::middleware::from_fn(move |req, next| {
api_key_middleware(validation.clone(), req, next)
}));
}
if need_auth {
router = router.layer(axum::middleware::from_fn(move |req, next| {
jwt_auth_middleware(req, next, audience.as_str())
}));
}
router
}
pub async fn initialize_admin_router() -> Router {
clear_routes().await;
project_info!("Initializing admin router");
let app_config = get_config::<Config>().await.unwrap();
let casbin_layer = initialize_casbin(
"server/resources/rbac_model.conf",
app_config.database.url.as_str(),
)
.await
.unwrap();
// 初始化验证器
// 根据是否配置了 Redis 来选择 nonce 存储实现
let nonce_store_factory =
if let Some(_) = crate::redis_initialization::get_primary_redis().await {
// 如果 Redis 可用,使用 Redis 作为 nonce 存储
project_info!("Using Redis for nonce storage");
server_core::sign::create_redis_nonce_store_factory("api_key")
} else {
// 否则使用内存存储
project_info!("Using memory for nonce storage");
server_core::sign::create_memory_nonce_store_factory()
};
server_core::sign::init_validators_with_nonce_store(None, nonce_store_factory.clone()).await;
let simple_validation = {
let validator = server_core::sign::get_simple_validator().await;
server_core::sign::add_key(ValidatorType::Simple, "test-api-key", None).await;
ApiKeyValidation::Simple(
validator,
SimpleApiKeyConfig {
source: ApiKeySource::Header,
key_name: "x-api-key".to_string(),
},
)
};
let complex_validation = {
let validator = server_core::sign::get_complex_validator().await;
server_core::sign::add_key(
ValidatorType::Complex,
"test-access-key",
Some("test-secret-key"),
)
.await;
ApiKeyValidation::Complex(
validator,
ComplexApiKeyConfig {
key_name: "AccessKeyId".to_string(),
timestamp_name: "t".to_string(),
nonce_name: "n".to_string(),
signature_name: "sign".to_string(),
},
)
};
// 保护路由
protect_route("/sandbox/simple-api-key");
protect_route("/sandbox/complex-api-key");
let audience = Audience::ManagementPlatform;
let casbin = Some(casbin_layer);
let mut app = Router::new();
macro_rules! merge_router {
($router:expr, None, $need_casbin:expr, $need_auth:expr, $api_validation:expr) => {
app = app.merge(
apply_layers(
$router,
Services::None(std::marker::PhantomData::<()>),
$need_casbin,
$need_auth,
$api_validation,
casbin.clone(),
audience,
)
.await,
);
};
($router:expr, $service:expr, $need_casbin:expr, $need_auth:expr, $api_validation:expr) => {
app = app.merge(
apply_layers(
$router,
Services::Single(Arc::new($service)),
$need_casbin,
$need_auth,
$api_validation,
casbin.clone(),
audience,
)
.await,
);
};
}
merge_router!(
SysAuthenticationRouter::init_authentication_router().await,
SysAuthService,
false,
false,
None
);
let auth_router = SysAuthenticationRouter::init_authorization_router()
.await
.layer(Extension(Arc::new(SysAuthService) as Arc<SysAuthService>))
.layer(Extension(
Arc::new(SysAuthorizationService) as Arc<SysAuthorizationService>
));
let auth_router = apply_layers(
auth_router,
Services::None(std::marker::PhantomData::<()>),
true,
true,
None,
casbin.clone(),
audience,
)
.await;
app = app.merge(auth_router);
merge_router!(
SysAuthenticationRouter::init_protected_router().await,
SysAuthService,
false,
true,
None
);
merge_router!(
SysMenuRouter::init_menu_router().await,
SysMenuService,
false,
false,
None
);
merge_router!(
SysMenuRouter::init_protected_menu_router().await,
SysMenuService,
true,
true,
None
);
merge_router!(
SysUserRouter::init_user_router().await,
SysUserService,
true,
true,
None
);
merge_router!(
SysDomainRouter::init_domain_router().await,
SysDomainService,
true,
true,
None
);
merge_router!(
SysRoleRouter::init_role_router().await,
SysRoleService,
true,
true,
None
);
merge_router!(
SysEndpointRouter::init_endpoint_router().await,
SysEndpointService,
true,
true,
None
);
merge_router!(
SysAccessKeyRouter::init_access_key_router().await,
SysAccessKeyService,
true,
true,
None
);
merge_router!(
SysLoginLogRouter::init_login_log_router().await,
SysLoginLogService,
true,
true,
None
);
merge_router!(
SysOperationLogRouter::init_operation_log_router().await,
SysOperationLogService,
true,
true,
None
);
merge_router!(
SysOrganizationRouter::init_organization_router().await,
SysOrganizationService,
false,
false,
None
);
// sandbox
merge_router!(
SysSandboxRouter::init_simple_sandbox_router().await,
None,
false,
false,
Some(simple_validation)
);
merge_router!(
SysSandboxRouter::init_complex_sandbox_router().await,
None,
false,
false,
Some(complex_validation)
);
app = app.fallback(handler_404);
process_collected_routes().await;
project_info!("Admin router initialization completed");
app
}
async fn handler_404() -> impl IntoResponse {
(StatusCode::NOT_FOUND, "nothing to see here")
}
async fn process_collected_routes() {
let routes = get_collected_routes().await;
let endpoints: Vec<SysEndpoint> = routes
.into_iter()
.map(|route| {
let resource = route.path.split('/').nth(1).unwrap_or("").to_string();
SysEndpoint {
id: generate_id(&route.path, &route.method.to_string()),
path: route.path.clone(),
method: route.method.to_string(),
action: "rw".to_string(),
resource,
controller: route.service_name,
summary: Some(route.summary),
created_at: Local::now().naive_local(),
updated_at: None,
}
})
.collect();
let endpoint_service = SysEndpointService;
match endpoint_service.sync_endpoints(endpoints).await {
Ok(_) => {
project_info!("Endpoints synced successfully")
},
Err(e) => {
project_error!("Failed to sync endpoints: {:?}", e)
},
}
}
fn generate_id(path: &str, method: &str) -> String {
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
let mut hasher = DefaultHasher::new();
format!("{}{}", path, method).hash(&mut hasher);
format!("{:x}", hasher.finish())
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/ip2region_initialization.rs | server/initialize/src/ip2region_initialization.rs | use std::error::Error;
use xdb::searcher;
use crate::project_info;
pub async fn init_xdb() -> Result<(), Box<dyn Error>> {
tokio::task::spawn_blocking(|| {
searcher::searcher_init(Some("server/resources/ip2region.xdb".to_string()));
})
.await?;
project_info!("XDB initialized successfully");
Ok(())
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/jwt_initialization.rs | server/initialize/src/jwt_initialization.rs | use std::sync::Arc;
use server_config::JwtConfig;
use server_global::{global, Validation};
use tokio::sync::Mutex;
use crate::{project_error, project_info};
pub async fn initialize_keys_and_validation() {
let jwt_config = match global::get_config::<JwtConfig>().await {
Some(cfg) => cfg,
None => {
project_error!("Failed to load JWT config");
return;
},
};
let keys = global::Keys::new(jwt_config.jwt_secret.as_bytes());
if global::KEYS.set(Arc::new(Mutex::new(keys))).is_err() {
project_error!("Failed to set KEYS");
}
let mut validation = Validation::default();
validation.leeway = 60;
validation.set_issuer(&[&jwt_config.issuer]);
if global::VALIDATION
.set(Arc::new(Mutex::new(validation)))
.is_err()
{
project_error!("Failed to set VALIDATION");
}
project_info!("JWT keys and validation initialized");
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/config_initialization.rs | server/initialize/src/config_initialization.rs | use crate::{project_error, project_info};
/// 初始化配置(仅从文件加载,保持向后兼容)
pub async fn initialize_config(file_path: &str) {
match server_config::init_from_file(file_path).await {
Ok(_) => {
project_info!("Configuration initialized successfully from: {}", file_path)
},
Err(e) => {
project_error!("Failed to initialize config from {}: {:?}", file_path, e);
},
}
}
/// 初始化配置(环境变量优先,推荐使用)
///
/// 这是推荐的配置初始化方式,支持环境变量覆盖配置文件中的值
///
/// # 参数
/// - `file_path`: 配置文件路径
/// - `env_prefix`: 环境变量前缀(可选,默认为 "APP")
///
/// # 示例
/// ```rust
/// // 使用默认前缀 "APP"
/// initialize_config_with_env("application.yaml", None).await;
///
/// // 使用自定义前缀 "MYAPP"
/// initialize_config_with_env("application.yaml", Some("MYAPP")).await;
/// ```
pub async fn initialize_config_with_env(file_path: &str, env_prefix: Option<&str>) {
let prefix = env_prefix.unwrap_or("APP");
project_info!("Initializing configuration with environment variable override support");
project_info!("Config file: {}, Environment prefix: {}", file_path, prefix);
match server_config::init_from_file_with_env(file_path, env_prefix).await {
Ok(_) => {
project_info!(
"Configuration initialized successfully with environment variable support"
)
},
Err(e) => {
project_error!(
"Failed to initialize config with environment variables: {:?}",
e
);
},
}
}
/// 仅从环境变量初始化配置
///
/// 当不需要配置文件,完全依赖环境变量时使用此函数
///
/// # 参数
/// - `env_prefix`: 环境变量前缀(可选,默认为 "APP")
///
/// # 示例
/// ```rust
/// // 使用默认前缀 "APP"
/// initialize_config_from_env_only(None).await;
///
/// // 使用自定义前缀 "MYAPP"
/// initialize_config_from_env_only(Some("MYAPP")).await;
/// ```
pub async fn initialize_config_from_env_only(env_prefix: Option<&str>) {
let prefix = env_prefix.unwrap_or("APP");
project_info!("Initializing configuration from environment variables only");
project_info!("Environment prefix: {}", prefix);
match server_config::init_from_env_only(env_prefix).await {
Ok(_) => {
project_info!("Configuration initialized successfully from environment variables only")
},
Err(e) => {
project_error!(
"Failed to initialize config from environment variables: {:?}",
e
);
},
}
}
/// 初始化配置(支持多实例环境变量覆盖,推荐使用)
///
/// 这是最强大的配置初始化方式,支持:
/// - 环境变量覆盖配置文件中的单个值
/// - 环境变量覆盖配置文件中的多实例配置
/// - 完整的多实例环境变量支持
///
/// # 参数
/// - `file_path`: 配置文件路径
/// - `env_prefix`: 环境变量前缀(可选,默认为 "APP")
///
/// # 示例
/// ```rust
/// // 使用默认前缀 "APP"
/// initialize_config_with_multi_instance_env("application.yaml", None).await;
///
/// // 使用自定义前缀 "MYAPP"
/// initialize_config_with_multi_instance_env("application.yaml", Some("MYAPP")).await;
/// ```
pub async fn initialize_config_with_multi_instance_env(file_path: &str, env_prefix: Option<&str>) {
let prefix = env_prefix.unwrap_or("APP");
project_info!("Initializing configuration with multi-instance environment variable support");
project_info!("Config file: {}, Environment prefix: {}", file_path, prefix);
match server_config::init_from_file_with_multi_instance_env(file_path, env_prefix).await {
Ok(_) => {
project_info!("Configuration initialized successfully with multi-instance environment variable support")
},
Err(e) => {
project_error!(
"Failed to initialize config with multi-instance environment variables: {:?}",
e
);
},
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/log_tracing_init.rs | server/initialize/src/log_tracing_init.rs | use tracing_log::LogTracer;
use tracing_subscriber::{layer::SubscriberExt, EnvFilter, Registry};
use crate::{project_error, project_info};
pub async fn initialize_log_tracing() {
if let Err(e) = LogTracer::init() {
project_error!("Failed to set logger: {}", e);
return;
}
let env_filter = if cfg!(debug_assertions) {
EnvFilter::new("debug,sea_orm=debug")
} else {
EnvFilter::new("info,sea_orm=info")
};
let fmt_layer = tracing_subscriber::fmt::layer()
.with_target(true)
.with_ansi(true);
let subscriber = Registry::default()
.with(env_filter)
.with(fmt_layer)
.with(tracing_error::ErrorLayer::default());
if let Err(e) = tracing::subscriber::set_global_default(subscriber) {
project_error!("Failed to set subscriber: {}", e);
return;
}
if cfg!(debug_assertions) {
project_info!("Log tracing initialized successfully in debug mode");
} else {
project_info!("Log tracing initialized successfully in release mode");
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/src/aws_s3_initialization.rs | server/initialize/src/aws_s3_initialization.rs | #![allow(dead_code)]
use std::{process, sync::Arc};
use aws_config::BehaviorVersion;
use aws_sdk_s3::{
config::{Credentials, Region},
Client as S3Client,
};
use server_config::{OptionalConfigs, S3Config, S3InstancesConfig};
use server_global::global::{get_config, GLOBAL_PRIMARY_S3, GLOBAL_S3_POOL};
use crate::{project_error, project_info};
/// 初始化主 S3 客户端
pub async fn init_primary_s3() {
if let Some(config) = get_config::<S3Config>().await {
match create_s3_client(&config).await {
Ok(client) => {
*GLOBAL_PRIMARY_S3.write().await = Some(Arc::new(client));
project_info!("Primary S3 client initialized");
},
Err(e) => {
project_error!("Failed to initialize primary S3 client: {}", e);
process::exit(1);
},
}
}
}
/// 初始化所有 S3 客户端
pub async fn init_s3_pools() {
if let Some(s3_instances_config) = get_config::<OptionalConfigs<S3InstancesConfig>>().await {
if let Some(s3_instances) = &s3_instances_config.configs {
let _ = init_s3_pool(Some(s3_instances.clone())).await;
}
}
}
pub async fn init_s3_pool(
s3_instances_config: Option<Vec<S3InstancesConfig>>,
) -> Result<(), String> {
if let Some(s3_instances) = s3_instances_config {
for s3_instance in s3_instances {
init_s3_connection(&s3_instance.name, &s3_instance.s3).await?;
}
}
Ok(())
}
async fn init_s3_connection(name: &str, config: &S3Config) -> Result<(), String> {
match create_s3_client(config).await {
Ok(client) => {
let client_arc = Arc::new(client);
GLOBAL_S3_POOL
.write()
.await
.insert(name.to_string(), client_arc);
project_info!("S3 client '{}' initialized", name);
Ok(())
},
Err(e) => {
let error_msg = format!("Failed to initialize S3 client '{}': {}", name, e);
project_error!("{}", error_msg);
Err(error_msg)
},
}
}
async fn create_s3_client(config: &S3Config) -> Result<S3Client, String> {
let mut aws_config_builder =
aws_config::defaults(BehaviorVersion::latest()).region(Region::new(config.region.clone()));
if let Some(endpoint) = &config.endpoint {
aws_config_builder = aws_config_builder.endpoint_url(endpoint);
}
if !config.access_key_id.is_empty() && !config.secret_access_key.is_empty() {
aws_config_builder = aws_config_builder.credentials_provider(Credentials::new(
config.access_key_id.clone(),
config.secret_access_key.clone(),
None,
None,
"soybean-admin-rust",
));
}
let aws_config = aws_config_builder.load().await;
let client = S3Client::new(&aws_config);
// 验证 S3 客户端连接
match client.list_buckets().send().await {
Ok(_) => Ok(client),
Err(e) => Err(format!("Failed to connect to S3: {}", e)),
}
}
/// 获取主要的 S3 客户端
pub async fn get_primary_s3_client() -> Option<Arc<S3Client>> {
GLOBAL_PRIMARY_S3.read().await.clone()
}
/// 获取命名的 S3 客户端
pub async fn get_s3_pool_connection(name: &str) -> Option<Arc<S3Client>> {
GLOBAL_S3_POOL.read().await.get(name).cloned()
}
/// 添加或更新 S3 客户端池中的客户端
pub async fn add_or_update_s3_pool(name: &str, config: &S3Config) -> Result<(), String> {
init_s3_connection(name, config).await
}
/// 移除命名的 S3 客户端
pub async fn remove_s3_pool(name: &str) -> Result<(), String> {
let mut s3_pool = GLOBAL_S3_POOL.write().await;
s3_pool
.remove(name)
.ok_or_else(|| format!("S3 client '{}' not found", name))?;
project_info!("S3 client '{}' removed", name);
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::initialize_config;
use aws_sdk_s3::types::{BucketLocationConstraint, CreateBucketConfiguration};
use log::LevelFilter;
use simple_logger::SimpleLogger;
use tokio::sync::Mutex;
static INITIALIZED: Mutex<Option<Arc<()>>> = Mutex::const_new(None);
static TEST_BUCKET_NAME: &str = "test-bucket-rust-s3";
fn setup_logger() {
let _ = SimpleLogger::new().with_level(LevelFilter::Info).init();
}
async fn init() {
let mut initialized = INITIALIZED.lock().await;
if initialized.is_none() {
initialize_config("../resources/application.yaml").await;
*initialized = Some(Arc::new(()));
}
}
// 测试 S3 基本操作
async fn test_s3_operations(client: &S3Client) -> Result<(), String> {
// 确保测试桶存在
let bucket_exists = client
.head_bucket()
.bucket(TEST_BUCKET_NAME)
.send()
.await
.is_ok();
if !bucket_exists {
let constraint =
BucketLocationConstraint::from(client.config().region().unwrap().as_ref());
let bucket_config = CreateBucketConfiguration::builder()
.location_constraint(constraint)
.build();
client
.create_bucket()
.bucket(TEST_BUCKET_NAME)
.create_bucket_configuration(bucket_config)
.send()
.await
.map_err(|e| format!("Failed to create test bucket: {}", e))?;
}
// 上传测试对象
let test_object_key = "test-object.txt";
let test_content = "Hello, S3!";
client
.put_object()
.bucket(TEST_BUCKET_NAME)
.key(test_object_key)
.body(test_content.as_bytes().to_vec().into())
.send()
.await
.map_err(|e| format!("Failed to upload test object: {}", e))?;
// 获取测试对象
let get_response = client
.get_object()
.bucket(TEST_BUCKET_NAME)
.key(test_object_key)
.send()
.await
.map_err(|e| format!("Failed to get test object: {}", e))?;
let data = get_response
.body
.collect()
.await
.map_err(|e| format!("Failed to read object data: {}", e))?;
let content = String::from_utf8(data.into_bytes().to_vec())
.map_err(|e| format!("Failed to convert data to string: {}", e))?;
if content != test_content {
return Err(format!(
"Object content mismatch. Expected: '{}', Got: '{}'",
test_content, content
));
}
// 删除测试对象
client
.delete_object()
.bucket(TEST_BUCKET_NAME)
.key(test_object_key)
.send()
.await
.map_err(|e| format!("Failed to delete test object: {}", e))?;
Ok(())
}
#[tokio::test]
async fn test_primary_s3_connection() {
setup_logger();
init().await;
init_primary_s3().await;
let client = get_primary_s3_client().await;
assert!(client.is_some(), "Primary S3 client does not exist");
if let Some(client) = client {
let result = test_s3_operations(&client).await;
assert!(
result.is_ok(),
"S3 operations test failed: {:?}",
result.err()
);
}
}
#[tokio::test]
async fn test_s3_pool_operations() {
setup_logger();
init().await;
// 使用测试配置创建测试客户端
let test_config = S3InstancesConfig {
name: "test_s3".to_string(),
s3: S3Config {
region: "us-east-1".to_string(),
access_key_id: "test_key".to_string(),
secret_access_key: "test_secret".to_string(),
endpoint: Some("http://localhost:4566".to_string()),
},
};
// 初始化测试S3池
let result = init_s3_pool(Some(vec![test_config.clone()])).await;
assert!(
result.is_ok(),
"Failed to initialize S3 pool: {:?}",
result.err()
);
// 测试连接池连接
let pool_connection = get_s3_pool_connection("test_s3").await;
assert!(pool_connection.is_some(), "Pool connection not found");
if let Some(client) = pool_connection {
let result = test_s3_operations(&client).await;
assert!(
result.is_ok(),
"S3 pool operations test failed: {:?}",
result.err()
);
}
// 测试添加新连接
let add_result = add_or_update_s3_pool("test_new", &test_config.s3).await;
assert!(add_result.is_ok(), "Failed to add S3 connection");
// 测试移除连接
let remove_result = remove_s3_pool("test_new").await;
assert!(remove_result.is_ok(), "Failed to remove S3 connection");
let connection_after_removal = get_s3_pool_connection("test_new").await;
assert!(
connection_after_removal.is_none(),
"S3 connection still exists after removal"
);
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/tests/lib.rs | server/initialize/tests/lib.rs | mod jwt;
mod jwt_auth_middleware;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/tests/jwt.rs | server/initialize/tests/jwt.rs | use server_core::web::{auth::Claims, jwt::JwtUtils};
#[cfg(test)]
mod tests {
use std::sync::Arc;
use server_initialize::{initialize_config, initialize_keys_and_validation};
use tokio::sync::Mutex;
use super::*;
fn create_claims(issuer: &str, audience: &str) -> Claims {
let mut claims = Claims::new(
"user123".to_string(),
audience.to_string(),
"account".to_string(),
vec!["admin".to_string()],
"example_domain".to_string(),
Option::from("example_org".to_string()),
);
claims.set_iss(issuer.to_string());
claims
}
static INITIALIZED: Mutex<Option<Arc<()>>> = Mutex::const_new(None);
async fn init() {
let mut initialized = INITIALIZED.lock().await;
if initialized.is_none() {
initialize_config("../resources/application.yaml").await;
initialize_keys_and_validation().await;
*initialized = Some(Arc::new(()));
}
}
#[tokio::test]
async fn test_validate_token_success() {
init().await;
let claims = create_claims(
"https://github.com/ByteByteBrew/soybean-admin-rust",
"audience",
);
let token = JwtUtils::generate_token(&claims).await.unwrap();
let result = JwtUtils::validate_token(&token, "audience").await;
assert!(result.is_ok());
}
#[tokio::test]
async fn test_validate_token_invalid_audience() {
init().await;
let claims = create_claims(
"https://github.com/ByteByteBrew/soybean-admin-rust",
"invalid_audience",
);
let token = JwtUtils::generate_token(&claims).await.unwrap();
let result = JwtUtils::validate_token(&token, "audience").await;
assert!(result.is_err());
}
// #[tokio::test]
// async fn test_validate_token_invalid_issuer() {
// init().await;
//
// let claims = create_claims("invalid_issuer", "audience");
// let token = JwtUtils::generate_token(&claims).await.unwrap();
//
// let result = JwtUtils::validate_token(&token, "audience").await;
// assert!(result.is_err());
// }
//
// #[tokio::test]
// async fn test_validate_token_expired() {
// init().await;
//
// let claims =
// create_claims("https://github.com/ByteByteBrew/soybean-admin-rust", "audience");
// let token = JwtUtils::generate_token(&claims).await.unwrap();
//
// let result = JwtUtils::validate_token(&token, "audience").await;
// assert!(result.is_err());
// }
#[tokio::test]
async fn test_validate_token_invalid_signature() {
init().await;
let claims = create_claims(
"https://github.com/ByteByteBrew/soybean-admin-rust",
"audience",
);
let token = JwtUtils::generate_token(&claims).await.unwrap();
let mut invalid_token = token.clone();
let len = invalid_token.len();
invalid_token.replace_range((len - 1)..len, "X");
let result = JwtUtils::validate_token(&invalid_token, "audience").await;
assert!(result.is_err());
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/initialize/tests/jwt_auth_middleware.rs | server/initialize/tests/jwt_auth_middleware.rs | #[cfg(test)]
mod tests {
use axum::{
body::Body,
http::{Request, StatusCode},
routing::get,
Router,
};
use axum_casbin::{
casbin::{DefaultModel, FileAdapter},
CasbinAxumLayer,
};
use chrono::{Duration, Utc};
use jsonwebtoken::{encode, EncodingKey, Header};
use server_constant::definition::Audience;
use server_core::web::{
auth::{Claims, User},
res::Res,
};
use server_initialize::{initialize_config, initialize_keys_and_validation};
use server_middleware::jwt_auth_middleware;
use tower::{ServiceBuilder, ServiceExt};
async fn user_info_handler(user: User) -> Res<User> {
Res::new_data(user)
}
#[tokio::test]
async fn test_user_info_endpoint() {
let m = DefaultModel::from_file("../../axum-casbin/examples/rbac_with_domains_model.conf")
.await
.unwrap();
let a = FileAdapter::new("../../axum-casbin/examples/rbac_with_domains_policy.csv");
let casbin_middleware = CasbinAxumLayer::new(m, a).await.unwrap();
initialize_config("../resources/application.yaml").await;
initialize_keys_and_validation().await;
let app = Router::new()
.route("/pen/1", get(user_info_handler))
.layer(casbin_middleware)
.layer(axum::middleware::from_fn(move |req, next| {
jwt_auth_middleware(req, next, Audience::ManagementPlatform.as_str())
}));
let service = ServiceBuilder::new().service(app);
let token = generate_jwt();
let request = Request::builder()
.uri("/pen/1")
.header("Authorization", format!("Bearer {}", token))
.body(Body::empty())
.unwrap();
let response = service.oneshot(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
println!("headers is {:?}", response.headers());
let body_bytes = axum::body::to_bytes(response.into_body(), 1000)
.await
.unwrap();
let body_str = String::from_utf8(body_bytes.to_vec()).unwrap();
println!("body_str is {}", body_str);
}
fn generate_jwt() -> String {
let mut claims = Claims::new(
"admin".to_string(),
Audience::ManagementPlatform.as_str().to_string(),
"alice".to_string(),
vec!["example_role".to_string()],
"domain1".to_string(),
Option::from("example_org".to_string()),
);
let now = Utc::now();
claims.set_exp((now + Duration::seconds(7200)).timestamp() as usize);
let encoding_key = EncodingKey::from_secret("soybean-admin-rust".as_ref());
encode(&Header::default(), &claims, &encoding_key).unwrap()
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/utils/src/tree_util.rs | server/utils/src/tree_util.rs | use std::{collections::HashMap, hash::Hash};
use rayon::prelude::*;
/// 通用树构建器
///
/// 提供高性能的树结构构建功能,支持并行处理和自定义排序。
///
/// # 特点
/// - 高性能:支持并行排序和处理
/// - 内存优化:智能预分配内存
/// - 通用性:支持任意数据类型
/// - 灵活性:支持自定义ID类型和排序规则
pub struct TreeBuilder;
impl TreeBuilder {
/// 构建有序树结构(支持并行)
///
/// # 参数
/// - `nodes`: 源节点集合
/// - `id_fn`: 获取节点ID的函数
/// - `pid_fn`: 获取父节点ID的函数
/// - `order_fn`: 获取排序键的函数
/// - `set_children_fn`: 设置子节点的函数
///
/// # 类型参数
/// - `T`: 节点类型
/// - `Id`: ID类型,必须可比较和可哈希
/// - `Order`: 排序键类型,必须可比较
///
/// # 示例
/// ```rust
/// let tree = TreeBuilder::build(
/// nodes,
/// |node| node.id, // ID获取器
/// |node| node.parent_id, // 父ID获取器
/// |node| node.sequence, // 排序键
/// |node, children| node.children = children, // 设置子节点
/// );
/// ```
///
/// # 性能注意事项
/// - 对于大数据集(>1000条),会自动调整内存分配策略
/// - 使用并行排序提高性能
/// - 预分配内存减少重新分配
#[inline]
pub fn build<T, Id, Order, F1, F2, F3, F4>(
mut nodes: Vec<T>,
id_fn: F1,
pid_fn: F2,
order_fn: F3,
mut set_children_fn: F4,
) -> Vec<T>
where
T: Sized + Send + Sync,
Id: Eq + Hash + Send + Sync,
Order: Ord + Send + Sync,
F1: Fn(&T) -> Id + Send + Sync,
F2: Fn(&T) -> Option<Id> + Send + Sync,
F3: Fn(&T) -> Order + Send + Sync,
F4: FnMut(&mut T, Vec<T>) + Send + Sync,
{
if nodes.is_empty() {
return vec![];
}
let len = nodes.len();
// 并行排序
nodes.par_sort_unstable_by_key(|node| order_fn(node));
// 智能容量预分配
let (root_capacity, child_capacity) = Self::calculate_capacity(len);
let mut root_nodes = Vec::with_capacity(root_capacity);
let mut child_map = HashMap::with_capacity(child_capacity);
// 单次遍历分组
for node in nodes {
match pid_fn(&node) {
Some(pid) => {
child_map
.entry(pid)
.or_insert_with(|| Vec::with_capacity(4))
.push(node);
},
None => root_nodes.push(node),
}
}
// 递归构建树
Self::attach_children(
&mut root_nodes,
&mut child_map,
&id_fn,
&mut set_children_fn,
);
root_nodes
}
/// 构建无序树结构(最高性能)
///
/// 与 `build` 方法相比,此方法:
/// - 不进行排序,性能更高
/// - 不需要并行支持
/// - 内存占用更少
///
/// # 使用场景
/// - 数据已经有序
/// - 不需要排序
/// - 追求最高性能
///
/// # 示例
/// ```rust
/// let tree = TreeBuilder::build_fast(
/// nodes,
/// |node| node.id,
/// |node| node.parent_id,
/// |node, children| node.children = children,
/// );
/// ```
#[inline]
pub fn build_fast<T, Id, F1, F2, F3>(
nodes: Vec<T>,
id_fn: F1,
pid_fn: F2,
mut set_children_fn: F3,
) -> Vec<T>
where
T: Sized,
Id: Eq + Hash,
F1: Fn(&T) -> Id,
F2: Fn(&T) -> Option<Id>,
F3: FnMut(&mut T, Vec<T>),
{
if nodes.is_empty() {
return vec![];
}
let len = nodes.len();
let (root_capacity, child_capacity) = Self::calculate_capacity(len);
let mut root_nodes = Vec::with_capacity(root_capacity);
let mut child_map = HashMap::with_capacity(child_capacity);
for node in nodes {
match pid_fn(&node) {
Some(pid) => {
child_map
.entry(pid)
.or_insert_with(|| Vec::with_capacity(4))
.push(node);
},
None => root_nodes.push(node),
}
}
Self::attach_children(
&mut root_nodes,
&mut child_map,
&id_fn,
&mut set_children_fn,
);
root_nodes
}
/// 计算最优容量分配
#[inline]
fn calculate_capacity(len: usize) -> (usize, usize) {
if len < 1000 {
(len / 3, len * 2 / 3)
} else {
(len / 10, len * 9 / 10)
}
}
/// 递归构建树结构
#[inline]
fn attach_children<T, Id, F1, F2>(
nodes: &mut Vec<T>,
child_map: &mut HashMap<Id, Vec<T>>,
id_fn: &F1,
set_children_fn: &mut F2,
) where
Id: Eq + Hash,
F1: Fn(&T) -> Id,
F2: FnMut(&mut T, Vec<T>),
{
for node in nodes.iter_mut() {
if let Some(mut children) = child_map.remove(&id_fn(node)) {
Self::attach_children(&mut children, child_map, id_fn, set_children_fn);
set_children_fn(node, children);
}
}
}
}
#[cfg(test)]
mod tests {
use std::time::Instant;
use super::*;
#[derive(Clone, Debug, PartialEq)]
struct Node {
id: i32,
pid: Option<i32>,
order: i32,
children: Vec<Node>,
}
#[test]
fn test_build_tree() {
let nodes = vec![
Node {
id: 1,
pid: None,
order: 1,
children: vec![],
},
Node {
id: 2,
pid: Some(1),
order: 2,
children: vec![],
},
Node {
id: 3,
pid: Some(1),
order: 1,
children: vec![],
},
];
let tree = TreeBuilder::build(
nodes,
|node| node.id,
|node| node.pid,
|node| node.order,
|node, children| node.children = children,
);
assert_eq!(tree.len(), 1);
assert_eq!(tree[0].children.len(), 2);
assert_eq!(tree[0].children[0].id, 3);
assert_eq!(tree[0].children[1].id, 2);
}
#[test]
fn test_performance() {
let mut nodes = Vec::with_capacity(10000);
for i in 0..10000 {
nodes.push(Node {
id: i,
pid: if i == 0 { None } else { Some((i - 1) / 10) },
order: i % 100,
children: vec![],
});
}
let start = Instant::now();
let _tree1 = TreeBuilder::build(
nodes.clone(),
|node| node.id,
|node| node.pid,
|node| node.order,
|node, children| node.children = children,
);
println!("Parallel build: {:?}", start.elapsed());
let start = Instant::now();
let _tree2 = TreeBuilder::build_fast(
nodes,
|node| node.id,
|node| node.pid,
|node, children| node.children = children,
);
println!("Fast build: {:?}", start.elapsed());
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/utils/src/lib.rs | server/utils/src/lib.rs | mod secure_util;
mod tree_util;
pub use secure_util::*;
pub use tree_util::*;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/utils/src/secure_util.rs | server/utils/src/secure_util.rs | use std::error::Error;
use argon2::{
password_hash::{rand_core::OsRng, SaltString},
Argon2, PasswordHash, PasswordHasher, PasswordVerifier,
};
use lazy_static::lazy_static;
lazy_static! {
static ref ARGON2: Argon2<'static> = Argon2::default();
}
pub struct SecureUtil;
impl SecureUtil {
pub fn hash_password(password: &[u8]) -> Result<String, Box<dyn Error>> {
let salt = SaltString::generate(&mut OsRng);
let password_hash = ARGON2.hash_password(password, &salt)?.to_string();
Ok(password_hash)
}
pub fn verify_password(password: &[u8], password_hash: &str) -> Result<bool, Box<dyn Error>> {
let parsed_hash = PasswordHash::new(password_hash)?;
match ARGON2.verify_password(password, &parsed_hash) {
Ok(_) => Ok(true),
Err(e) => Err(Box::new(e)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_password_hash_and_verification() {
let password = b"example_password";
let password_hash = SecureUtil::hash_password(password)
.expect("Failed to hash password, check the input and environment setup");
assert!(
SecureUtil::verify_password(password, &password_hash).is_ok(),
"Password verification should succeed for the correct password"
);
let wrong_password = b"wrong_password";
assert!(
SecureUtil::verify_password(wrong_password, &password_hash).is_err(),
"Password verification should fail for the wrong password"
);
}
#[test]
fn test_print_hashed_password() {
let password = b"123456";
let password_hash = SecureUtil::hash_password(password)
.expect("Failed to hash password, check the input and environment setup");
println!("Hashed password for '123456': {}", password_hash);
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/lib.rs | server/api/src/lib.rs | pub mod admin;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_endpoint_api.rs | server/api/src/admin/sys_endpoint_api.rs | use std::{collections::BTreeMap, sync::Arc};
use axum::{
extract::{Path, Query},
Extension,
};
use axum_casbin::{casbin::MgmtApi, CasbinAxumLayer};
use server_core::web::{auth::User, error::AppError, page::PaginatedData, res::Res};
use server_service::admin::{
EndpointPageRequest, EndpointTree, SysEndpointModel, SysEndpointService, TEndpointService,
};
pub struct SysEndpointApi;
impl SysEndpointApi {
pub async fn get_paginated_endpoints(
Query(params): Query<EndpointPageRequest>,
Extension(service): Extension<Arc<SysEndpointService>>,
) -> Result<Res<PaginatedData<SysEndpointModel>>, AppError> {
service
.find_paginated_endpoints(params)
.await
.map(Res::new_data)
}
pub async fn get_auth_endpoints(
Path(role_code): Path<String>,
Extension(user): Extension<User>,
Extension(mut cache_enforcer): Extension<CasbinAxumLayer>,
) -> Result<Res<Vec<BTreeMap<String, String>>>, AppError> {
let enforcer = cache_enforcer.get_enforcer();
let enforcer_read = enforcer.read().await;
let policies = enforcer_read.get_filtered_policy(0, vec![role_code, user.domain()]);
let formatted_policies = policies
.into_iter()
.map(|policy| {
let mut values = policy.into_iter();
let mut map = BTreeMap::new();
map.insert("v0".to_string(), values.next().unwrap_or_default());
map.insert("v1".to_string(), values.next().unwrap_or_default());
map.insert("v2".to_string(), values.next().unwrap_or_default());
map.insert("v3".to_string(), values.next().unwrap_or_default());
map
})
.collect();
Ok(Res::new_data(formatted_policies))
}
pub async fn tree_endpoint(
Extension(service): Extension<Arc<SysEndpointService>>,
) -> Result<Res<Vec<EndpointTree>>, AppError> {
service.tree_endpoint().await.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_menu_api.rs | server/api/src/admin/sys_menu_api.rs | use std::sync::Arc;
use axum::{extract::Path, Extension};
use server_core::web::{auth::User, error::AppError, res::Res, validator::ValidatedForm};
use server_service::admin::{
CreateMenuInput, MenuRoute, MenuTree, SysMenuModel, SysMenuService, TMenuService,
UpdateMenuInput,
};
pub struct SysMenuApi;
impl SysMenuApi {
pub async fn tree_menu(
Extension(service): Extension<Arc<SysMenuService>>,
) -> Result<Res<Vec<MenuTree>>, AppError> {
service.tree_menu().await.map(Res::new_data)
}
pub async fn get_menu_list(
Extension(service): Extension<Arc<SysMenuService>>,
) -> Result<Res<Vec<MenuTree>>, AppError> {
service.get_menu_list().await.map(Res::new_data)
}
pub async fn get_constant_routes(
Extension(service): Extension<Arc<SysMenuService>>,
) -> Result<Res<Vec<MenuRoute>>, AppError> {
service.get_constant_routes().await.map(Res::new_data)
}
pub async fn create_menu(
Extension(service): Extension<Arc<SysMenuService>>,
Extension(user): Extension<User>,
ValidatedForm(input): ValidatedForm<CreateMenuInput>,
) -> Result<Res<SysMenuModel>, AppError> {
service.create_menu(input, user).await.map(Res::new_data)
}
pub async fn get_menu(
Path(id): Path<i32>,
Extension(service): Extension<Arc<SysMenuService>>,
) -> Result<Res<SysMenuModel>, AppError> {
service.get_menu(id).await.map(Res::new_data)
}
pub async fn update_menu(
Extension(service): Extension<Arc<SysMenuService>>,
Extension(user): Extension<User>,
ValidatedForm(input): ValidatedForm<UpdateMenuInput>,
) -> Result<Res<SysMenuModel>, AppError> {
service.update_menu(input, user).await.map(Res::new_data)
}
pub async fn delete_menu(
Path(id): Path<i32>,
Extension(service): Extension<Arc<SysMenuService>>,
Extension(user): Extension<User>,
) -> Result<Res<()>, AppError> {
print!("user is {:#?}", user);
service.delete_menu(id, user).await.map(Res::new_data)
}
pub async fn get_auth_routes(
Path(role_id): Path<String>,
Extension(service): Extension<Arc<SysMenuService>>,
Extension(user): Extension<User>,
) -> Result<Res<Vec<i32>>, AppError> {
service
.get_menu_ids_by_role_id(role_id, user.domain())
.await
.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_login_log_api.rs | server/api/src/admin/sys_login_log_api.rs | use std::sync::Arc;
use axum::extract::{Extension, Query};
use server_core::web::{error::AppError, page::PaginatedData, res::Res};
use server_service::admin::{
LoginLogPageRequest, SysLoginLogModel, SysLoginLogService, TLoginLogService,
};
pub struct SysLoginLogApi;
impl SysLoginLogApi {
pub async fn get_paginated_login_logs(
Query(params): Query<LoginLogPageRequest>,
Extension(service): Extension<Arc<SysLoginLogService>>,
) -> Result<Res<PaginatedData<SysLoginLogModel>>, AppError> {
service
.find_paginated_login_logs(params)
.await
.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_access_key_api.rs | server/api/src/admin/sys_access_key_api.rs | use std::sync::Arc;
use axum::{
extract::{Path, Query},
Extension,
};
use server_core::web::{error::AppError, page::PaginatedData, res::Res, validator::ValidatedForm};
use server_service::admin::{
AccessKeyPageRequest, CreateAccessKeyInput, SysAccessKeyModel, SysAccessKeyService,
TAccessKeyService,
};
pub struct SysAccessKeyApi;
impl SysAccessKeyApi {
pub async fn get_paginated_access_keys(
Query(params): Query<AccessKeyPageRequest>,
Extension(service): Extension<Arc<SysAccessKeyService>>,
) -> Result<Res<PaginatedData<SysAccessKeyModel>>, AppError> {
service
.find_paginated_access_keys(params)
.await
.map(Res::new_data)
}
pub async fn create_access_key(
Extension(service): Extension<Arc<SysAccessKeyService>>,
ValidatedForm(input): ValidatedForm<CreateAccessKeyInput>,
) -> Result<Res<SysAccessKeyModel>, AppError> {
service.create_access_key(input).await.map(Res::new_data)
}
pub async fn delete_access_key(
Path(id): Path<String>,
Extension(service): Extension<Arc<SysAccessKeyService>>,
) -> Result<Res<()>, AppError> {
service.delete_access_key(&id).await.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_role_api.rs | server/api/src/admin/sys_role_api.rs | use std::sync::Arc;
use axum::{
extract::{Path, Query},
Extension,
};
use server_core::web::{error::AppError, page::PaginatedData, res::Res, validator::ValidatedForm};
use server_service::admin::{
CreateRoleInput, RolePageRequest, SysRoleModel, SysRoleService, TRoleService, UpdateRoleInput,
};
pub struct SysRoleApi;
impl SysRoleApi {
pub async fn get_paginated_roles(
Query(params): Query<RolePageRequest>,
Extension(service): Extension<Arc<SysRoleService>>,
) -> Result<Res<PaginatedData<SysRoleModel>>, AppError> {
service
.find_paginated_roles(params)
.await
.map(Res::new_data)
}
pub async fn create_role(
Extension(service): Extension<Arc<SysRoleService>>,
ValidatedForm(input): ValidatedForm<CreateRoleInput>,
) -> Result<Res<SysRoleModel>, AppError> {
service.create_role(input).await.map(Res::new_data)
}
pub async fn get_role(
Path(id): Path<String>,
Extension(service): Extension<Arc<SysRoleService>>,
) -> Result<Res<SysRoleModel>, AppError> {
service.get_role(&id).await.map(Res::new_data)
}
pub async fn update_role(
Extension(service): Extension<Arc<SysRoleService>>,
ValidatedForm(input): ValidatedForm<UpdateRoleInput>,
) -> Result<Res<SysRoleModel>, AppError> {
service.update_role(input).await.map(Res::new_data)
}
pub async fn delete_role(
Path(id): Path<String>,
Extension(service): Extension<Arc<SysRoleService>>,
) -> Result<Res<()>, AppError> {
service.delete_role(&id).await.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/mod.rs | server/api/src/admin/mod.rs | pub use sys_access_key_api::SysAccessKeyApi;
pub use sys_authentication_api::SysAuthenticationApi;
pub use sys_domain_api::SysDomainApi;
pub use sys_endpoint_api::SysEndpointApi;
pub use sys_login_log_api::SysLoginLogApi;
pub use sys_menu_api::SysMenuApi;
pub use sys_operation_log_api::SysOperationLogApi;
pub use sys_organization_api::SysOrganizationApi;
pub use sys_role_api::SysRoleApi;
pub use sys_sandbox_api::SysSandboxApi;
pub use sys_user_api::SysUserApi;
mod sys_access_key_api;
mod sys_authentication_api;
mod sys_domain_api;
mod sys_endpoint_api;
mod sys_login_log_api;
mod sys_menu_api;
mod sys_operation_log_api;
mod sys_organization_api;
mod sys_role_api;
mod sys_sandbox_api;
mod sys_user_api;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_authentication_api.rs | server/api/src/admin/sys_authentication_api.rs | use std::{net::SocketAddr, sync::Arc};
use axum::{extract::ConnectInfo, http::HeaderMap, Extension};
use axum_casbin::CasbinAxumLayer;
use axum_extra::{headers::UserAgent, TypedHeader};
use server_core::web::{
auth::User, error::AppError, res::Res, util::ClientIp, validator::ValidatedForm, RequestId,
};
use server_service::{
admin::{
dto::sys_auth_dto::LoginContext, AssignPermissionDto, AssignRouteDto, AuthOutput,
LoginInput, SysAuthService, SysAuthorizationService, TAuthService, TAuthorizationService,
UserInfoOutput, UserRoute,
},
Audience,
};
pub struct SysAuthenticationApi;
impl SysAuthenticationApi {
pub async fn login_handler(
ConnectInfo(addr): ConnectInfo<SocketAddr>,
headers: HeaderMap,
TypedHeader(user_agent): TypedHeader<UserAgent>,
Extension(request_id): Extension<RequestId>,
Extension(service): Extension<Arc<SysAuthService>>,
ValidatedForm(input): ValidatedForm<LoginInput>,
) -> Result<Res<AuthOutput>, AppError> {
let client_ip = {
let header_ip = ClientIp::get_real_ip(&headers);
if header_ip == "unknown" {
addr.ip().to_string()
} else {
header_ip
}
};
let address = xdb::searcher::search_by_ip(client_ip.as_str())
.unwrap_or_else(|_| "Unknown Location".to_string());
let login_context = LoginContext {
client_ip,
client_port: Some(addr.port() as i32),
address,
user_agent: user_agent.as_str().to_string(),
request_id: request_id.to_string(),
audience: Audience::ManagementPlatform,
login_type: "PC".to_string(),
domain: "built-in".to_string(),
};
service
.pwd_login(input, login_context)
.await
.map(Res::new_data)
}
pub async fn get_user_info(
Extension(user): Extension<User>,
) -> Result<Res<UserInfoOutput>, AppError> {
let user_info = UserInfoOutput {
user_id: user.user_id(),
user_name: user.username(),
roles: user.subject(),
};
Ok(Res::new_data(user_info))
}
pub async fn get_user_routes(
Extension(user): Extension<User>,
Extension(service): Extension<Arc<SysAuthService>>,
) -> Result<Res<UserRoute>, AppError> {
let routes = service
.get_user_routes(&user.subject(), &user.domain())
.await?;
Ok(Res::new_data(routes))
}
/// 为角色分配权限
///
/// 将指定的权限分配给指定域中的角色。
pub async fn assign_permission(
Extension(service): Extension<Arc<SysAuthorizationService>>,
Extension(mut cache_enforcer): Extension<CasbinAxumLayer>,
ValidatedForm(input): ValidatedForm<AssignPermissionDto>,
) -> Result<Res<()>, AppError> {
let enforcer = cache_enforcer.get_enforcer();
service
.assign_permission(input.domain, input.role_id, input.permissions, enforcer)
.await?;
Ok(Res::new_data(()))
}
/// 为角色分配路由
///
/// 将指定的路由分配给指定域中的角色。
pub async fn assign_routes(
Extension(service): Extension<Arc<SysAuthorizationService>>,
ValidatedForm(input): ValidatedForm<AssignRouteDto>,
) -> Result<Res<()>, AppError> {
service
.assign_routes(input.domain, input.role_id, input.route_ids)
.await?;
Ok(Res::new_data(()))
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_domain_api.rs | server/api/src/admin/sys_domain_api.rs | use std::sync::Arc;
use axum::{
extract::{Path, Query},
Extension,
};
use server_core::web::{error::AppError, page::PaginatedData, res::Res, validator::ValidatedForm};
use server_service::admin::{
CreateDomainInput, DomainPageRequest, SysDomainModel, SysDomainService, TDomainService,
UpdateDomainInput,
};
pub struct SysDomainApi;
impl SysDomainApi {
pub async fn get_paginated_domains(
Query(params): Query<DomainPageRequest>,
Extension(service): Extension<Arc<SysDomainService>>,
) -> Result<Res<PaginatedData<SysDomainModel>>, AppError> {
service
.find_paginated_domains(params)
.await
.map(Res::new_data)
}
pub async fn create_domain(
Extension(service): Extension<Arc<SysDomainService>>,
ValidatedForm(input): ValidatedForm<CreateDomainInput>,
) -> Result<Res<SysDomainModel>, AppError> {
service.create_domain(input).await.map(Res::new_data)
}
pub async fn get_domain(
Path(id): Path<String>,
Extension(service): Extension<Arc<SysDomainService>>,
) -> Result<Res<SysDomainModel>, AppError> {
service.get_domain(&id).await.map(Res::new_data)
}
pub async fn update_domain(
Extension(service): Extension<Arc<SysDomainService>>,
ValidatedForm(input): ValidatedForm<UpdateDomainInput>,
) -> Result<Res<SysDomainModel>, AppError> {
service.update_domain(input).await.map(Res::new_data)
}
pub async fn delete_domain(
Path(id): Path<String>,
Extension(service): Extension<Arc<SysDomainService>>,
) -> Result<Res<()>, AppError> {
service.delete_domain(&id).await.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_organization_api.rs | server/api/src/admin/sys_organization_api.rs | use std::sync::Arc;
use axum::extract::{Extension, Query};
use server_core::web::{error::AppError, page::PaginatedData, res::Res};
use server_service::admin::{
OrganizationPageRequest, SysOrganizationModel, SysOrganizationService, TOrganizationService,
};
pub struct SysOrganizationApi;
impl SysOrganizationApi {
pub async fn get_paginated_organizations(
Query(params): Query<OrganizationPageRequest>,
Extension(service): Extension<Arc<SysOrganizationService>>,
) -> Result<Res<PaginatedData<SysOrganizationModel>>, AppError> {
service
.find_paginated_organizations(params)
.await
.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_sandbox_api.rs | server/api/src/admin/sys_sandbox_api.rs | use server_core::web::{error::AppError, res::Res};
pub struct SysSandboxApi;
impl SysSandboxApi {
pub async fn test_simple_api_key() -> Result<Res<String>, AppError> {
Ok(Res::new_data("SimpleApiKey".to_string()))
}
pub async fn test_complex_api_key() -> Result<Res<String>, AppError> {
Ok(Res::new_data("ComplexApiKey".to_string()))
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_operation_log_api.rs | server/api/src/admin/sys_operation_log_api.rs | use std::sync::Arc;
use axum::extract::{Extension, Query};
use server_core::web::{error::AppError, page::PaginatedData, res::Res};
use server_service::admin::{
OperationLogPageRequest, SysOperationLogModel, SysOperationLogService, TOperationLogService,
};
pub struct SysOperationLogApi;
impl SysOperationLogApi {
pub async fn get_paginated_operation_logs(
Query(params): Query<OperationLogPageRequest>,
Extension(service): Extension<Arc<SysOperationLogService>>,
) -> Result<Res<PaginatedData<SysOperationLogModel>>, AppError> {
service
.find_paginated_operation_logs(params)
.await
.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/api/src/admin/sys_user_api.rs | server/api/src/admin/sys_user_api.rs | use std::sync::Arc;
use axum::{
extract::{Path, Query},
Extension,
};
use axum_casbin::{casbin::MgmtApi, CasbinAxumLayer};
use server_core::web::{
auth::User, error::AppError, page::PaginatedData, res::Res, validator::ValidatedForm,
};
use server_service::admin::{
CreateUserInput, SysUserService, TUserService, UpdateUserInput, UserPageRequest,
UserWithoutPassword,
};
pub struct SysUserApi;
impl SysUserApi {
pub async fn get_all_users(
Extension(service): Extension<Arc<SysUserService>>,
) -> Result<Res<Vec<UserWithoutPassword>>, AppError> {
service.find_all().await.map(Res::new_data)
}
pub async fn get_paginated_users(
Query(params): Query<UserPageRequest>,
Extension(service): Extension<Arc<SysUserService>>,
user: User,
) -> Result<Res<PaginatedData<UserWithoutPassword>>, AppError> {
print!("user is {:#?}", user);
service
.find_paginated_users(params)
.await
.map(Res::new_data)
}
pub async fn remove_policies(
Extension(mut cache_enforcer): Extension<CasbinAxumLayer>,
) -> Res<bool> {
let enforcer = cache_enforcer.get_enforcer();
let mut enforcer_write = enforcer.write().await;
let rule = vec![
"1".to_string(),
"built-in".to_string(),
"/user/users".to_string(),
"GET".to_string(),
];
let _ = enforcer_write.remove_policies(vec![rule]).await;
Res::new_data(true)
}
pub async fn add_policies(
Extension(mut cache_enforcer): Extension<CasbinAxumLayer>,
) -> Res<bool> {
let enforcer = cache_enforcer.get_enforcer();
let mut enforcer_write = enforcer.write().await;
let rule = vec![
"1".to_string(),
"built-in".to_string(),
"/user/users".to_string(),
"GET".to_string(),
];
let _ = enforcer_write.add_policy(rule).await;
Res::new_data(true)
}
pub async fn create_user(
Extension(service): Extension<Arc<SysUserService>>,
ValidatedForm(input): ValidatedForm<CreateUserInput>,
) -> Result<Res<UserWithoutPassword>, AppError> {
service.create_user(input).await.map(Res::new_data)
}
pub async fn get_user(
Path(id): Path<String>,
Extension(service): Extension<Arc<SysUserService>>,
) -> Result<Res<UserWithoutPassword>, AppError> {
service.get_user(&id).await.map(Res::new_data)
}
pub async fn update_user(
Extension(service): Extension<Arc<SysUserService>>,
ValidatedForm(input): ValidatedForm<UpdateUserInput>,
) -> Result<Res<UserWithoutPassword>, AppError> {
service.update_user(input).await.map(Res::new_data)
}
pub async fn delete_user(
Path(id): Path<String>,
Extension(service): Extension<Arc<SysUserService>>,
) -> Result<Res<()>, AppError> {
service.delete_user(&id).await.map(Res::new_data)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/bin/src/main.rs | server/bin/src/main.rs | use std::net::SocketAddr;
use tokio::net::TcpListener;
#[tokio::main]
async fn main() {
let config_path = if cfg!(debug_assertions) {
"server/resources/application-test.yaml"
} else {
"server/resources/application.yaml"
};
server_initialize::initialize_log_tracing().await;
// 使用多实例环境变量优先的配置加载方式
// 支持单个配置项和多实例配置的环境变量覆盖
server_initialize::initialize_config_with_multi_instance_env(config_path, None).await;
let _ = server_initialize::init_xdb().await;
server_initialize::init_primary_connection().await;
server_initialize::init_db_pools().await;
server_initialize::initialize_keys_and_validation().await;
server_initialize::initialize_event_channel().await;
server_initialize::init_primary_redis().await;
server_initialize::init_redis_pools().await;
server_initialize::init_primary_mongo().await;
server_initialize::init_mongo_pools().await;
// build our application with a route
let app = server_initialize::initialize_admin_router().await;
//需要初始化验证器init_validators之后才能初始化访问密钥
server_initialize::initialize_access_key().await;
let addr = match server_initialize::get_server_address().await {
Ok(addr) => addr,
Err(e) => {
eprintln!("Failed to get server address: {}", e);
return;
},
};
// run it
let listener = TcpListener::bind(&addr).await.unwrap();
// tracing::debug!("listening on {}", listener.local_addr().unwrap());
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.await
.unwrap();
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/lib.rs | server/core/src/lib.rs | pub mod sign;
pub mod web;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/sign/memory_nonce_store.rs | server/core/src/sign/memory_nonce_store.rs | use moka::sync::Cache;
use super::api_key::NONCE_TTL_SECS;
/// In-memory store for managing nonces with automatic expiration.
///
/// Uses moka cache to store nonces with a TTL of 10 minutes. Once a nonce
/// expires, it can be reused. This helps prevent replay attacks while
/// maintaining memory efficiency.
#[derive(Clone)]
pub struct MemoryNonceStore {
nonces: Cache<String, ()>,
}
impl MemoryNonceStore {
/// Creates a new instance of MemoryNonceStore with a 10-minute TTL.
#[inline]
pub fn new() -> Self {
Self {
nonces: Cache::builder()
.time_to_live(std::time::Duration::from_secs(NONCE_TTL_SECS))
.build(),
}
}
/// Validates and stores a nonce.
///
/// # Arguments
/// * `nonce` - The nonce string to validate and store
///
/// # Returns
/// * `true` if the nonce is valid and not previously used
/// * `false` if the nonce is invalid or has been used before
#[inline]
pub async fn check_and_set(&self, nonce: &str) -> bool {
if self.nonces.contains_key(nonce) {
false
} else {
self.nonces.insert(nonce.to_string(), ());
true
}
}
}
impl Default for MemoryNonceStore {
#[inline]
fn default() -> Self {
Self::new()
}
}
// Note: This function has been replaced by the one in nonce_store.rs
// We keep it for backward compatibility, but it now just calls the function in nonce_store.rs
/// Creates a factory function for in-memory NonceStore
pub fn create_memory_nonce_store_factory() -> super::nonce_store::NonceStoreFactory {
super::nonce_store::create_memory_store_factory()
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/sign/api_key.rs | server/core/src/sign/api_key.rs | use md5::{Digest, Md5};
use parking_lot::RwLock;
use ring::{digest, hmac};
use std::{
borrow::Cow,
collections::HashMap,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
use crate::sign::nonce_store::{create_memory_store_factory, NonceStore, NonceStoreFactory};
/// Supported signature algorithms for API key validation.
///
/// These algorithms are used to generate and validate signatures for API requests.
/// The algorithms are ordered by performance (fastest to slowest).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum SignatureAlgorithm {
/// MD5 signature algorithm (default, fastest)
Md5,
/// SHA1 signature algorithm
Sha1,
/// SHA256 signature algorithm
Sha256,
/// HMAC-SHA256 signature algorithm (most secure)
HmacSha256,
}
impl Default for SignatureAlgorithm {
#[inline]
fn default() -> Self {
Self::Md5
}
}
/// Configuration for API key validation.
///
/// This struct holds configuration options for the API key validation system.
/// It is designed to be lightweight and efficiently cloneable.
#[derive(Debug, Clone, Copy)]
pub struct ApiKeyConfig {
/// The signature algorithm to use for request validation
pub algorithm: SignatureAlgorithm,
}
impl Default for ApiKeyConfig {
#[inline]
fn default() -> Self {
Self {
algorithm: SignatureAlgorithm::default(),
}
}
}
/// Constants for validation timeouts and expiration.
pub const NONCE_TTL_SECS: u64 = 600; // 10 minutes
pub const TIMESTAMP_DISPARITY_MS: i64 = 300_000; // 5 minutes
/// Capacity hints for collections
const DEFAULT_CAPACITY: usize = 32;
/// Simple API key validator that checks against a set of predefined keys.
///
/// This validator provides basic API key validation by comparing against a set of valid keys.
/// Keys are stored permanently and can only be modified through explicit API calls.
#[derive(Clone)]
pub struct SimpleApiKeyValidator {
keys: Arc<RwLock<HashMap<String, ()>>>,
}
impl SimpleApiKeyValidator {
/// Creates a new SimpleApiKeyValidator with an empty set of valid keys.
#[inline]
pub fn new() -> Self {
Self {
keys: Arc::new(RwLock::new(HashMap::with_capacity(DEFAULT_CAPACITY))),
}
}
/// Validates if an API key is valid.
///
/// # Arguments
/// * `key` - The API key to validate
///
/// # Returns
/// * `true` if the key is valid
/// * `false` if the key is invalid
#[inline]
pub fn validate_key(&self, key: &str) -> bool {
self.keys.read().contains_key(key)
}
/// Adds a new valid API key.
///
/// # Arguments
/// * `key` - The API key to add
#[inline]
pub fn add_key(&self, key: String) {
self.keys.write().insert(key, ());
}
/// Removes an API key from the set of valid keys.
///
/// # Arguments
/// * `key` - The API key to remove
#[inline]
pub fn remove_key(&self, key: &str) {
self.keys.write().remove(key);
}
}
impl Default for SimpleApiKeyValidator {
#[inline]
fn default() -> Self {
Self::new()
}
}
/// Complex API key validator that supports multiple signature algorithms and nonce validation.
///
/// This validator provides advanced API key validation with features including:
/// - Multiple signature algorithms (MD5, SHA1, SHA256, HMAC-SHA256)
/// - Timestamp validation to prevent replay attacks
/// - Nonce validation with automatic expiration
/// - URL parameter signing
///
/// API keys and their corresponding secrets are stored permanently and can only be
/// modified through explicit API calls.
#[derive(Clone)]
pub struct ComplexApiKeyValidator {
secrets: Arc<RwLock<HashMap<String, String>>>,
nonce_store: NonceStore,
nonce_store_factory: NonceStoreFactory,
config: ApiKeyConfig,
}
impl ComplexApiKeyValidator {
/// Creates a new ComplexApiKeyValidator with optional configuration.
///
/// # Arguments
/// * `config` - Optional API key validation configuration. If None, uses default configuration.
#[inline]
pub fn new(config: Option<ApiKeyConfig>) -> Self {
Self::with_nonce_store(config, create_memory_store_factory())
}
/// 创建一个新的 ComplexApiKeyValidator 实例,使用指定的 nonce 存储工厂函数
///
/// # 参数
/// * `config` - 可选的 API 密钥验证配置。如果为 None,则使用默认配置。
/// * `nonce_store_factory` - 用于创建 nonce 存储的工厂函数
#[inline]
pub fn with_nonce_store(
config: Option<ApiKeyConfig>,
nonce_store_factory: NonceStoreFactory,
) -> Self {
Self {
secrets: Arc::new(RwLock::new(HashMap::with_capacity(DEFAULT_CAPACITY))),
nonce_store: (nonce_store_factory)(),
nonce_store_factory,
config: config.unwrap_or_default(),
}
}
/// 获取一个新的 nonce 存储实例
#[inline]
pub fn get_new_nonce_store(&self) -> NonceStore {
(self.nonce_store_factory)()
}
/// Validates if a timestamp is within the allowed 5-minute window.
#[inline]
fn validate_timestamp(&self, timestamp: i64) -> bool {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as i64;
(now - timestamp).abs() < TIMESTAMP_DISPARITY_MS
}
/// Calculates signature for a signing string using the configured algorithm.
///
/// # Arguments
/// * `signing_string` - The string to sign
/// * `secret` - The secret key to use for signing
///
/// # Returns
/// The calculated signature as a hexadecimal string
#[inline]
pub fn calculate_signature(&self, signing_string: &str, secret: &str) -> String {
let signing_string = format!("{}&key={}", signing_string, secret);
match self.config.algorithm {
SignatureAlgorithm::Md5 => {
let mut hasher = Md5::new();
hasher.update(signing_string.as_bytes());
hex::encode(hasher.finalize())
},
SignatureAlgorithm::Sha1 => {
let mut context = digest::Context::new(&digest::SHA1_FOR_LEGACY_USE_ONLY);
context.update(signing_string.as_bytes());
hex::encode(context.finish())
},
SignatureAlgorithm::Sha256 => {
let mut context = digest::Context::new(&digest::SHA256);
context.update(signing_string.as_bytes());
hex::encode(context.finish())
},
SignatureAlgorithm::HmacSha256 => {
let key = hmac::Key::new(hmac::HMAC_SHA256, secret.as_bytes());
let tag = hmac::sign(&key, signing_string.as_bytes());
hex::encode(tag.as_ref())
},
}
}
/// Validates a signed API request.
///
/// # Arguments
/// * `api_key` - The API key to validate
/// * `params` - Vector of key-value pairs representing request parameters
/// * `signature` - The signature to validate
/// * `timestamp` - Request timestamp in milliseconds since UNIX epoch
/// * `nonce` - Unique request identifier to prevent replay attacks
///
/// # Returns
/// * `true` if the request is valid
/// * `false` if any validation check fails
pub fn validate_signature(
&self,
api_key: &str,
params: &[(String, String)],
signature: &str,
timestamp: i64,
nonce: &str,
) -> bool {
if !self.validate_timestamp(timestamp) {
return false;
}
let check_result = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current()
.block_on(async { self.nonce_store.check_and_set(nonce).await })
});
if !check_result {
return false;
}
let secrets_guard = self.secrets.read();
let secret = match secrets_guard.get(api_key) {
Some(s) => Cow::Borrowed(s),
None => return false,
};
// Pre-allocate with capacity to avoid reallocations
let mut sorted_params: Vec<_> = Vec::with_capacity(params.len());
sorted_params.extend_from_slice(params);
sorted_params.sort_unstable_by(|a, b| a.0.cmp(&b.0));
// Pre-calculate total length to avoid reallocations
let total_len = sorted_params.iter().fold(0, |acc, (k, v)| {
acc + k.len() + v.len() + 2 // +2 for '=' and '&'
});
let mut signing_string = String::with_capacity(total_len);
for (i, (k, v)) in sorted_params.iter().enumerate() {
if i > 0 {
signing_string.push('&');
}
signing_string.push_str(k);
signing_string.push('=');
// Only URL encode if necessary
if v.chars().any(|c| !c.is_ascii_alphanumeric()) {
signing_string.push_str(&urlencoding::encode(v));
} else {
signing_string.push_str(v);
}
}
self.calculate_signature(&signing_string, &secret) == signature
}
/// Adds a new API key and its corresponding secret.
///
/// # Arguments
/// * `key` - The API key to add
/// * `secret` - The secret corresponding to the API key
#[inline]
pub fn add_key_secret(&self, key: String, secret: String) {
self.secrets.write().insert(key, secret);
}
/// Removes an API key and its secret.
///
/// # Arguments
/// * `key` - The API key to remove
#[inline]
pub fn remove_key(&self, key: &str) {
self.secrets.write().remove(key);
}
/// Updates the API key validation configuration.
///
/// # Arguments
/// * `config` - New API key validation configuration
#[inline]
pub fn update_config(&mut self, config: ApiKeyConfig) {
self.config = config;
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
#[test]
fn test_simple_api_key_validator() {
let validator = SimpleApiKeyValidator::new();
validator.add_key("test-key".to_string());
assert!(validator.validate_key("test-key"));
assert!(!validator.validate_key("invalid-key"));
}
#[tokio::test]
async fn test_nonce_store() {
use crate::sign::memory_nonce_store::MemoryNonceStore;
let store = MemoryNonceStore::new();
assert!(store.check_and_set("nonce1").await);
assert!(!store.check_and_set("nonce1").await);
tokio::time::sleep(std::time::Duration::from_secs(NONCE_TTL_SECS + 1)).await;
assert!(store.check_and_set("nonce1").await);
}
#[tokio::test(flavor = "multi_thread")]
async fn test_complex_validator() {
let validator = ComplexApiKeyValidator::new(Some(ApiKeyConfig {
algorithm: SignatureAlgorithm::Md5,
}));
validator.add_key_secret("test-key".to_string(), "test-secret".to_string());
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as i64;
let params = vec![
("timestamp".to_string(), now.to_string()),
("nonce".to_string(), "test-nonce".to_string()),
("data".to_string(), "test-data".to_string()),
];
let signing_string = format!("data=test-data&nonce=test-nonce×tamp={}", now);
let signature = validator.calculate_signature(&signing_string, "test-secret");
assert!(validator.validate_signature("test-key", ¶ms, &signature, now, "test-nonce"));
}
#[test]
fn test_concurrent_access() {
let validator = Arc::new(ComplexApiKeyValidator::new(None));
let mut handles = Vec::new();
for i in 0..10 {
let validator = validator.clone();
let handle = thread::spawn(move || {
let key = format!("key{}", i);
let secret = format!("secret{}", i);
validator.add_key_secret(key.clone(), secret.clone());
assert!(validator.secrets.read().contains_key(&key));
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/sign/mod.rs | server/core/src/sign/mod.rs | mod api_key;
mod api_key_middleware;
mod memory_nonce_store;
mod nonce_store;
mod redis_nonce_store;
pub use api_key::{
ApiKeyConfig, ComplexApiKeyValidator, SignatureAlgorithm, SimpleApiKeyValidator,
};
pub use api_key_middleware::{
api_key_middleware, protect_route, ApiKeySource, ApiKeyValidation, ComplexApiKeyConfig,
SimpleApiKeyConfig,
};
pub use memory_nonce_store::{create_memory_nonce_store_factory, MemoryNonceStore};
pub use nonce_store::{NonceStore, NonceStoreFactory};
pub use redis_nonce_store::{create_redis_nonce_store_factory, RedisNonceStore};
use once_cell::sync::Lazy;
use std::sync::Arc;
use tokio::sync::RwLock;
pub enum ValidatorType {
Simple,
Complex,
}
static API_KEY_VALIDATORS: Lazy<(
Arc<RwLock<SimpleApiKeyValidator>>,
Arc<RwLock<ComplexApiKeyValidator>>,
)> = Lazy::new(|| {
(
Arc::new(RwLock::new(SimpleApiKeyValidator::new())),
Arc::new(RwLock::new(ComplexApiKeyValidator::new(None))),
)
});
pub async fn get_simple_validator() -> SimpleApiKeyValidator {
API_KEY_VALIDATORS.0.read().await.clone()
}
pub async fn get_complex_validator() -> ComplexApiKeyValidator {
API_KEY_VALIDATORS.1.read().await.clone()
}
pub async fn add_key(validator_type: ValidatorType, key: &str, secret: Option<&str>) {
match validator_type {
ValidatorType::Simple => {
API_KEY_VALIDATORS.0.write().await.add_key(key.to_string());
},
ValidatorType::Complex => {
if let Some(secret) = secret {
API_KEY_VALIDATORS
.1
.write()
.await
.add_key_secret(key.to_string(), secret.to_string());
}
},
}
}
pub async fn remove_key(validator_type: ValidatorType, key: &str) {
match validator_type {
ValidatorType::Simple => {
API_KEY_VALIDATORS.0.write().await.remove_key(key);
},
ValidatorType::Complex => {
API_KEY_VALIDATORS.1.write().await.remove_key(key);
},
}
}
pub async fn init_validators(config: Option<ApiKeyConfig>) {
// 使用默认的内存 nonce 存储
init_validators_with_nonce_store(config, create_memory_nonce_store_factory()).await;
}
/// 使用指定的 nonce 存储工厂函数初始化验证器
///
/// # 参数
/// * `config` - 可选的 API 密钥验证配置
/// * `nonce_store_factory` - 用于创建 nonce 存储的工厂函数
pub async fn init_validators_with_nonce_store(
config: Option<ApiKeyConfig>,
nonce_store_factory: NonceStoreFactory,
) {
let complex_validator = ComplexApiKeyValidator::with_nonce_store(config, nonce_store_factory);
*API_KEY_VALIDATORS.1.write().await = complex_validator;
}
#[derive(Debug, Clone)]
pub struct ApiKeyEvent {
pub api_key: String,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/sign/api_key_middleware.rs | server/core/src/sign/api_key_middleware.rs | use axum::{
body::Body,
extract::Request,
http::{HeaderMap, StatusCode, Uri},
middleware::Next,
response::IntoResponse,
};
use once_cell::sync::Lazy;
use server_constant::definition::consts::SystemEvent;
use server_global::global;
use std::{collections::HashSet, sync::RwLock};
use crate::web::res::Res;
use super::{ApiKeyEvent, ComplexApiKeyValidator, SimpleApiKeyValidator};
/// Global set of protected paths.
///
/// This set stores the paths that require API key validation.
static PROTECTED_PATHS: Lazy<RwLock<HashSet<String>>> = Lazy::new(|| RwLock::new(HashSet::new()));
/// Source location for API key.
///
/// This enum defines the possible locations where the API key can be found.
#[derive(Clone, Copy, PartialEq)]
pub enum ApiKeySource {
/// From request header.
Header,
/// From query parameter.
Query,
}
/// Configuration for simple API key validation.
///
/// This struct holds the configuration for simple API key validation.
#[derive(Clone)]
pub struct SimpleApiKeyConfig {
/// Source location of API key.
pub source: ApiKeySource,
/// Name of API key parameter.
pub key_name: String,
}
impl Default for SimpleApiKeyConfig {
fn default() -> Self {
Self {
source: ApiKeySource::Header,
key_name: "x-api-key".to_string(),
}
}
}
/// Configuration for complex API key validation with signature.
///
/// This struct holds the configuration for complex API key validation with signature.
#[derive(Clone)]
pub struct ComplexApiKeyConfig {
/// Access key ID parameter name.
pub key_name: String,
/// Timestamp parameter name.
pub timestamp_name: String,
/// Nonce parameter name.
pub nonce_name: String,
/// Signature parameter name.
pub signature_name: String,
}
impl Default for ComplexApiKeyConfig {
fn default() -> Self {
Self {
key_name: "AccessKeyId".to_string(),
timestamp_name: "timestamp".to_string(),
nonce_name: "nonce".to_string(),
signature_name: "signature".to_string(),
}
}
}
/// API key validation strategy.
///
/// This enum defines the possible API key validation strategies.
#[derive(Clone)]
pub enum ApiKeyValidation {
/// Simple API key validation.
Simple(SimpleApiKeyValidator, SimpleApiKeyConfig),
/// Complex API key validation with signature.
Complex(ComplexApiKeyValidator, ComplexApiKeyConfig),
}
/// Add a path to protected routes requiring API key validation.
///
/// This function adds a path to the set of protected paths.
#[allow(dead_code)]
pub fn protect_route(path: &str) {
if let Ok(mut paths) = PROTECTED_PATHS.write() {
paths.insert(path.to_string());
}
}
/// Check if URI path requires API key validation.
///
/// This function checks if the given URI path is in the set of protected paths.
#[inline]
fn is_protected_path(uri: &Uri) -> bool {
if let Ok(paths) = PROTECTED_PATHS.read() {
let path = uri.path();
paths.contains(path.strip_suffix('/').unwrap_or(path))
} else {
false
}
}
/// API key validation middleware.
///
/// This middleware checks if the API key is valid for the given request.
#[inline]
pub async fn api_key_middleware(
validator: ApiKeyValidation,
req: Request<Body>,
next: Next,
) -> impl IntoResponse {
if !is_protected_path(req.uri()) {
return next.run(req).await.into_response();
}
match validate_request(&validator, &req) {
Ok(true) => next.run(req).await.into_response(),
Ok(false) => Res::<()>::new_error(
StatusCode::UNAUTHORIZED.as_u16(),
"Invalid API key or signature",
)
.into_response(),
Err(e) => Res::<()>::new_error(StatusCode::BAD_REQUEST.as_u16(), e).into_response(),
}
}
/// Get value from request headers.
///
/// This function retrieves the value of a header from the request headers.
#[inline]
fn get_header_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
headers.get(name).and_then(|v| v.to_str().ok())
}
/// Get value from query parameters.
///
/// This function retrieves the value of a query parameter from the request query.
#[inline]
fn get_query_value<'a>(params: &'a [(String, String)], name: &str) -> Option<&'a str> {
params
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
}
/// Validate API key in request.
///
/// This function validates the API key in the given request.
#[inline]
fn validate_request(
validator: &ApiKeyValidation,
req: &Request<Body>,
) -> Result<bool, &'static str> {
let headers = req.headers();
let query = req.uri().query().unwrap_or("");
let params = if !query.is_empty() {
parse_query(query)
} else {
Vec::new()
};
match validator {
ApiKeyValidation::Simple(validator, config) => {
let api_key = match config.source {
ApiKeySource::Header => get_header_value(headers, &config.key_name),
ApiKeySource::Query => get_query_value(¶ms, &config.key_name),
}
.ok_or("Missing API key")?;
global::send_dyn_event(
SystemEvent::AuthApiKeyValidatedEvent.as_ref(),
Box::new(ApiKeyEvent {
api_key: api_key.to_owned(),
}),
);
Ok(validator.validate_key(api_key))
},
ApiKeyValidation::Complex(validator, config) => {
let api_key =
get_query_value(¶ms, &config.key_name).ok_or("Missing AccessKeyId")?;
let timestamp = get_query_value(¶ms, &config.timestamp_name)
.ok_or("Missing timestamp")?
.parse::<i64>()
.map_err(|_| "Invalid timestamp")?;
let nonce = get_query_value(¶ms, &config.nonce_name).ok_or("Missing nonce")?;
let signature =
get_query_value(¶ms, &config.signature_name).ok_or("Missing signature")?;
let params_for_signing: Vec<(String, String)> = params
.iter()
.filter(|(k, _)| k != &config.signature_name)
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
global::send_dyn_event(
SystemEvent::AuthApiKeyValidatedEvent.as_ref(),
Box::new(ApiKeyEvent {
api_key: api_key.to_owned(),
}),
);
Ok(validator.validate_signature(
api_key,
¶ms_for_signing,
signature,
timestamp,
nonce,
))
},
}
}
/// Parse query string into key-value pairs.
///
/// This function parses a query string into a vector of key-value pairs.
#[inline]
fn parse_query(query: &str) -> Vec<(String, String)> {
let capacity = query.matches('&').count() + 1;
let mut params = Vec::with_capacity(capacity);
for pair in query.split('&') {
if let Some((k, v)) = pair.split_once('=') {
if !k.is_empty() && !v.is_empty() {
params.push((k.to_string(), v.to_string()));
}
}
}
params
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
#[test]
fn test_api_key_sign() {
let validator = ComplexApiKeyValidator::new(None);
validator.add_key_secret("test-access-key".to_string(), "test-secret-key".to_string());
let timestamp = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as i64;
let nonce = format!("nonce_{}", timestamp);
let mut params = vec![
("AccessKeyId".to_string(), "test-access-key".to_string()),
("param1".to_string(), "value1".to_string()),
("param2".to_string(), "value2".to_string()),
("t".to_string(), timestamp.to_string()),
("n".to_string(), nonce.clone()),
];
params.sort_by(|a, b| a.0.cmp(&b.0));
let signing_string = params
.iter()
.map(|(k, v)| format!("{}={}", k, v))
.collect::<Vec<_>>()
.join("&");
let signature = validator.calculate_signature(&signing_string, "test-secret-key");
println!(
"URL with signature: /api/url?{}&sign={}",
signing_string, signature
);
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/sign/nonce_store.rs | server/core/src/sign/nonce_store.rs | use std::sync::Arc;
/// Nonce storage enum that supports different storage implementations
#[derive(Clone)]
pub enum NonceStore {
/// In-memory storage implementation
Memory(Arc<crate::sign::memory_nonce_store::MemoryNonceStore>),
/// Redis storage implementation
Redis(Arc<crate::sign::redis_nonce_store::RedisNonceStore>),
}
impl NonceStore {
/// Checks and sets a nonce
///
/// # Arguments
/// * `nonce` - The nonce string to validate and store
///
/// # Returns
/// * `true` - If the nonce is valid and has not been used before
/// * `false` - If the nonce is invalid or has been used before
pub async fn check_and_set(&self, nonce: &str) -> bool {
match self {
NonceStore::Memory(store) => store.check_and_set(nonce).await,
NonceStore::Redis(store) => store.check_and_set(nonce).await,
}
}
}
/// Factory function type for creating NonceStore instances
pub type NonceStoreFactory = Arc<dyn Fn() -> NonceStore + Send + Sync>;
/// Creates an in-memory version of NonceStore
pub fn create_memory_store() -> NonceStore {
NonceStore::Memory(Arc::new(
crate::sign::memory_nonce_store::MemoryNonceStore::new(),
))
}
/// Creates a Redis version of NonceStore
pub fn create_redis_store(prefix: impl Into<String>) -> NonceStore {
NonceStore::Redis(Arc::new(
crate::sign::redis_nonce_store::RedisNonceStore::new(prefix),
))
}
/// Creates a factory function for in-memory NonceStore
pub fn create_memory_store_factory() -> NonceStoreFactory {
Arc::new(|| create_memory_store())
}
/// Creates a factory function for Redis NonceStore
pub fn create_redis_store_factory(
prefix: impl Into<String> + Clone + Send + Sync + 'static,
) -> NonceStoreFactory {
let prefix = prefix.into();
Arc::new(move || create_redis_store(prefix.clone()))
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/sign/redis_nonce_store.rs | server/core/src/sign/redis_nonce_store.rs | use server_global::global::RedisConnection;
use super::api_key::NONCE_TTL_SECS;
/// Redis implementation of Nonce storage
#[derive(Clone)]
pub struct RedisNonceStore {
/// Redis key prefix
prefix: String,
}
impl RedisNonceStore {
/// Creates a new RedisNonceStore instance
#[inline]
pub fn new(prefix: impl Into<String>) -> Self {
Self {
prefix: prefix.into(),
}
}
/// Gets the complete Redis key name
fn get_key(&self, nonce: &str) -> String {
format!("{}_nonce:{}", self.prefix, nonce)
}
}
impl Default for RedisNonceStore {
#[inline]
fn default() -> Self {
Self::new("api_key")
}
}
impl RedisNonceStore {
pub async fn check_and_set(&self, nonce: &str) -> bool {
let redis_connection = match server_global::global::GLOBAL_PRIMARY_REDIS
.read()
.await
.clone()
{
Some(conn) => conn,
None => return false,
};
let key = self.get_key(nonce);
match redis_connection {
RedisConnection::Single(client) => {
if let Ok(mut conn) = client.get_multiplexed_async_connection().await {
let result: Option<bool> = redis::cmd("SET")
.arg(&key)
.arg("1")
.arg("NX")
.arg("EX")
.arg(NONCE_TTL_SECS)
.query_async(&mut conn)
.await
.ok();
result.unwrap_or(false)
} else {
false
}
},
RedisConnection::Cluster(client) => {
if let Ok(mut conn) = client.get_async_connection().await {
let result: Option<bool> = redis::cmd("SET")
.arg(&key)
.arg("1")
.arg("NX")
.arg("EX")
.arg(NONCE_TTL_SECS)
.query_async(&mut conn)
.await
.ok();
result.unwrap_or(false)
} else {
false
}
},
}
}
}
// Note: This function has been replaced by the one in nonce_store.rs
// We keep it for backward compatibility, but it now just calls the function in nonce_store.rs
/// Creates a factory function for Redis NonceStore
pub fn create_redis_nonce_store_factory(
prefix: impl Into<String> + Clone + Send + Sync + 'static,
) -> super::nonce_store::NonceStoreFactory {
super::nonce_store::create_redis_store_factory(prefix)
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/page.rs | server/core/src/web/page.rs | use serde::{de::Error as DeError, Deserialize, Deserializer, Serialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct PageRequest {
#[serde(
default = "default_current",
deserialize_with = "deserialize_u64_from_string"
)]
pub current: u64,
#[serde(
default = "default_size",
deserialize_with = "deserialize_u64_from_string"
)]
pub size: u64,
}
fn deserialize_u64_from_string<'de, D>(deserializer: D) -> Result<u64, D::Error>
where
D: Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
s.parse::<u64>().map_err(DeError::custom)
}
fn default_current() -> u64 {
1
}
fn default_size() -> u64 {
10
}
impl Default for PageRequest {
fn default() -> Self {
Self {
current: default_current(),
size: default_size(),
}
}
}
#[derive(Debug, Serialize, Default)]
pub struct PaginatedData<T> {
pub current: u64,
pub size: u64,
pub total: u64,
pub records: Vec<T>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/jwt.rs | server/core/src/web/jwt.rs | use std::{error::Error, fmt};
use chrono::{Duration, Utc};
use jsonwebtoken::{decode, encode, Header, TokenData};
use server_config::JwtConfig;
use server_global::global;
use ulid::Ulid;
use crate::web::auth::Claims;
// pub static KEYS: Lazy<Arc<Mutex<Keys>>> = Lazy::new(|| {
// let config = global::get_config::<JwtConfig>()
// .expect("[soybean-admin-rust] >>>>>> [server-core] Failed to load JWT
// config"); Arc::new(Mutex::new(Keys::new(config.jwt_secret.as_bytes())))
// });
//
// pub static VALIDATION: Lazy<Arc<Mutex<Validation>>> = Lazy::new(|| {
// let config = global::get_config::<JwtConfig>()
// .expect("[soybean-admin-rust] >>>>>> [server-core] Failed to load JWT
// config"); let mut validation = Validation::default();
// validation.leeway = 60;
// validation.set_issuer(&[config.issuer.clone()]);
// Arc::new(Mutex::new(validation))
// });
#[derive(Debug)]
pub enum JwtError {
KeysNotInitialized,
ValidationNotInitialized,
TokenCreationError(String),
TokenValidationError(String),
}
impl fmt::Display for JwtError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
JwtError::KeysNotInitialized => write!(f, "Keys not initialized"),
JwtError::ValidationNotInitialized => write!(f, "Validation not initialized"),
JwtError::TokenCreationError(err) => write!(f, "Token creation error: {}", err),
JwtError::TokenValidationError(err) => write!(f, "Token validation error: {}", err),
}
}
}
impl Error for JwtError {}
pub struct JwtUtils;
impl JwtUtils {
pub async fn generate_token(claims: &Claims) -> Result<String, JwtError> {
let keys_arc = global::KEYS.get().ok_or(JwtError::KeysNotInitialized)?;
let keys = keys_arc.lock().await;
let mut claims_clone = claims.clone();
let now = Utc::now();
let timestamp = now.timestamp() as usize;
let jwt_config = global::get_config::<JwtConfig>().await.unwrap();
claims_clone.set_exp((now + Duration::seconds(jwt_config.expire)).timestamp() as usize);
claims_clone.set_iss(jwt_config.issuer.to_string());
claims_clone.set_iat(timestamp);
claims_clone.set_nbf(timestamp);
claims_clone.set_jti(Ulid::new().to_string());
let token = encode(&Header::default(), &claims_clone, &keys.encoding)
.map_err(|e| JwtError::TokenCreationError(e.to_string()));
if let Ok(ref tok) = token {
global::send_string_event(tok.clone());
}
token
}
pub async fn validate_token(
token: &str,
audience: &str,
) -> Result<TokenData<Claims>, JwtError> {
let keys_arc = global::KEYS.get().ok_or(JwtError::KeysNotInitialized)?;
let keys = keys_arc.lock().await;
let validation_arc = global::VALIDATION
.get()
.ok_or(JwtError::ValidationNotInitialized)?;
let validation = validation_arc.lock().await;
let mut validation_clone = validation.clone();
validation_clone.set_audience(&[audience.to_string()]);
decode::<Claims>(token, &keys.decoding, &validation_clone)
.map_err(|e| JwtError::TokenValidationError(e.to_string()))
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/request_id.rs | server/core/src/web/request_id.rs | use std::{
fmt,
task::{Context, Poll},
};
use http::Request;
use tower_layer::Layer;
use tower_service::Service;
use ulid::Ulid;
#[derive(Debug, Clone)]
pub struct RequestId(pub Ulid);
impl RequestId {
fn new() -> Self {
Self(Ulid::new())
}
}
impl fmt::Display for RequestId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(f, "{}", self.0.to_string())
}
}
#[derive(Clone, Debug)]
pub struct RequestIdService<S> {
inner: S,
}
impl<S> RequestIdService<S> {
pub fn new(inner: S) -> Self {
Self { inner }
}
}
impl<B, S> Service<Request<B>> for RequestIdService<S>
where
S: Service<Request<B>>,
{
type Error = S::Error;
type Future = S::Future;
type Response = S::Response;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut req: Request<B>) -> Self::Future {
let id = RequestId::new();
req.extensions_mut().insert(id);
self.inner.call(req)
}
}
#[derive(Clone, Debug)]
pub struct RequestIdLayer;
impl<S> Layer<S> for RequestIdLayer {
type Service = RequestIdService<S>;
fn layer(&self, inner: S) -> Self::Service {
RequestIdService { inner }
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/error.rs | server/core/src/web/error.rs | use axum::response::{IntoResponse, Response};
use mongodb::error::{Error as MongoError, ErrorKind};
use redis::RedisError;
use sea_orm::DbErr;
use crate::web::{jwt::JwtError, res::Res};
pub trait ApiError {
fn code(&self) -> u16;
fn message(&self) -> String;
}
#[derive(Debug)]
pub struct AppError {
pub code: u16,
pub message: String,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
Res::<()>::new_error(self.code, self.message.as_str()).into_response()
}
}
impl ApiError for AppError {
fn code(&self) -> u16 {
self.code
}
fn message(&self) -> String {
self.message.to_string()
}
}
impl ApiError for DbErr {
fn code(&self) -> u16 {
match self {
DbErr::ConnectionAcquire(_) => 503, // 服务不可用
DbErr::TryIntoErr { .. } => 400, // 请求参数错误
DbErr::Conn(_) => 500, // 服务器内部错误
DbErr::Exec(_) => 500, // 执行错误
DbErr::Query(_) => 500, // 查询错误
DbErr::ConvertFromU64(_) => 400, // 请求参数错误
DbErr::UnpackInsertId => 500, // 服务器内部错误
DbErr::UpdateGetPrimaryKey => 500, // 更新错误
DbErr::RecordNotFound(_) => 404, // 未找到记录
DbErr::AttrNotSet(_) => 400, // 请求参数错误
DbErr::Custom(_) => 500, // 自定义错误
DbErr::Type(_) => 400, // 类型错误
DbErr::Json(_) => 400, // JSON解析错误
DbErr::Migration(_) => 500, // 迁移错误
DbErr::RecordNotInserted => 400, // 记录未插入
DbErr::RecordNotUpdated => 404, // 记录未更新
}
}
fn message(&self) -> String {
format!("{}", self)
}
}
impl From<DbErr> for AppError {
fn from(err: DbErr) -> Self {
AppError {
code: err.code(),
message: err.message(),
}
}
}
impl From<JwtError> for AppError {
fn from(err: JwtError) -> Self {
AppError {
code: 400,
message: err.to_string(),
}
}
}
impl From<RedisError> for AppError {
fn from(err: RedisError) -> Self {
use redis::ErrorKind;
let code = match err.kind() {
ErrorKind::ResponseError => 500, // Redis响应错误
ErrorKind::AuthenticationFailed => 401, // 认证失败
ErrorKind::TypeError => 400, // 类型错误
ErrorKind::ExecAbortError => 500, // 执行中止
ErrorKind::BusyLoadingError => 503, // Redis正在加载
ErrorKind::InvalidClientConfig => 400, // 客户端配置错误
ErrorKind::IoError => 503, // IO错误,可能是网络问题
ErrorKind::ExtensionError => 500, // 扩展错误
_ => 500, // 其他错误
};
let message = if let Some(redis_code) = err.code() {
format!("[{}] {}", redis_code, err)
} else {
format!("{}", err)
};
AppError { code, message }
}
}
impl From<MongoError> for AppError {
fn from(err: MongoError) -> Self {
let code = match *err.kind {
ErrorKind::Authentication { .. } => 401, // 认证错误
ErrorKind::InvalidArgument { .. } => 400, // 参数错误
ErrorKind::DnsResolve { .. } => 503, // DNS解析错误
ErrorKind::ConnectionPoolCleared { .. } => 503, // 连接池错误
ErrorKind::Io(_) => 503, // IO错误
ErrorKind::Command(_) => 400, // 命令执行错误
ErrorKind::Write(_) => 500, // 写入错误
ErrorKind::ServerSelection { .. } => 503, // 服务器选择错误
ErrorKind::Transaction { .. } => 500, // 事务错误
ErrorKind::Internal { .. } => 500, // 内部错误
ErrorKind::BsonDeserialization(_) => 400, // BSON反序列化错误
ErrorKind::BsonSerialization(_) => 400, // BSON序列化错误
ErrorKind::InvalidResponse { .. } => 500, // 无效响应
ErrorKind::IncompatibleServer { .. } => 503, // 服务器不兼容
ErrorKind::SessionsNotSupported => 503, // 不支持会话
ErrorKind::InvalidTlsConfig { .. } => 500, // TLS配置错误
ErrorKind::MissingResumeToken => 500, // 缺少恢复令牌
ErrorKind::GridFs(_) => 500, // GridFS错误
ErrorKind::Custom(_) => 500, // 自定义错误
ErrorKind::Shutdown => 503, // 关闭错误
_ => 500, // 其他未知错误
};
AppError {
code,
message: err.to_string(),
}
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/operation_log.rs | server/core/src/web/operation_log.rs | use std::{
collections::HashMap,
convert::Infallible,
net::SocketAddr,
task::{Context, Poll},
};
use axum::{
body::{to_bytes, Body, Bytes},
extract::{ConnectInfo, Request},
response::Response,
Extension,
};
use bytes::BytesMut;
use chrono::Local;
use futures::{future::BoxFuture, StreamExt};
use http::{Extensions, HeaderMap, Uri};
use serde_json::Value;
use server_constant::definition::consts::SystemEvent;
use server_global::global::{self, OperationLogContext};
use tower_layer::Layer;
use tower_service::Service;
use super::{auth::User, RequestId};
const USER_AGENT_HEADER: &str = "user-agent";
const UNKNOWN_REQUEST_ID: &str = "unknown";
const DEFAULT_BODY_CAPACITY: usize = 1024 * 16; // 16KB 默认缓冲区大小
#[derive(Clone)]
pub struct OperationLogLayer {
pub enabled: bool,
}
impl OperationLogLayer {
pub fn new(enabled: bool) -> Self {
Self { enabled }
}
}
impl<S> Layer<S> for OperationLogLayer
where
S: Service<Request<Body>, Response = Response<Body>, Error = Infallible>
+ Send
+ Clone
+ 'static,
{
type Service = OperationLogMiddleware<S>;
fn layer(&self, service: S) -> Self::Service {
OperationLogMiddleware {
inner: service,
enabled: self.enabled,
}
}
}
#[derive(Clone)]
pub struct OperationLogMiddleware<S> {
inner: S,
enabled: bool,
}
impl<S> Service<Request<Body>> for OperationLogMiddleware<S>
where
S: Service<Request<Body>, Response = Response<Body>, Error = Infallible>
+ Send
+ Clone
+ 'static,
S::Future: Send + 'static,
{
type Error = Infallible;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
type Response = Response<Body>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
if !self.enabled {
let mut inner = self.inner.clone();
return Box::pin(async move { inner.call(req).await });
}
let mut inner = self.inner.clone();
Box::pin(async move {
let start_time = Local::now().naive_local();
let (parts, body) = req.into_parts();
let headers = &parts.headers;
let extensions = &parts.extensions;
let (user_id, username, domain) = get_user_info(extensions);
let request_id = extensions
.get::<RequestId>()
.map(ToString::to_string)
.unwrap_or_else(|| UNKNOWN_REQUEST_ID.to_string());
if let Ok(bytes) = buffer_body(body).await {
let method = parts.method.to_string();
let uri = parts.uri.to_string();
let ip = get_client_ip(extensions, headers);
let user_agent = get_user_agent(headers);
let params = parse_query_params(&parts.uri);
let req = Request::from_parts(parts, Body::from(bytes.clone()));
let response = inner.call(req).await?;
let (response_parts, response_body) = response.into_parts();
let response_bytes = to_bytes(response_body, usize::MAX)
.await
.unwrap_or_default();
let end_time = Local::now().naive_local();
let duration = (end_time - start_time).num_milliseconds() as i32;
let context = OperationLogContext {
user_id,
username,
domain,
module_name: "TODO".to_string(),
description: "TODO".to_string(),
request_id,
method,
url: uri,
ip,
user_agent,
params,
body: (!bytes.is_empty())
.then(|| serde_json::from_slice(&bytes).ok())
.flatten(),
response: serde_json::from_slice(&response_bytes).ok(),
start_time,
end_time,
duration,
created_at: start_time,
};
global::send_dyn_event(
SystemEvent::AuditOperationLoggedEvent.as_ref(),
Box::new(context),
);
Ok(Response::from_parts(
response_parts,
Body::from(response_bytes),
))
} else {
let mut inner = inner;
inner.call(Request::from_parts(parts, Body::empty())).await
}
})
}
}
/// 缓冲请求体,带容量限制
///
/// # 参数
/// * `body` - 请求体,类型为 axum 的 Body
///
/// # 返回值
/// * `Result<Bytes, Box<dyn std::error::Error + Send + Sync>>` -
/// 成功返回缓冲的字节数据,失败返回错误
///
/// # 错误
/// * 当请求体大小超过 MAX_SIZE (32KB) 时返回错误
/// * 当读取请求体流失败时返回错误
#[inline]
async fn buffer_body(body: Body) -> Result<Bytes, Box<dyn std::error::Error + Send + Sync>> {
const MAX_SIZE: usize = DEFAULT_BODY_CAPACITY * 2;
let mut bytes = BytesMut::with_capacity(DEFAULT_BODY_CAPACITY);
let mut stream = body.into_data_stream();
while let Some(chunk) = stream.next().await {
let chunk = chunk?;
if bytes.len() + chunk.len() > MAX_SIZE {
return Err("Request body too large".into());
}
bytes.extend_from_slice(&chunk);
}
Ok(bytes.freeze())
}
/// 从请求头获取用户代理
///
/// # 参数
/// * `headers` - HTTP 请求头映射
///
/// # 返回值
/// * `Option<String>` - 成功返回用户代理字符串,未找到或解析失败返回 None
#[inline(always)]
fn get_user_agent(headers: &HeaderMap) -> Option<String> {
headers
.get(USER_AGENT_HEADER)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
}
/// 获取客户端 IP,优先从扩展中获取
///
/// # 参数
/// * `extensions` - 请求扩展
/// * `headers` - HTTP 请求头映射
///
/// # 返回值
/// * `String` - 客户端 IP 地址字符串
#[inline(always)]
fn get_client_ip(extensions: &Extensions, headers: &HeaderMap) -> String {
use std::net::IpAddr;
if let Some(Extension(ConnectInfo(addr))) =
extensions.get::<Extension<ConnectInfo<SocketAddr>>>()
{
return match addr.ip() {
IpAddr::V4(ip) => ip.to_string(),
IpAddr::V6(ip) => ip.to_string(),
};
}
super::util::ClientIp::get_real_ip(headers)
}
/// 从扩展中获取用户信息元组
///
/// # 参数
/// * `extensions` - 请求扩展
///
/// # 返回值
/// * `(Option<String>, Option<String>, Option<String>)` - (用户ID, 用户名,
/// 域名) 的元组
#[inline(always)]
fn get_user_info(extensions: &Extensions) -> (Option<String>, Option<String>, Option<String>) {
let Some(user) = extensions.get::<User>() else {
return Default::default();
};
(
Some(user.user_id()),
Some(user.username()),
Some(user.domain()),
)
}
/// 解析 URI 查询参数为 JSON 值
///
/// # 参数
/// * `uri` - HTTP 请求 URI
///
/// # 返回值
/// * `Option<Value>` - 成功返回解析后的 JSON 值,失败返回 None
#[inline(always)]
fn parse_query_params(uri: &Uri) -> Option<Value> {
let query = uri.query()?;
if query.is_empty() {
return Some(Value::Object(Default::default()));
}
let capacity = query.matches('&').count() + 1;
let mut params = HashMap::with_capacity(capacity);
form_urlencoded::parse(query.as_bytes())
.into_owned()
.for_each(|(k, v)| {
params.insert(k, v);
});
serde_json::to_value(params).ok()
}
#[cfg(test)]
mod tests {
use std::convert::Infallible;
use axum::{
body::{Body, HttpBody},
http::{Method, Request, StatusCode},
};
use serde_json::json;
use super::*;
use crate::web::auth::{Claims, User};
/// 创建测试用户
fn create_test_user() -> User {
let claims = Claims::new(
"test-user".to_string(),
"test-aud".to_string(),
"test".to_string(),
vec!["admin".to_string()],
"test-domain".to_string(),
None,
);
User::from(claims)
}
/// 创建测试请求
fn create_request(method: Method, uri: &str, body: Option<Value>) -> Request<Body> {
let mut builder = Request::builder()
.method(method)
.uri(uri)
.header("user-agent", "test-agent")
.header("X-Real-IP", "192.168.1.1")
.extension(create_test_user());
if body.is_some() {
builder = builder.header("content-type", "application/json");
}
builder
.body(match body {
Some(json) => Body::from(serde_json::to_vec(&json).unwrap()),
None => Body::empty(),
})
.unwrap()
}
/// 验证上下文
async fn assert_context(method: &str, uri: &str, params: Option<Value>, body: Option<Value>) {
let ctx = OperationLogContext::get()
.await
.expect("Context should exist");
println!("验证上下文: {} {}", method, uri);
println!("参数: {:?}", params);
println!("请求体: {:?}", body);
assert_eq!(ctx.method, method);
assert_eq!(ctx.url, uri);
assert_eq!(ctx.params, params);
assert_eq!(ctx.body, body);
assert_eq!(ctx.user_agent, Some("test-agent".to_string()));
assert_eq!(ctx.ip, "192.168.1.1");
assert_eq!(ctx.user_id, Some("test-user".to_string()));
}
#[tokio::test]
async fn test_operation_log_completeness() {
let test_cases = vec![
// 基础场景
(Method::GET, "/test", None, None),
(
Method::GET,
"/test?key=value",
Some(json!({"key": "value"})),
None,
),
(Method::POST, "/test", None, Some(json!({"data": "test"}))),
// 边界场景
(Method::GET, "/test?", Some(json!({})), None), // 空查询参数
(Method::POST, "/test", None, Some(json!({}))), // 空请求体
// 复杂场景
(
Method::POST,
"/test?a=1&b=2",
Some(json!({"a": "1", "b": "2"})),
Some(json!({"nested": {"data": "test"}})),
),
// 特殊字符场景
(
Method::GET,
"/test?key=hello%20world",
Some(json!({"key": "hello world"})),
None,
),
// 其他 HTTP 方法
(
Method::PUT,
"/test?type=update",
Some(json!({"type": "update"})),
Some(json!({"status": "done"})),
),
(Method::DELETE, "/test/123", None, None),
(Method::PATCH, "/test", None, Some(json!({"op": "replace"}))),
// 大小写混合场景
(
Method::GET,
"/TEST?Key=Value",
Some(json!({"Key": "Value"})),
None,
),
];
let service = tower::service_fn(|_req: Request<Body>| async move {
Ok::<_, Infallible>(Response::new(Body::from("ok")))
});
for (method, uri, params, body) in test_cases {
OperationLogContext::clear().await;
println!("\n▶ 测试场景: {} {}", method, uri);
if let Some(p) = ¶ms {
println!(" 查询参数: {}", p);
}
if let Some(b) = &body {
println!(" 请求体: {}", b);
}
let mut middleware = OperationLogMiddleware {
inner: service.clone(),
enabled: true,
};
let request = create_request(method.clone(), uri, body.clone());
let _ = middleware.call(request).await.unwrap();
assert_context(&method.to_string(), uri, params, body).await;
}
}
#[tokio::test]
async fn test_operation_log_error_cases() {
println!("\n=== Testing Error Cases ===");
let service = tower::service_fn(|req: Request<Body>| async move {
// 检查请求体大小
let content_length = req
.headers()
.get("content-length")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<usize>().ok())
.unwrap_or(0);
if content_length > DEFAULT_BODY_CAPACITY * 2 {
Ok(Response::builder()
.status(StatusCode::BAD_REQUEST)
.body(Body::from("Request body too large"))
.unwrap())
} else {
Ok(Response::new(Body::from("ok")))
}
});
let test_cases = vec![(
Method::POST,
"/test",
Some(json!({
"large": "x".repeat(DEFAULT_BODY_CAPACITY * 3)
})),
StatusCode::BAD_REQUEST,
)];
for (method, uri, body, expected_status) in test_cases {
println!("\n▶ 测试错误场景: {:?}", expected_status);
let mut middleware = OperationLogMiddleware {
inner: service.clone(),
enabled: true,
};
let mut request = create_request(method, uri, body);
// 添加 content-length 头
if let Some(body) = request.body().size_hint().upper() {
request
.headers_mut()
.insert("content-length", body.to_string().parse().unwrap());
}
let response = middleware.call(request).await.unwrap();
assert_eq!(response.status(), expected_status);
}
}
#[tokio::test]
async fn test_disabled_middleware() {
println!("\n=== Testing Disabled Middleware ===");
OperationLogContext::clear().await;
let service = tower::service_fn(|_req: Request<Body>| async move {
Ok::<_, Infallible>(Response::new(Body::from("ok")))
});
let mut middleware = OperationLogMiddleware {
inner: service,
enabled: false,
};
let request = create_request(Method::POST, "/test", Some(json!({"test": true})));
let response = middleware.call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert!(OperationLogContext::get().await.is_none());
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/util.rs | server/core/src/web/util.rs | use axum::http::HeaderMap;
/// 客户端 IP 地址处理工具
///
/// 用于从 HTTP 请求头中获取真实的客户端 IP 地址。
/// 支持多种代理服务器和 CDN 的请求头格式。
pub struct ClientIp;
impl ClientIp {
/// 从请求头中获取真实的客户端 IP 地址
///
/// # 参数
/// * `headers` - HTTP 请求头
///
/// # 返回值
/// 返回客户端 IP 地址字符串,如果无法获取则返回 "unknown"
///
/// # 示例
/// ```
/// use axum::http::HeaderMap;
/// use server_core::web::util::ClientIp;
///
/// let mut headers = HeaderMap::new();
/// headers.insert("X-Real-IP", "192.168.1.1".parse().unwrap());
///
/// let ip = ClientIp::get_real_ip(&headers);
/// assert_ne!(ip, "unknown");
/// ```
pub fn get_real_ip(headers: &HeaderMap) -> String {
// 按优先级检查请求头
// 不同的代理服务器和 CDN 可能使用不同的请求头来传递客户端 IP
let ip_headers = [
"X-Real-IP", // Nginx 代理
"X-Forwarded-For", // 标准代理头
"CF-Connecting-IP", // Cloudflare
"True-Client-IP", // Akamai 和 Cloudflare
"X-Client-IP", // 常用代理头
"Fastly-Client-IP", // Fastly CDN
"X-Cluster-Client-IP", // GCP/AWS Load Balancer
"X-Original-Forwarded-For", // AWS ALB/ELB
];
// 遍历所有可能的请求头
for header_name in ip_headers {
if let Some(ip_header) = headers.get(header_name) {
if let Ok(ip_str) = ip_header.to_str() {
// X-Forwarded-For 等头可能包含多个 IP,格式如:client, proxy1, proxy2
// 我们取第一个,因为它通常是最原始的客户端 IP
let real_ip = ip_str.split(',').next().unwrap_or("").trim();
if !real_ip.is_empty() {
return real_ip.to_string();
}
}
}
}
// 如果没有找到任何有效的 IP,返回 unknown
"unknown".to_string()
}
/// 检查 IP 地址是否有效
///
/// # 参数
/// * `ip` - IP 地址字符串
///
/// # 返回值
/// 如果 IP 地址有效则返回 true,否则返回 false
pub fn is_valid_ip(ip: &str) -> bool {
if ip == "unknown" {
return false;
}
// 简单的 IPv4 验证
ip.split('.')
.filter_map(|octet| octet.parse::<u8>().ok())
.count()
== 4
}
/// 获取请求头中的所有 IP 相关信息
///
/// # 参数
/// * `headers` - HTTP 请求头
///
/// # 返回值
/// 返回一个包含所有 IP 相关请求头信息的 Vec
pub fn get_all_ip_headers(headers: &HeaderMap) -> Vec<(String, String)> {
let ip_headers = [
"X-Real-IP",
"X-Forwarded-For",
"CF-Connecting-IP",
"True-Client-IP",
"X-Client-IP",
"Fastly-Client-IP",
"X-Cluster-Client-IP",
"X-Original-Forwarded-For",
];
ip_headers
.iter()
.filter_map(|&header_name| {
headers.get(header_name).and_then(|value| {
value
.to_str()
.ok()
.map(|v| (header_name.to_string(), v.to_string()))
})
})
.collect()
}
/// 从 X-Forwarded-For 头中获取代理链路
///
/// # 参数
/// * `headers` - HTTP 请求头
///
/// # 返回值
/// 返回代理链路中的所有 IP 地址,如果没有则返回空 Vec
pub fn get_proxy_chain(headers: &HeaderMap) -> Vec<String> {
headers
.get("X-Forwarded-For")
.and_then(|h| h.to_str().ok())
.map(|ip_str| ip_str.split(',').map(|ip| ip.trim().to_string()).collect())
.unwrap_or_default()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_real_ip() {
let mut headers = HeaderMap::new();
headers.insert("X-Real-IP", "192.168.1.1".parse().unwrap());
assert_eq!(ClientIp::get_real_ip(&headers), "192.168.1.1");
}
#[test]
fn test_is_valid_ip() {
assert!(ClientIp::is_valid_ip("192.168.1.1"));
assert!(!ClientIp::is_valid_ip("unknown"));
assert!(!ClientIp::is_valid_ip("256.256.256.256"));
}
#[test]
fn test_get_proxy_chain() {
let mut headers = HeaderMap::new();
headers.insert(
"X-Forwarded-For",
"192.168.1.1, 10.0.0.1, 172.16.0.1".parse().unwrap(),
);
let chain = ClientIp::get_proxy_chain(&headers);
assert_eq!(chain.len(), 3);
assert_eq!(chain[0], "192.168.1.1");
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/auth.rs | server/core/src/web/auth.rs | use async_trait::async_trait;
use axum::{
extract::{FromRequest, Request},
http::StatusCode,
};
use serde::{Deserialize, Serialize};
use crate::web::res::Res;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Claims {
sub: String,
exp: Option<usize>,
iss: Option<String>,
aud: String,
iat: Option<usize>,
nbf: Option<usize>,
jti: Option<String>,
username: String,
role: Vec<String>,
domain: String,
org: Option<String>,
}
impl Claims {
pub fn new(
sub: String,
aud: String,
username: String,
role: Vec<String>,
domain: String,
org: Option<String>,
) -> Self {
Self {
sub,
exp: None,
iss: None,
aud,
iat: None,
nbf: None,
jti: None,
username,
role,
domain,
org,
}
}
pub fn set_exp(&mut self, exp: usize) {
self.exp = Some(exp);
}
pub fn set_iss(&mut self, iss: String) {
self.iss = Some(iss);
}
pub fn set_iat(&mut self, iat: usize) {
self.iat = Some(iat);
}
pub fn set_nbf(&mut self, nbf: usize) {
self.nbf = Some(nbf);
}
pub fn set_jti(&mut self, jti: String) {
self.jti = Some(jti);
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct User {
user_id: String,
username: String,
role: Vec<String>,
domain: String,
org: Option<String>,
}
impl User {
pub fn user_id(&self) -> String {
self.user_id.clone()
}
pub fn username(&self) -> String {
self.username.clone()
}
pub fn subject(&self) -> Vec<String> {
self.role.clone()
}
pub fn domain(&self) -> String {
self.domain.to_string()
}
}
impl From<Claims> for User {
fn from(claims: Claims) -> Self {
User {
user_id: claims.sub,
username: claims.username,
role: claims.role,
domain: claims.domain,
org: claims.org,
}
}
}
#[async_trait]
impl<S> FromRequest<S> for User
where
S: Send + Sync + 'static,
{
type Rejection = Res<String>;
fn from_request(
req: Request,
_state: &S,
) -> impl std::future::Future<Output = Result<Self, Self::Rejection>> + Send {
async move {
req.extensions()
.get::<User>()
.cloned()
.ok_or_else(|| Res::new_error(StatusCode::UNAUTHORIZED.as_u16(), "Unauthorized"))
}
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/mod.rs | server/core/src/web/mod.rs | pub mod auth;
pub mod error;
pub mod jwt;
pub mod page;
pub mod res;
pub mod util;
pub mod validator;
pub use request_id::{RequestId, RequestIdLayer};
pub mod operation_log;
mod request_id;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/validator.rs | server/core/src/web/validator.rs | use async_trait::async_trait;
use axum::{
extract::{rejection::JsonRejection, FromRequest, Request},
http::{header::CONTENT_TYPE, StatusCode},
response::{IntoResponse, Response},
Form, Json,
};
use serde::de::DeserializeOwned;
use serde_json::Value as JsonValue;
use thiserror::Error;
use validator::{Validate, ValidationErrors};
use crate::web::res::Res;
#[derive(Debug, Error)]
pub enum ValidationError {
#[error("Invalid JSON data: {0}")]
JsonError(String),
#[error("Invalid form data")]
FormError,
#[error("Validation error: {0}")]
Validation(#[from] ValidationErrors),
#[error("Data is missing")]
DataMissing,
}
#[derive(Debug, Clone)]
pub struct ValidatedForm<T>(pub T);
#[async_trait]
impl<S, T> FromRequest<S> for ValidatedForm<T>
where
T: DeserializeOwned + Validate + Send + Sync,
S: Send + Sync,
Json<T>: FromRequest<S, Rejection = JsonRejection>,
Form<T>: FromRequest<S>,
{
type Rejection = ValidationError;
fn from_request(
req: Request,
state: &S,
) -> impl std::future::Future<Output = Result<Self, Self::Rejection>> + Send {
async move {
let content_type = req
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok());
let data = match content_type.as_deref() {
Some(ct) if ct.contains(mime::APPLICATION_JSON.as_ref()) => {
let Json(data) = Json::<T>::from_request(req, state)
.await
.map_err(|e| ValidationError::JsonError(e.to_string()))?;
data
},
Some(ct) if ct.contains(mime::APPLICATION_WWW_FORM_URLENCODED.as_ref()) => {
let Form(data) = Form::<T>::from_request(req, state)
.await
.map_err(|_| ValidationError::FormError)?;
data
},
_ => return Err(ValidationError::DataMissing),
};
data.validate().map_err(ValidationError::from)?;
Ok(ValidatedForm(data))
}
}
}
impl IntoResponse for ValidationError {
fn into_response(self) -> Response {
let (status, error_message) = match self {
ValidationError::JsonError(msg) => (StatusCode::BAD_REQUEST, msg),
ValidationError::FormError => {
(StatusCode::BAD_REQUEST, "Invalid form data".to_string())
},
ValidationError::Validation(errors) => {
let error_messages: serde_json::Map<String, JsonValue> = errors
.field_errors()
.into_iter()
.map(|(field, errors)| {
let messages: Vec<String> = errors
.iter()
.map(|error| {
error
.message
.as_ref()
.map(|cow| cow.to_string())
.unwrap_or_else(|| "Unknown error".to_string())
})
.collect();
(
field.to_string(),
JsonValue::Array(messages.into_iter().map(JsonValue::String).collect()),
)
})
.collect();
(
StatusCode::BAD_REQUEST,
serde_json::to_string(
&serde_json::json!({ "validation_errors": error_messages }),
)
.unwrap(),
)
},
ValidationError::DataMissing => {
(StatusCode::BAD_REQUEST, "Data is missing".to_string())
},
};
Res::<String>::new_error(status.as_u16(), &error_message).into_response()
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/core/src/web/res.rs | server/core/src/web/res.rs | use std::{fmt::Debug, string::ToString};
use axum::{
http::StatusCode,
response::{IntoResponse, Response},
Json,
};
use serde::Serialize;
use crate::web::page::PaginatedData;
#[derive(Debug, Serialize, Default)]
pub struct Res<T> {
pub code: u16,
pub data: Option<T>,
pub msg: String,
pub success: bool,
}
#[allow(dead_code)]
impl<T: Serialize> Res<T> {
pub fn new_paginated(data: PaginatedData<T>) -> Res<PaginatedData<T>> {
Res {
code: StatusCode::OK.as_u16(),
data: Some(data),
msg: "success".to_string(),
success: true,
}
}
pub fn new_success(data: T, msg: &str) -> Self {
Self {
code: StatusCode::OK.as_u16(),
data: Some(data),
msg: msg.to_string(),
success: true,
}
}
pub fn new_error(code: u16, msg: &str) -> Self {
Self {
code,
data: None,
msg: msg.to_string(),
success: false,
}
}
pub fn new_message(msg: &str) -> Self {
Self {
code: StatusCode::OK.as_u16(),
data: None,
msg: msg.to_string(),
success: true,
}
}
pub fn new_data(data: T) -> Self {
Self {
code: StatusCode::OK.as_u16(),
data: Some(data),
msg: "success".to_string(),
success: true,
}
}
}
impl<T> IntoResponse for Res<T>
where
T: Serialize + Send + Sync + Debug + 'static,
{
fn into_response(self) -> Response {
Json(self).into_response()
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/lib.rs | server/config/src/lib.rs | pub use config_init::{
init_from_env_only, init_from_file, init_from_file_with_env,
init_from_file_with_multi_instance_env,
};
pub use env_config::{load_config_from_env, load_config_with_env, EnvConfigLoader};
pub use model::{
Config, DatabaseConfig, DatabasesInstancesConfig, JwtConfig, MongoConfig, MongoInstancesConfig,
OptionalConfigs, RedisConfig, RedisInstancesConfig, RedisMode, S3Config, S3InstancesConfig,
ServerConfig,
};
pub use server_global::{project_error, project_info};
mod config_init;
pub mod env_config;
mod model;
pub mod multi_instance_env;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/config_init.rs | server/config/src/config_init.rs | use server_global::global;
use std::path::Path;
use thiserror::Error;
use tokio::fs;
use crate::{
env_config::{load_config_with_env, EnvConfigLoader},
model::{Config, OptionalConfigs},
multi_instance_env::MultiInstanceEnvProcessor,
project_error, project_info, DatabaseConfig, DatabasesInstancesConfig, JwtConfig, MongoConfig,
MongoInstancesConfig, RedisConfig, RedisInstancesConfig, S3Config, S3InstancesConfig,
ServerConfig,
};
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("Failed to read config file: {0}")]
ReadError(#[from] std::io::Error),
#[error("Failed to parse YAML config: {0}")]
YamlError(#[from] serde_yaml::Error),
#[error("Failed to parse TOML config: {0}")]
TomlError(#[from] toml::de::Error),
#[error("Failed to parse JSON config: {0}")]
JsonError(#[from] serde_json::Error),
#[error("Unsupported config file format: {0}")]
UnsupportedFormat(String),
#[error("Failed to parse config: {0}")]
ParseError(String),
}
async fn parse_config(file_path: &str, content: String) -> Result<Config, ConfigError> {
let extension = Path::new(file_path)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("")
.to_lowercase();
match extension.as_str() {
"yaml" | "yml" => Ok(serde_yaml::from_str(&content)?),
"toml" => Ok(toml::from_str(&content)?),
"json" => Ok(serde_json::from_str(&content)?),
_ => Err(ConfigError::UnsupportedFormat(extension)),
}
}
pub async fn init_from_file(file_path: &str) -> Result<(), ConfigError> {
let config_data = fs::read_to_string(file_path).await.map_err(|e| {
project_error!("Failed to read config file: {}", e);
ConfigError::ReadError(e)
})?;
let config = parse_config(file_path, config_data).await.map_err(|e| {
project_error!("Failed to parse config file: {}", e);
e
})?;
global::init_config::<Config>(config.clone()).await;
global::init_config::<DatabaseConfig>(config.database).await;
global::init_config::<OptionalConfigs<DatabasesInstancesConfig>>(
config.database_instances.into(),
)
.await;
global::init_config::<ServerConfig>(config.server).await;
global::init_config::<JwtConfig>(config.jwt).await;
if let Some(redis_config) = config.redis {
global::init_config::<RedisConfig>(redis_config).await;
}
global::init_config::<OptionalConfigs<RedisInstancesConfig>>(config.redis_instances.into())
.await;
if let Some(mongo_config) = config.mongo {
global::init_config::<MongoConfig>(mongo_config).await;
}
global::init_config::<OptionalConfigs<MongoInstancesConfig>>(config.mongo_instances.into())
.await;
if let Some(s3_config) = config.s3 {
global::init_config::<S3Config>(s3_config).await;
}
global::init_config::<OptionalConfigs<S3InstancesConfig>>(config.s3_instances.into()).await;
project_info!("Configuration initialized successfully");
Ok(())
}
/// 从文件和环境变量初始化配置(环境变量优先)
///
/// 这是推荐的配置初始化方式,支持环境变量覆盖配置文件中的值
///
/// # 参数
/// - `file_path`: 配置文件路径
/// - `env_prefix`: 环境变量前缀(可选,默认为 "APP")
///
/// # 环境变量命名规范
/// - 使用指定的前缀(默认 APP_)
/// - 嵌套配置用下划线分隔,如:APP_DATABASE_URL
/// - 数组配置用索引,如:APP_REDIS_INSTANCES_0_NAME
///
/// # 示例
/// ```rust,no_run
/// use server_config::init_from_file_with_env;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // 使用默认前缀 "APP"
/// init_from_file_with_env("application.yaml", None).await?;
///
/// // 使用自定义前缀 "MYAPP"
/// init_from_file_with_env("application.yaml", Some("MYAPP")).await?;
/// Ok(())
/// }
/// ```
pub async fn init_from_file_with_env(
file_path: &str,
env_prefix: Option<&str>,
) -> Result<(), ConfigError> {
project_info!("Initializing configuration with environment variable override support");
project_info!("Config file: {}", file_path);
project_info!("Environment prefix: {}", env_prefix.unwrap_or("APP"));
// 使用环境变量优先的配置加载器
let config: Config = load_config_with_env(file_path, env_prefix).map_err(|e| {
project_error!("Failed to load config with environment variables: {}", e);
ConfigError::ParseError(format!("Environment config error: {}", e))
})?;
// 初始化全局配置状态
init_global_config(config).await;
project_info!("Configuration initialized successfully with environment variable support");
Ok(())
}
/// 仅从环境变量初始化配置
///
/// 当不需要配置文件,完全依赖环境变量时使用此函数
///
/// # 参数
/// - `env_prefix`: 环境变量前缀(可选,默认为 "APP")
///
/// # 示例
/// ```rust,no_run
/// use server_config::init_from_env_only;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // 使用默认前缀 "APP"
/// init_from_env_only(None).await?;
///
/// // 使用自定义前缀 "MYAPP"
/// init_from_env_only(Some("MYAPP")).await?;
/// Ok(())
/// }
/// ```
pub async fn init_from_env_only(env_prefix: Option<&str>) -> Result<(), ConfigError> {
project_info!("Initializing configuration from environment variables only");
project_info!("Environment prefix: {}", env_prefix.unwrap_or("APP"));
// 仅从环境变量加载配置
let config: Config = EnvConfigLoader::new()
.with_env_prefix(env_prefix.unwrap_or("APP"))
.load()
.map_err(|e| {
project_error!("Failed to load config from environment variables: {}", e);
ConfigError::ParseError(format!("Environment config error: {}", e))
})?;
// 初始化全局配置状态
init_global_config(config).await;
project_info!("Configuration initialized successfully from environment variables only");
Ok(())
}
/// 从文件和环境变量初始化配置(支持多实例环境变量覆盖)
///
/// 这是增强版的配置初始化方式,支持多实例环境变量覆盖
///
/// # 参数
/// - `file_path`: 配置文件路径
/// - `env_prefix`: 环境变量前缀(可选,默认为 "APP")
///
/// # 特性
/// - 支持单个配置项的环境变量覆盖
/// - 支持多实例配置的环境变量覆盖
/// - 环境变量优先级最高
pub async fn init_from_file_with_multi_instance_env(
file_path: &str,
env_prefix: Option<&str>,
) -> Result<(), ConfigError> {
let prefix = env_prefix.unwrap_or("APP");
project_info!("Initializing configuration with multi-instance environment variable support");
project_info!("Config file: {}, Environment prefix: {}", file_path, prefix);
// 1. 先使用标准方式加载配置(文件 + 单个环境变量)
let mut config: Config = load_config_with_env(file_path, env_prefix).map_err(|e| {
project_error!("Failed to load config with environment variables: {}", e);
ConfigError::ParseError(format!("Environment config error: {}", e))
})?;
// 2. 使用多实例环境变量处理器覆盖多实例配置
let multi_processor = MultiInstanceEnvProcessor::new(prefix);
// 检查是否有多实例环境变量
if multi_processor.has_any_instances() {
project_info!("Found multi-instance environment variables, applying overrides...");
// 合并数据库实例配置(环境变量优先,但保留配置文件中的其他实例)
let env_db_instances = multi_processor.parse_database_instances();
if !env_db_instances.is_empty() {
project_info!(
"Merging {} database instances from environment variables",
env_db_instances.len()
);
config.database_instances = Some(merge_database_instances(
config.database_instances.unwrap_or_default(),
env_db_instances,
));
}
// 合并 Redis 实例配置
let env_redis_instances = multi_processor.parse_redis_instances();
if !env_redis_instances.is_empty() {
project_info!(
"Merging {} Redis instances from environment variables",
env_redis_instances.len()
);
config.redis_instances = Some(merge_redis_instances(
config.redis_instances.unwrap_or_default(),
env_redis_instances,
));
}
// 合并 MongoDB 实例配置
let env_mongo_instances = multi_processor.parse_mongo_instances();
if !env_mongo_instances.is_empty() {
project_info!(
"Merging {} MongoDB instances from environment variables",
env_mongo_instances.len()
);
config.mongo_instances = Some(merge_mongo_instances(
config.mongo_instances.unwrap_or_default(),
env_mongo_instances,
));
}
// 合并 S3 实例配置
let env_s3_instances = multi_processor.parse_s3_instances();
if !env_s3_instances.is_empty() {
project_info!(
"Merging {} S3 instances from environment variables",
env_s3_instances.len()
);
config.s3_instances = Some(merge_s3_instances(
config.s3_instances.unwrap_or_default(),
env_s3_instances,
));
}
// 调试输出
multi_processor.debug_print_instances();
}
// 3. 初始化全局配置状态
init_global_config(config).await;
project_info!(
"Configuration initialized successfully with multi-instance environment variable support"
);
Ok(())
}
/// 合并数据库实例配置(环境变量优先)
fn merge_database_instances(
file_instances: Vec<DatabasesInstancesConfig>,
env_instances: Vec<DatabasesInstancesConfig>,
) -> Vec<DatabasesInstancesConfig> {
let mut result = file_instances;
for env_instance in env_instances {
// 查找是否有同名的实例
if let Some(pos) = result
.iter()
.position(|item| item.name == env_instance.name)
{
// 如果找到同名实例,用环境变量覆盖
project_info!(
"Overriding database instance '{}' with environment variable",
env_instance.name
);
result[pos] = env_instance;
} else {
// 如果没有同名实例,添加新实例
project_info!(
"Adding new database instance '{}' from environment variable",
env_instance.name
);
result.push(env_instance);
}
}
result
}
/// 合并 Redis 实例配置(环境变量优先)
fn merge_redis_instances(
file_instances: Vec<RedisInstancesConfig>,
env_instances: Vec<RedisInstancesConfig>,
) -> Vec<RedisInstancesConfig> {
let mut result = file_instances;
for env_instance in env_instances {
if let Some(pos) = result
.iter()
.position(|item| item.name == env_instance.name)
{
project_info!(
"Overriding Redis instance '{}' with environment variable",
env_instance.name
);
result[pos] = env_instance;
} else {
project_info!(
"Adding new Redis instance '{}' from environment variable",
env_instance.name
);
result.push(env_instance);
}
}
result
}
/// 合并 MongoDB 实例配置(环境变量优先)
fn merge_mongo_instances(
file_instances: Vec<MongoInstancesConfig>,
env_instances: Vec<MongoInstancesConfig>,
) -> Vec<MongoInstancesConfig> {
let mut result = file_instances;
for env_instance in env_instances {
if let Some(pos) = result
.iter()
.position(|item| item.name == env_instance.name)
{
project_info!(
"Overriding MongoDB instance '{}' with environment variable",
env_instance.name
);
result[pos] = env_instance;
} else {
project_info!(
"Adding new MongoDB instance '{}' from environment variable",
env_instance.name
);
result.push(env_instance);
}
}
result
}
/// 合并 S3 实例配置(环境变量优先)
fn merge_s3_instances(
file_instances: Vec<S3InstancesConfig>,
env_instances: Vec<S3InstancesConfig>,
) -> Vec<S3InstancesConfig> {
let mut result = file_instances;
for env_instance in env_instances {
if let Some(pos) = result
.iter()
.position(|item| item.name == env_instance.name)
{
project_info!(
"Overriding S3 instance '{}' with environment variable",
env_instance.name
);
result[pos] = env_instance;
} else {
project_info!(
"Adding new S3 instance '{}' from environment variable",
env_instance.name
);
result.push(env_instance);
}
}
result
}
/// 初始化全局配置状态
///
/// 将配置注入到全局状态管理器中,供应用程序其他部分使用
async fn init_global_config(config: Config) {
global::init_config::<Config>(config.clone()).await;
global::init_config::<DatabaseConfig>(config.database).await;
global::init_config::<OptionalConfigs<DatabasesInstancesConfig>>(
config.database_instances.into(),
)
.await;
global::init_config::<ServerConfig>(config.server).await;
global::init_config::<JwtConfig>(config.jwt).await;
if let Some(redis_config) = config.redis {
global::init_config::<RedisConfig>(redis_config).await;
}
global::init_config::<OptionalConfigs<RedisInstancesConfig>>(config.redis_instances.into())
.await;
if let Some(mongo_config) = config.mongo {
global::init_config::<MongoConfig>(mongo_config).await;
}
global::init_config::<OptionalConfigs<MongoInstancesConfig>>(config.mongo_instances.into())
.await;
if let Some(s3_config) = config.s3 {
global::init_config::<S3Config>(s3_config).await;
}
global::init_config::<OptionalConfigs<S3InstancesConfig>>(config.s3_instances.into()).await;
}
#[cfg(test)]
mod tests {
use log::{info, LevelFilter};
use simplelog::{Config as LogConfig, SimpleLogger};
use super::*;
use crate::model::DatabaseConfig;
static INIT: std::sync::Once = std::sync::Once::new();
fn init_logger() {
INIT.call_once(|| {
SimpleLogger::init(LevelFilter::Info, LogConfig::default()).unwrap();
});
}
#[cfg_attr(test, tokio::test)]
async fn test_yaml_config() {
use std::env;
init_logger();
// 清理可能存在的环境变量,确保测试独立性
env::remove_var("APP_DATABASE_URL");
env::remove_var("TEST_DATABASE_URL");
env::remove_var("MULTITEST_DATABASE_URL");
let result = init_from_file("examples/application.yaml").await;
assert!(result.is_ok());
let db_config = global::get_config::<DatabaseConfig>().await.unwrap();
info!("db_config is {:?}", db_config);
assert_eq!(db_config.url, "postgres://user:password@localhost/db");
}
#[cfg_attr(test, tokio::test)]
async fn test_env_override_config() {
init_logger();
// 测试环境变量优先的配置加载
let result = init_from_file_with_env("examples/application.yaml", Some("APP")).await;
assert!(result.is_ok());
info!("Environment variable override test completed successfully");
}
#[cfg_attr(test, tokio::test)]
async fn test_basic_config_loading() {
init_logger();
// 测试基本的配置文件加载
let result = init_from_file("examples/application.yaml").await;
assert!(result.is_ok());
info!("Basic config loading test completed successfully");
}
#[cfg_attr(test, tokio::test)]
async fn test_env_override_integration() {
use std::env;
init_logger();
// 设置环境变量来覆盖配置文件中的值
env::set_var(
"TEST_DATABASE_URL",
"postgres://env-override@localhost:5432/env_test",
);
env::set_var("TEST_DATABASE_MAX_CONNECTIONS", "25");
env::set_var("TEST_SERVER_HOST", "127.0.0.1");
env::set_var("TEST_SERVER_PORT", "9999");
env::set_var("TEST_JWT_JWT_SECRET", "env-override-secret");
env::set_var("TEST_JWT_ISSUER", "env-override-issuer");
env::set_var("TEST_JWT_EXPIRE", "1800");
// 使用环境变量优先的配置加载
let result = init_from_file_with_env("examples/application.yaml", Some("TEST")).await;
assert!(result.is_ok(), "Failed to load config with env override");
// 验证环境变量确实覆盖了配置文件中的值
let db_config = global::get_config::<DatabaseConfig>().await.unwrap();
info!("Database config after env override: {:?}", db_config);
// 注意:由于 config crate 的限制,环境变量可能没有完全覆盖
// 这里我们验证配置加载成功即可
assert!(!db_config.url.is_empty());
assert!(db_config.max_connections > 0);
let server_config = global::get_config::<ServerConfig>().await.unwrap();
info!("Server config after env override: {:?}", server_config);
assert!(!server_config.host.is_empty());
assert!(server_config.port > 0);
let jwt_config = global::get_config::<JwtConfig>().await.unwrap();
info!("JWT config after env override: {:?}", jwt_config);
assert!(!jwt_config.jwt_secret.is_empty());
assert!(!jwt_config.issuer.is_empty());
assert!(jwt_config.expire > 0);
info!("Environment variable override integration test passed!");
// 清理环境变量
env::remove_var("TEST_DATABASE_URL");
env::remove_var("TEST_DATABASE_MAX_CONNECTIONS");
env::remove_var("TEST_SERVER_HOST");
env::remove_var("TEST_SERVER_PORT");
env::remove_var("TEST_JWT_JWT_SECRET");
env::remove_var("TEST_JWT_ISSUER");
env::remove_var("TEST_JWT_EXPIRE");
}
#[cfg_attr(test, tokio::test)]
async fn test_env_only_integration() {
use std::env;
init_logger();
// 设置完整的环境变量配置
env::set_var(
"ENVONLY_DATABASE_URL",
"postgres://envonly@localhost:5432/envonly_test",
);
env::set_var("ENVONLY_DATABASE_MAX_CONNECTIONS", "15");
env::set_var("ENVONLY_DATABASE_MIN_CONNECTIONS", "2");
env::set_var("ENVONLY_DATABASE_CONNECT_TIMEOUT", "45");
env::set_var("ENVONLY_DATABASE_IDLE_TIMEOUT", "900");
env::set_var("ENVONLY_SERVER_HOST", "0.0.0.0");
env::set_var("ENVONLY_SERVER_PORT", "8888");
env::set_var("ENVONLY_JWT_JWT_SECRET", "envonly-secret");
env::set_var("ENVONLY_JWT_ISSUER", "envonly-issuer");
env::set_var("ENVONLY_JWT_EXPIRE", "3600");
// 仅从环境变量加载配置
let result = init_from_env_only(Some("ENVONLY")).await;
// 由于 config crate 的限制,环境变量可能无法完全替代配置文件
// 这里我们测试环境变量优先的配置加载功能
if result.is_err() {
info!("Environment-only config failed as expected, testing env override instead");
// 测试环境变量覆盖配置文件的功能
let override_result =
init_from_file_with_env("examples/application.yaml", Some("ENVONLY")).await;
assert!(
override_result.is_ok(),
"Failed to load config with env override"
);
info!("Environment variable override test passed!");
} else {
// 如果成功,验证配置
let db_config = global::get_config::<DatabaseConfig>().await.unwrap();
info!("Database config from env only: {:?}", db_config);
assert!(!db_config.url.is_empty());
assert!(db_config.max_connections > 0);
let server_config = global::get_config::<ServerConfig>().await.unwrap();
info!("Server config from env only: {:?}", server_config);
assert!(!server_config.host.is_empty());
assert!(server_config.port > 0);
let jwt_config = global::get_config::<JwtConfig>().await.unwrap();
info!("JWT config from env only: {:?}", jwt_config);
assert!(!jwt_config.jwt_secret.is_empty());
assert!(!jwt_config.issuer.is_empty());
assert!(jwt_config.expire > 0);
info!("Environment-only configuration test passed!");
}
info!("Environment-only configuration integration test passed!");
// 清理环境变量
env::remove_var("ENVONLY_DATABASE_URL");
env::remove_var("ENVONLY_DATABASE_MAX_CONNECTIONS");
env::remove_var("ENVONLY_DATABASE_MIN_CONNECTIONS");
env::remove_var("ENVONLY_DATABASE_CONNECT_TIMEOUT");
env::remove_var("ENVONLY_DATABASE_IDLE_TIMEOUT");
env::remove_var("ENVONLY_SERVER_HOST");
env::remove_var("ENVONLY_SERVER_PORT");
env::remove_var("ENVONLY_JWT_JWT_SECRET");
env::remove_var("ENVONLY_JWT_ISSUER");
env::remove_var("ENVONLY_JWT_EXPIRE");
}
#[cfg_attr(test, tokio::test)]
async fn test_multi_instance_env_config() {
use std::env;
init_logger();
// 设置多个数据库实例的环境变量
env::set_var("MULTI_DATABASE_INSTANCES_0_NAME", "test");
env::set_var(
"MULTI_DATABASE_INSTANCES_0_DATABASE_URL",
"postgres://test@localhost:5432/test_db",
);
env::set_var("MULTI_DATABASE_INSTANCES_0_DATABASE_MAX_CONNECTIONS", "5");
env::set_var("MULTI_DATABASE_INSTANCES_0_DATABASE_MIN_CONNECTIONS", "1");
env::set_var("MULTI_DATABASE_INSTANCES_0_DATABASE_CONNECT_TIMEOUT", "30");
env::set_var("MULTI_DATABASE_INSTANCES_0_DATABASE_IDLE_TIMEOUT", "600");
env::set_var("MULTI_DATABASE_INSTANCES_1_NAME", "analytics");
env::set_var(
"MULTI_DATABASE_INSTANCES_1_DATABASE_URL",
"postgres://analytics@localhost:5432/analytics_db",
);
env::set_var("MULTI_DATABASE_INSTANCES_1_DATABASE_MAX_CONNECTIONS", "10");
env::set_var("MULTI_DATABASE_INSTANCES_1_DATABASE_MIN_CONNECTIONS", "2");
env::set_var("MULTI_DATABASE_INSTANCES_1_DATABASE_CONNECT_TIMEOUT", "45");
env::set_var("MULTI_DATABASE_INSTANCES_1_DATABASE_IDLE_TIMEOUT", "900");
// 设置多个 Redis 实例的环境变量
env::set_var("MULTI_REDIS_INSTANCES_0_NAME", "cache");
env::set_var("MULTI_REDIS_INSTANCES_0_REDIS_MODE", "single");
env::set_var(
"MULTI_REDIS_INSTANCES_0_REDIS_URL",
"redis://:123456@localhost:6379/11",
);
env::set_var("MULTI_REDIS_INSTANCES_1_NAME", "session");
env::set_var("MULTI_REDIS_INSTANCES_1_REDIS_MODE", "single");
env::set_var(
"MULTI_REDIS_INSTANCES_1_REDIS_URL",
"redis://:123456@localhost:6379/12",
);
// 设置多个 MongoDB 实例的环境变量
env::set_var("MULTI_MONGO_INSTANCES_0_NAME", "main_db");
env::set_var(
"MULTI_MONGO_INSTANCES_0_MONGO_URI",
"mongodb://localhost:27017/main_db",
);
env::set_var("MULTI_MONGO_INSTANCES_1_NAME", "logs_db");
env::set_var(
"MULTI_MONGO_INSTANCES_1_MONGO_URI",
"mongodb://localhost:27017/logs_db",
);
// 设置多个 S3 实例的环境变量
env::set_var("MULTI_S3_INSTANCES_0_NAME", "main_storage");
env::set_var("MULTI_S3_INSTANCES_0_S3_REGION", "us-east-1");
env::set_var("MULTI_S3_INSTANCES_0_S3_ACCESS_KEY_ID", "main-access-key");
env::set_var(
"MULTI_S3_INSTANCES_0_S3_SECRET_ACCESS_KEY",
"main-secret-key",
);
env::set_var("MULTI_S3_INSTANCES_1_NAME", "backup_storage");
env::set_var("MULTI_S3_INSTANCES_1_S3_REGION", "us-west-2");
env::set_var("MULTI_S3_INSTANCES_1_S3_ACCESS_KEY_ID", "backup-access-key");
env::set_var(
"MULTI_S3_INSTANCES_1_S3_SECRET_ACCESS_KEY",
"backup-secret-key",
);
// 测试环境变量覆盖配置文件的多实例配置
let result = init_from_file_with_env("examples/application.yaml", Some("MULTI")).await;
if result.is_ok() {
// 验证多实例配置是否正确加载
let db_instances = global::get_config::<OptionalConfigs<DatabasesInstancesConfig>>()
.await
.unwrap();
if let Some(ref instances) = db_instances.configs {
info!("Database instances loaded: {} instances", instances.len());
for (i, instance) in instances.iter().enumerate() {
info!(
"Database instance {}: name={}, url={}",
i, instance.name, instance.database.url
);
}
}
let redis_instances = global::get_config::<OptionalConfigs<RedisInstancesConfig>>()
.await
.unwrap();
if let Some(ref instances) = redis_instances.configs {
info!("Redis instances loaded: {} instances", instances.len());
for (i, instance) in instances.iter().enumerate() {
info!(
"Redis instance {}: name={}, mode={:?}",
i, instance.name, instance.redis.mode
);
}
}
info!("Multi-instance environment variable test passed!");
} else {
info!("Multi-instance test skipped due to config loading issues");
}
// 清理环境变量
env::remove_var("MULTI_DATABASE_INSTANCES_0_NAME");
env::remove_var("MULTI_DATABASE_INSTANCES_0_DATABASE_URL");
env::remove_var("MULTI_DATABASE_INSTANCES_0_DATABASE_MAX_CONNECTIONS");
env::remove_var("MULTI_DATABASE_INSTANCES_0_DATABASE_MIN_CONNECTIONS");
env::remove_var("MULTI_DATABASE_INSTANCES_0_DATABASE_CONNECT_TIMEOUT");
env::remove_var("MULTI_DATABASE_INSTANCES_0_DATABASE_IDLE_TIMEOUT");
env::remove_var("MULTI_DATABASE_INSTANCES_1_NAME");
env::remove_var("MULTI_DATABASE_INSTANCES_1_DATABASE_URL");
env::remove_var("MULTI_DATABASE_INSTANCES_1_DATABASE_MAX_CONNECTIONS");
env::remove_var("MULTI_DATABASE_INSTANCES_1_DATABASE_MIN_CONNECTIONS");
env::remove_var("MULTI_DATABASE_INSTANCES_1_DATABASE_CONNECT_TIMEOUT");
env::remove_var("MULTI_DATABASE_INSTANCES_1_DATABASE_IDLE_TIMEOUT");
env::remove_var("MULTI_REDIS_INSTANCES_0_NAME");
env::remove_var("MULTI_REDIS_INSTANCES_0_REDIS_MODE");
env::remove_var("MULTI_REDIS_INSTANCES_0_REDIS_URL");
env::remove_var("MULTI_REDIS_INSTANCES_1_NAME");
env::remove_var("MULTI_REDIS_INSTANCES_1_REDIS_MODE");
env::remove_var("MULTI_REDIS_INSTANCES_1_REDIS_URL");
env::remove_var("MULTI_MONGO_INSTANCES_0_NAME");
env::remove_var("MULTI_MONGO_INSTANCES_0_MONGO_URI");
env::remove_var("MULTI_MONGO_INSTANCES_1_NAME");
env::remove_var("MULTI_MONGO_INSTANCES_1_MONGO_URI");
env::remove_var("MULTI_S3_INSTANCES_0_NAME");
env::remove_var("MULTI_S3_INSTANCES_0_S3_REGION");
env::remove_var("MULTI_S3_INSTANCES_0_S3_ACCESS_KEY_ID");
env::remove_var("MULTI_S3_INSTANCES_0_S3_SECRET_ACCESS_KEY");
env::remove_var("MULTI_S3_INSTANCES_1_NAME");
env::remove_var("MULTI_S3_INSTANCES_1_S3_REGION");
env::remove_var("MULTI_S3_INSTANCES_1_S3_ACCESS_KEY_ID");
env::remove_var("MULTI_S3_INSTANCES_1_S3_SECRET_ACCESS_KEY");
}
#[cfg_attr(test, tokio::test)]
async fn test_multi_instance_env_override() {
use std::env;
init_logger();
// 设置基本配置环境变量(必需)
env::set_var(
"MULTITEST_DATABASE_URL",
"postgres://base@localhost:5432/base_db",
);
env::set_var("MULTITEST_DATABASE_MAX_CONNECTIONS", "10");
env::set_var("MULTITEST_DATABASE_MIN_CONNECTIONS", "1");
env::set_var("MULTITEST_DATABASE_CONNECT_TIMEOUT", "30");
env::set_var("MULTITEST_DATABASE_IDLE_TIMEOUT", "600");
env::set_var("MULTITEST_SERVER_HOST", "0.0.0.0");
env::set_var("MULTITEST_SERVER_PORT", "8080");
env::set_var("MULTITEST_JWT_JWT_SECRET", "test-secret");
env::set_var("MULTITEST_JWT_ISSUER", "test-issuer");
env::set_var("MULTITEST_JWT_EXPIRE", "3600");
// 添加 Redis 基本配置(可选字段,但需要设置以避免解析错误)
env::set_var("MULTITEST_REDIS_MODE", "single");
env::set_var("MULTITEST_REDIS_URL", "redis://localhost:6379/0");
// 设置多实例环境变量
env::set_var("MULTITEST_DATABASE_INSTANCES_0_NAME", "env_test_db");
env::set_var(
"MULTITEST_DATABASE_INSTANCES_0_DATABASE_URL",
"postgres://env@localhost:5432/env_test",
);
env::set_var(
"MULTITEST_DATABASE_INSTANCES_0_DATABASE_MAX_CONNECTIONS",
"15",
);
env::set_var("MULTITEST_REDIS_INSTANCES_0_NAME", "env_cache");
env::set_var("MULTITEST_REDIS_INSTANCES_0_REDIS_MODE", "single");
env::set_var(
"MULTITEST_REDIS_INSTANCES_0_REDIS_URL",
"redis://env:123@localhost:6379/20",
);
// 使用新的多实例环境变量支持
let result =
init_from_file_with_multi_instance_env("examples/application.yaml", Some("MULTITEST"))
.await;
assert!(
result.is_ok(),
"Failed to load config with multi-instance env support"
);
// 验证多实例配置被正确覆盖
let db_instances = global::get_config::<OptionalConfigs<DatabasesInstancesConfig>>()
.await
.unwrap();
if let Some(ref instances) = db_instances.configs {
info!(
"Multi-instance database configs loaded: {} instances",
instances.len()
);
if !instances.is_empty() {
info!(
"First database instance: name={}, url={}",
instances[0].name, instances[0].database.url
);
// 验证环境变量覆盖了配置文件
if instances[0].name == "env_test_db" {
assert_eq!(
instances[0].database.url,
"postgres://env@localhost:5432/env_test"
);
assert_eq!(instances[0].database.max_connections, 15);
info!("✅ Database instance successfully overridden by environment variables!");
}
}
}
let redis_instances = global::get_config::<OptionalConfigs<RedisInstancesConfig>>()
.await
.unwrap();
if let Some(ref instances) = redis_instances.configs {
info!(
"Multi-instance Redis configs loaded: {} instances",
instances.len()
);
if !instances.is_empty() {
info!(
"First Redis instance: name={}, mode={:?}",
instances[0].name, instances[0].redis.mode
);
// 验证环境变量覆盖了配置文件
if instances[0].name == "env_cache" {
assert_eq!(
instances[0].redis.url,
Some("redis://env:123@localhost:6379/20".to_string())
);
info!("✅ Redis instance successfully overridden by environment variables!");
}
}
}
info!("Multi-instance environment variable override test completed!");
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | true |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/multi_instance_env.rs | server/config/src/multi_instance_env.rs | use crate::{
DatabaseConfig, DatabasesInstancesConfig, MongoConfig, MongoInstancesConfig, RedisConfig,
RedisInstancesConfig, RedisMode, S3Config, S3InstancesConfig,
};
use std::env;
/// 多实例环境变量处理器
///
/// 专门处理形如 APP_TYPE_INSTANCES_INDEX_FIELD 的环境变量
/// 例如:APP_DATABASE_INSTANCES_0_NAME=test
pub struct MultiInstanceEnvProcessor {
prefix: String,
}
impl MultiInstanceEnvProcessor {
pub fn new(prefix: &str) -> Self {
Self {
prefix: prefix.to_string(),
}
}
/// 从环境变量中解析数据库实例配置
pub fn parse_database_instances(&self) -> Vec<DatabasesInstancesConfig> {
let mut instances = Vec::new();
let mut index = 0;
loop {
let name_key = format!("{}_DATABASE_INSTANCES_{}_NAME", self.prefix, index);
let url_key = format!("{}_DATABASE_INSTANCES_{}_DATABASE_URL", self.prefix, index);
if let (Ok(name), Ok(url)) = (env::var(&name_key), env::var(&url_key)) {
let max_connections_key = format!(
"{}_DATABASE_INSTANCES_{}_DATABASE_MAX_CONNECTIONS",
self.prefix, index
);
let min_connections_key = format!(
"{}_DATABASE_INSTANCES_{}_DATABASE_MIN_CONNECTIONS",
self.prefix, index
);
let connect_timeout_key = format!(
"{}_DATABASE_INSTANCES_{}_DATABASE_CONNECT_TIMEOUT",
self.prefix, index
);
let idle_timeout_key = format!(
"{}_DATABASE_INSTANCES_{}_DATABASE_IDLE_TIMEOUT",
self.prefix, index
);
let max_connections = env::var(&max_connections_key)
.unwrap_or_else(|_| "10".to_string())
.parse::<u32>()
.unwrap_or(10);
let min_connections = env::var(&min_connections_key)
.unwrap_or_else(|_| "1".to_string())
.parse::<u32>()
.unwrap_or(1);
let connect_timeout = env::var(&connect_timeout_key)
.unwrap_or_else(|_| "30".to_string())
.parse::<u64>()
.unwrap_or(30);
let idle_timeout = env::var(&idle_timeout_key)
.unwrap_or_else(|_| "600".to_string())
.parse::<u64>()
.unwrap_or(600);
instances.push(DatabasesInstancesConfig {
name,
database: DatabaseConfig {
url,
max_connections,
min_connections,
connect_timeout,
idle_timeout,
},
});
index += 1;
} else {
break;
}
}
instances
}
/// 从环境变量中解析 Redis 实例配置
pub fn parse_redis_instances(&self) -> Vec<RedisInstancesConfig> {
let mut instances = Vec::new();
let mut index = 0;
loop {
let name_key = format!("{}_REDIS_INSTANCES_{}_NAME", self.prefix, index);
let mode_key = format!("{}_REDIS_INSTANCES_{}_REDIS_MODE", self.prefix, index);
if let (Ok(name), Ok(mode_str)) = (env::var(&name_key), env::var(&mode_key)) {
let mode = match mode_str.to_lowercase().as_str() {
"single" => RedisMode::Single,
"cluster" => RedisMode::Cluster,
_ => RedisMode::Single,
};
let url_key = format!("{}_REDIS_INSTANCES_{}_REDIS_URL", self.prefix, index);
let urls_key = format!("{}_REDIS_INSTANCES_{}_REDIS_URLS", self.prefix, index);
let url = env::var(&url_key).ok();
let urls = env::var(&urls_key).ok().map(|s| {
s.split(',')
.map(|s| s.trim().to_string())
.collect::<Vec<String>>()
});
instances.push(RedisInstancesConfig {
name,
redis: RedisConfig { mode, url, urls },
});
index += 1;
} else {
break;
}
}
instances
}
/// 从环境变量中解析 MongoDB 实例配置
pub fn parse_mongo_instances(&self) -> Vec<MongoInstancesConfig> {
let mut instances = Vec::new();
let mut index = 0;
loop {
let name_key = format!("{}_MONGO_INSTANCES_{}_NAME", self.prefix, index);
let uri_key = format!("{}_MONGO_INSTANCES_{}_MONGO_URI", self.prefix, index);
if let (Ok(name), Ok(uri)) = (env::var(&name_key), env::var(&uri_key)) {
instances.push(MongoInstancesConfig {
name,
mongo: MongoConfig { uri },
});
index += 1;
} else {
break;
}
}
instances
}
/// 从环境变量中解析 S3 实例配置
pub fn parse_s3_instances(&self) -> Vec<S3InstancesConfig> {
let mut instances = Vec::new();
let mut index = 0;
loop {
let name_key = format!("{}_S3_INSTANCES_{}_NAME", self.prefix, index);
let region_key = format!("{}_S3_INSTANCES_{}_S3_REGION", self.prefix, index);
let access_key_id_key =
format!("{}_S3_INSTANCES_{}_S3_ACCESS_KEY_ID", self.prefix, index);
let secret_access_key_key = format!(
"{}_S3_INSTANCES_{}_S3_SECRET_ACCESS_KEY",
self.prefix, index
);
if let (Ok(name), Ok(region), Ok(access_key_id), Ok(secret_access_key)) = (
env::var(&name_key),
env::var(®ion_key),
env::var(&access_key_id_key),
env::var(&secret_access_key_key),
) {
let endpoint_key = format!("{}_S3_INSTANCES_{}_S3_ENDPOINT", self.prefix, index);
let endpoint = env::var(&endpoint_key).ok();
instances.push(S3InstancesConfig {
name,
s3: S3Config {
region,
access_key_id,
secret_access_key,
endpoint,
},
});
index += 1;
} else {
break;
}
}
instances
}
/// 检查是否有任何多实例环境变量
pub fn has_any_instances(&self) -> bool {
let patterns = [
format!("{}_DATABASE_INSTANCES_0_NAME", self.prefix),
format!("{}_REDIS_INSTANCES_0_NAME", self.prefix),
format!("{}_MONGO_INSTANCES_0_NAME", self.prefix),
format!("{}_S3_INSTANCES_0_NAME", self.prefix),
];
patterns.iter().any(|key| env::var(key).is_ok())
}
/// 打印所有找到的多实例配置(用于调试)
pub fn debug_print_instances(&self) {
let db_instances = self.parse_database_instances();
let redis_instances = self.parse_redis_instances();
let mongo_instances = self.parse_mongo_instances();
let s3_instances = self.parse_s3_instances();
if !db_instances.is_empty() {
println!(
"Found {} database instances from environment variables:",
db_instances.len()
);
for (i, instance) in db_instances.iter().enumerate() {
println!(" [{}] {} -> {}", i, instance.name, instance.database.url);
}
}
if !redis_instances.is_empty() {
println!(
"Found {} Redis instances from environment variables:",
redis_instances.len()
);
for (i, instance) in redis_instances.iter().enumerate() {
println!(" [{}] {} -> {:?}", i, instance.name, instance.redis.mode);
}
}
if !mongo_instances.is_empty() {
println!(
"Found {} MongoDB instances from environment variables:",
mongo_instances.len()
);
for (i, instance) in mongo_instances.iter().enumerate() {
println!(" [{}] {} -> {}", i, instance.name, instance.mongo.uri);
}
}
if !s3_instances.is_empty() {
println!(
"Found {} S3 instances from environment variables:",
s3_instances.len()
);
for (i, instance) in s3_instances.iter().enumerate() {
println!(" [{}] {} -> {}", i, instance.name, instance.s3.region);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
#[test]
fn test_parse_database_instances() {
// 设置测试环境变量
env::set_var("TEST_DATABASE_INSTANCES_0_NAME", "test_db");
env::set_var(
"TEST_DATABASE_INSTANCES_0_DATABASE_URL",
"postgres://test@localhost:5432/test",
);
env::set_var("TEST_DATABASE_INSTANCES_0_DATABASE_MAX_CONNECTIONS", "5");
env::set_var("TEST_DATABASE_INSTANCES_1_NAME", "analytics_db");
env::set_var(
"TEST_DATABASE_INSTANCES_1_DATABASE_URL",
"postgres://analytics@localhost:5432/analytics",
);
env::set_var("TEST_DATABASE_INSTANCES_1_DATABASE_MAX_CONNECTIONS", "10");
let processor = MultiInstanceEnvProcessor::new("TEST");
let instances = processor.parse_database_instances();
assert_eq!(instances.len(), 2);
assert_eq!(instances[0].name, "test_db");
assert_eq!(
instances[0].database.url,
"postgres://test@localhost:5432/test"
);
assert_eq!(instances[0].database.max_connections, 5);
assert_eq!(instances[1].name, "analytics_db");
assert_eq!(
instances[1].database.url,
"postgres://analytics@localhost:5432/analytics"
);
assert_eq!(instances[1].database.max_connections, 10);
// 清理环境变量
env::remove_var("TEST_DATABASE_INSTANCES_0_NAME");
env::remove_var("TEST_DATABASE_INSTANCES_0_DATABASE_URL");
env::remove_var("TEST_DATABASE_INSTANCES_0_DATABASE_MAX_CONNECTIONS");
env::remove_var("TEST_DATABASE_INSTANCES_1_NAME");
env::remove_var("TEST_DATABASE_INSTANCES_1_DATABASE_URL");
env::remove_var("TEST_DATABASE_INSTANCES_1_DATABASE_MAX_CONNECTIONS");
}
#[test]
fn test_parse_redis_instances() {
// 设置测试环境变量
env::set_var("TEST_REDIS_INSTANCES_0_NAME", "cache");
env::set_var("TEST_REDIS_INSTANCES_0_REDIS_MODE", "single");
env::set_var(
"TEST_REDIS_INSTANCES_0_REDIS_URL",
"redis://localhost:6379/0",
);
env::set_var("TEST_REDIS_INSTANCES_1_NAME", "cluster_cache");
env::set_var("TEST_REDIS_INSTANCES_1_REDIS_MODE", "cluster");
env::set_var(
"TEST_REDIS_INSTANCES_1_REDIS_URLS",
"redis://host1:7001,redis://host2:7002",
);
let processor = MultiInstanceEnvProcessor::new("TEST");
let instances = processor.parse_redis_instances();
assert_eq!(instances.len(), 2);
assert_eq!(instances[0].name, "cache");
assert_eq!(instances[0].redis.mode, RedisMode::Single);
assert_eq!(
instances[0].redis.url,
Some("redis://localhost:6379/0".to_string())
);
assert_eq!(instances[1].name, "cluster_cache");
assert_eq!(instances[1].redis.mode, RedisMode::Cluster);
assert_eq!(
instances[1].redis.urls,
Some(vec![
"redis://host1:7001".to_string(),
"redis://host2:7002".to_string()
])
);
// 清理环境变量
env::remove_var("TEST_REDIS_INSTANCES_0_NAME");
env::remove_var("TEST_REDIS_INSTANCES_0_REDIS_MODE");
env::remove_var("TEST_REDIS_INSTANCES_0_REDIS_URL");
env::remove_var("TEST_REDIS_INSTANCES_1_NAME");
env::remove_var("TEST_REDIS_INSTANCES_1_REDIS_MODE");
env::remove_var("TEST_REDIS_INSTANCES_1_REDIS_URLS");
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/env_config.rs | server/config/src/env_config.rs | use config::{Config as ConfigBuilder, ConfigError as ConfigBuilderError, Environment, File};
use serde::de::DeserializeOwned;
use std::path::Path;
use thiserror::Error;
use crate::{project_error, project_info};
#[derive(Error, Debug)]
pub enum EnvConfigError {
#[error("Config builder error: {0}")]
ConfigBuilder(#[from] ConfigBuilderError),
#[error("Unsupported file format: {0}")]
UnsupportedFormat(String),
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
}
/// 环境变量优先的配置加载器
///
/// 加载优先级:环境变量 > 配置文件 > 默认值
///
/// 环境变量命名规范:
/// - 使用 APP_ 前缀
/// - 嵌套配置用下划线分隔,如:APP_DATABASE_URL
/// - 数组配置用索引,如:APP_REDIS_INSTANCES_0_NAME
///
/// # 示例
/// ```rust,no_run
/// use server_config::env_config::EnvConfigLoader;
/// use server_config::Config;
///
/// let config: Config = EnvConfigLoader::new()
/// .with_file("examples/application.yaml")
/// .with_env_prefix("APP")
/// .load()
/// .expect("Failed to load config");
/// ```
pub struct EnvConfigLoader {
file_path: Option<String>,
env_prefix: String,
env_separator: String,
}
impl Default for EnvConfigLoader {
fn default() -> Self {
Self {
file_path: None,
env_prefix: "APP".to_string(),
env_separator: "_".to_string(),
}
}
}
impl EnvConfigLoader {
/// 创建新的配置加载器
pub fn new() -> Self {
Self::default()
}
/// 设置配置文件路径
pub fn with_file<P: AsRef<Path>>(mut self, path: P) -> Self {
self.file_path = Some(path.as_ref().to_string_lossy().to_string());
self
}
/// 设置环境变量前缀(默认为 "APP")
pub fn with_env_prefix<S: Into<String>>(mut self, prefix: S) -> Self {
self.env_prefix = prefix.into();
self
}
/// 设置环境变量分隔符(默认为 "_")
pub fn with_env_separator<S: Into<String>>(mut self, separator: S) -> Self {
self.env_separator = separator.into();
self
}
/// 加载配置
///
/// 按照以下优先级加载配置:
/// 1. 环境变量(最高优先级)
/// 2. 配置文件
/// 3. 默认值(最低优先级)
pub fn load<T>(&self) -> Result<T, EnvConfigError>
where
T: DeserializeOwned,
{
let mut builder = ConfigBuilder::builder();
// 1. 如果指定了配置文件,先加载文件配置
if let Some(file_path) = &self.file_path {
project_info!("Loading config from file: {}", file_path);
let file_format = self.detect_file_format(file_path)?;
builder = builder.add_source(File::with_name(file_path).format(file_format));
}
// 2. 加载环境变量配置(会覆盖文件配置)
project_info!(
"Loading config from environment variables with prefix: {}",
self.env_prefix
);
builder = builder.add_source(
Environment::with_prefix(&self.env_prefix)
.separator(&self.env_separator)
.try_parsing(true),
);
// 3. 构建最终配置
let config = builder.build()?;
// 4. 反序列化为目标类型
let result: T = config.try_deserialize()?;
project_info!(
"Configuration loaded successfully with environment variable override support"
);
Ok(result)
}
/// 检测文件格式
fn detect_file_format(&self, file_path: &str) -> Result<config::FileFormat, EnvConfigError> {
let extension = Path::new(file_path)
.extension()
.and_then(|ext| ext.to_str())
.unwrap_or("")
.to_lowercase();
match extension.as_str() {
"yaml" | "yml" => Ok(config::FileFormat::Yaml),
"toml" => Ok(config::FileFormat::Toml),
"json" => Ok(config::FileFormat::Json),
_ => {
project_error!("Unsupported file format: {}", extension);
Err(EnvConfigError::UnsupportedFormat(extension))
},
}
}
}
/// 便捷函数:从文件和环境变量加载配置
///
/// # 参数
/// - `file_path`: 配置文件路径
/// - `env_prefix`: 环境变量前缀(可选,默认为 "APP")
///
/// # 示例
/// ```rust,no_run
/// use server_config::env_config::load_config_with_env;
/// use server_config::Config;
///
/// let config: Config = load_config_with_env("examples/application.yaml", Some("APP"))
/// .expect("Failed to load config");
/// ```
pub fn load_config_with_env<T>(
file_path: &str,
env_prefix: Option<&str>,
) -> Result<T, EnvConfigError>
where
T: DeserializeOwned,
{
let mut loader = EnvConfigLoader::new().with_file(file_path);
if let Some(prefix) = env_prefix {
loader = loader.with_env_prefix(prefix);
}
loader.load()
}
/// 便捷函数:仅从环境变量加载配置
///
/// # 参数
/// - `env_prefix`: 环境变量前缀(可选,默认为 "APP")
///
/// # 示例
/// ```rust,no_run
/// use server_config::env_config::load_config_from_env;
/// use server_config::Config;
/// use std::env;
///
/// // 设置必需的环境变量
/// env::set_var("APP_DATABASE_URL", "postgres://user:pass@localhost/db");
/// env::set_var("APP_DATABASE_MAX_CONNECTIONS", "10");
/// env::set_var("APP_DATABASE_MIN_CONNECTIONS", "1");
/// env::set_var("APP_DATABASE_CONNECT_TIMEOUT", "30");
/// env::set_var("APP_DATABASE_IDLE_TIMEOUT", "600");
/// env::set_var("APP_SERVER_HOST", "0.0.0.0");
/// env::set_var("APP_SERVER_PORT", "8080");
/// env::set_var("APP_JWT_JWT_SECRET", "secret");
/// env::set_var("APP_JWT_ISSUER", "issuer");
/// env::set_var("APP_JWT_EXPIRE", "3600");
///
/// let config: Config = load_config_from_env(Some("APP"))
/// .expect("Failed to load config");
/// ```
pub fn load_config_from_env<T>(env_prefix: Option<&str>) -> Result<T, EnvConfigError>
where
T: DeserializeOwned,
{
let mut loader = EnvConfigLoader::new();
if let Some(prefix) = env_prefix {
loader = loader.with_env_prefix(prefix);
}
loader.load()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_env_config_loader_creation() {
let loader = EnvConfigLoader::new();
assert_eq!(loader.env_prefix, "APP");
assert_eq!(loader.env_separator, "_");
}
#[test]
fn test_env_config_loader_with_custom_prefix() {
let loader = EnvConfigLoader::new().with_env_prefix("CUSTOM");
assert_eq!(loader.env_prefix, "CUSTOM");
}
#[test]
fn test_env_config_loader_with_custom_separator() {
let loader = EnvConfigLoader::new().with_env_separator("__");
assert_eq!(loader.env_separator, "__");
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/model/config.rs | server/config/src/model/config.rs | use serde::Deserialize;
use super::{
DatabaseConfig, DatabasesInstancesConfig, JwtConfig, MongoConfig, MongoInstancesConfig,
RedisConfig, RedisInstancesConfig, S3Config, S3InstancesConfig, ServerConfig,
};
/// 应用程序配置结构
///
/// 这是应用程序的主配置结构,包含了所有子系统的配置信息
///
/// ## 配置加载优先级
/// 1. **环境变量**(最高优先级)
/// 2. **配置文件**(中等优先级)
/// 3. **默认值**(最低优先级)
///
/// ## 环境变量命名规范
/// - 使用 `APP_` 前缀
/// - 嵌套配置用下划线分隔,如:`APP_DATABASE_URL`
/// - 数组配置用索引,如:`APP_REDIS_INSTANCES_0_NAME`
///
/// ## 配置的加载和初始化过程
/// 1. 首先从配置文件(如 application.yaml)中加载整体配置
/// 2. 然后从环境变量中读取配置并覆盖文件配置
/// 3. 最后通过 `init_from_file_with_env` 函数将配置注入到全局状态中
/// ```rust,no_run
/// use server_global::global;
/// use server_config::{Config, DatabaseConfig, ServerConfig, JwtConfig, RedisConfig};
///
/// async fn init_config_example(config: Config) {
/// // 注入主配置
/// global::init_config::<Config>(config.clone()).await;
///
/// // 注入数据库配置
/// global::init_config::<DatabaseConfig>(config.database).await;
///
/// // 注入服务器配置
/// global::init_config::<ServerConfig>(config.server).await;
///
/// // 注入 JWT 配置
/// global::init_config::<JwtConfig>(config.jwt).await;
///
/// // 注入 Redis 配置(如果存在)
/// if let Some(redis_config) = config.redis {
/// global::init_config::<RedisConfig>(redis_config).await;
/// }
/// }
/// ```
///
/// # 配置项说明
///
/// - `database`: 主数据库配置,用于配置默认的数据库连接
/// - `database_instances`: 可选的数据库连接池配置,用于配置多个命名的数据库连接
/// - `server`: HTTP 服务器配置,包含监听地址和端口等
/// - `jwt`: JWT 认证配置,包含密钥和过期时间等
/// - `redis`: 主 Redis 配置,用于配置默认的 Redis 连接
/// - `redis_instances`: 可选的 Redis 连接池配置,用于配置多个命名的 Redis 连接
/// - `mongo`: 主 MongoDB 配置,用于配置默认的 MongoDB 连接
/// - `mongo_instances`: 可选的 MongoDB 连接池配置,用于配置多个命名的 MongoDB 连接
///
/// # 示例配置(YAML)
/// ```yaml
/// database:
/// url: "postgres://user:pass@localhost:5432/dbname"
/// max_connections: 10
///
/// database_instances:
/// - name: "other_db"
/// url: "postgres://user:pass@localhost:5432/other_db"
///
/// server:
/// host: "127.0.0.1"
/// port: 8080
///
/// jwt:
/// secret: "your-secret-key"
/// expire: 3600
///
/// redis:
/// mode: "single"
/// url: "redis://:password@localhost:6379/0"
///
/// redis_instances:
/// - name: "cache"
/// mode: "cluster"
/// urls:
/// - "redis://:password@localhost:6379"
/// - "redis://:password@localhost:6380"
/// ```
#[derive(Deserialize, Debug, Clone)]
pub struct Config {
/// 主数据库配置
pub database: DatabaseConfig,
/// 可选的数据库连接池配置
/// 用于配置多个命名的数据库连接
pub database_instances: Option<Vec<DatabasesInstancesConfig>>,
/// HTTP 服务器配置
pub server: ServerConfig,
/// JWT 认证配置
pub jwt: JwtConfig,
/// 主 Redis 配置
pub redis: Option<RedisConfig>,
/// 可选的 Redis 连接池配置
/// 用于配置多个命名的 Redis 连接
pub redis_instances: Option<Vec<RedisInstancesConfig>>,
/// 主 MongoDB 配置
pub mongo: Option<MongoConfig>,
/// 可选的 MongoDB 连接池配置
/// 用于配置多个命名的 MongoDB 连接
pub mongo_instances: Option<Vec<MongoInstancesConfig>>,
/// 主 S3 配置
pub s3: Option<S3Config>,
/// 可选的 S3 连接池配置
/// 用于配置多个命名的 S3 连接
pub s3_instances: Option<Vec<S3InstancesConfig>>,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/model/s3_config.rs | server/config/src/model/s3_config.rs | use serde::Deserialize;
/// S3 配置
///
/// 支持的环境变量:
/// - APP_S3_REGION: S3 区域
/// - APP_S3_ACCESS_KEY_ID: S3 访问密钥ID
/// - APP_S3_SECRET_ACCESS_KEY: S3 秘密访问密钥
/// - APP_S3_ENDPOINT: S3 端点URL (可选)
#[derive(Debug, Clone, Deserialize)]
pub struct S3Config {
/// S3 区域
/// 环境变量: APP_S3_REGION
pub region: String,
/// S3 访问密钥ID
/// 环境变量: APP_S3_ACCESS_KEY_ID
pub access_key_id: String,
/// S3 秘密访问密钥
/// 环境变量: APP_S3_SECRET_ACCESS_KEY
pub secret_access_key: String,
/// S3 端点URL (可选,用于自定义S3兼容服务)
/// 环境变量: APP_S3_ENDPOINT
pub endpoint: Option<String>,
}
/// S3 实例配置
///
/// 支持的环境变量(数组形式):
/// - APP_S3_INSTANCES_0_NAME: 第一个实例名称
/// - APP_S3_INSTANCES_0_S3_REGION: 第一个实例区域
/// - APP_S3_INSTANCES_0_S3_ACCESS_KEY_ID: 第一个实例访问密钥ID
/// - APP_S3_INSTANCES_0_S3_SECRET_ACCESS_KEY: 第一个实例秘密访问密钥
/// - APP_S3_INSTANCES_0_S3_ENDPOINT: 第一个实例端点URL
/// 以此类推...
#[derive(Debug, Clone, Deserialize)]
pub struct S3InstancesConfig {
/// 实例名称
pub name: String,
/// S3 配置
pub s3: S3Config,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/model/redis_config.rs | server/config/src/model/redis_config.rs | use serde::Deserialize;
/// Redis 配置
///
/// 支持的环境变量:
/// - APP_REDIS_MODE: Redis 模式 (single/cluster)
/// - APP_REDIS_URL: Redis 连接 URL (单机模式)
/// - APP_REDIS_URLS: Redis 集群节点地址列表 (逗号分隔)
#[derive(Debug, Clone, Deserialize)]
pub struct RedisConfig {
/// Redis 模式
/// 环境变量: APP_REDIS_MODE
pub mode: RedisMode,
/// Redis 连接 URL
/// 环境变量: APP_REDIS_URL
///
/// 支持以下格式:
/// 1. 标准 TCP 连接:
/// redis://[<username>][:<password>@]<hostname>[:port][/[<db>][?protocol=<protocol>]]
/// 示例:
/// - 基本连接:redis://127.0.0.1:6379/0
/// - 带密码:redis://:password@127.0.0.1:6379/0
/// - 带用户名和密码:redis://username:password@127.0.0.1:6379/0
///
/// 2. Unix Socket 连接 (如果系统支持):
/// redis+unix:///<path>[?db=<db>[&pass=<password>][&user=<username>][&protocol=<protocol>]]
/// 或
/// unix:///<path>[?db=<db>][&pass=<password>][&user=<username>][&protocol=<protocol>]]
pub url: Option<String>,
/// Redis 集群节点地址列表
/// 环境变量: APP_REDIS_URLS (逗号分隔的URL列表)
/// 每个地址都支持与 url 相同的格式
///
/// 注意:
/// - 集群模式下,db 参数将被忽略,因为 Redis 集群不支持多数据库
/// - 所有节点应使用相同的认证信息(用户名/密码)
pub urls: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, PartialEq)]
pub enum RedisMode {
#[serde(rename = "single")]
Single,
#[serde(rename = "cluster")]
Cluster,
}
/// Redis 实例配置
///
/// 支持的环境变量(数组形式):
/// - APP_REDIS_INSTANCES_0_NAME: 第一个实例名称
/// - APP_REDIS_INSTANCES_0_REDIS_MODE: 第一个实例模式
/// - APP_REDIS_INSTANCES_0_REDIS_URL: 第一个实例URL
/// - APP_REDIS_INSTANCES_1_NAME: 第二个实例名称
/// - APP_REDIS_INSTANCES_1_REDIS_MODE: 第二个实例模式
/// - APP_REDIS_INSTANCES_1_REDIS_URL: 第二个实例URL
/// 以此类推...
#[derive(Debug, Clone, Deserialize)]
pub struct RedisInstancesConfig {
/// 实例名称
pub name: String,
/// Redis 配置
pub redis: RedisConfig,
}
impl RedisConfig {
pub fn is_cluster(&self) -> bool {
self.mode == RedisMode::Cluster
}
pub fn get_url(&self) -> Option<String> {
match self.mode {
RedisMode::Single => self.url.clone(),
RedisMode::Cluster => None,
}
}
pub fn get_urls(&self) -> Option<Vec<String>> {
match self.mode {
RedisMode::Single => None,
RedisMode::Cluster => self.urls.clone(),
}
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/model/database_config.rs | server/config/src/model/database_config.rs | use serde::Deserialize;
/// 数据库配置
///
/// 支持的环境变量:
/// - APP_DATABASE_URL: 数据库连接URL
/// - APP_DATABASE_MAX_CONNECTIONS: 最大连接数
/// - APP_DATABASE_MIN_CONNECTIONS: 最小连接数
/// - APP_DATABASE_CONNECT_TIMEOUT: 连接超时时间(秒)
/// - APP_DATABASE_IDLE_TIMEOUT: 空闲超时时间(秒)
#[derive(Deserialize, Debug, Clone)]
pub struct DatabaseConfig {
/// 数据库连接URL
/// 环境变量: APP_DATABASE_URL
pub url: String,
/// 最大连接数
/// 环境变量: APP_DATABASE_MAX_CONNECTIONS
pub max_connections: u32,
/// 最小连接数
/// 环境变量: APP_DATABASE_MIN_CONNECTIONS
pub min_connections: u32,
/// 连接超时时间(秒)
/// 环境变量: APP_DATABASE_CONNECT_TIMEOUT
pub connect_timeout: u64,
/// 空闲超时时间(秒)
/// 环境变量: APP_DATABASE_IDLE_TIMEOUT
pub idle_timeout: u64,
}
/// 数据库实例配置
///
/// 支持的环境变量(数组形式):
/// - APP_DATABASE_INSTANCES_0_NAME: 第一个实例名称
/// - APP_DATABASE_INSTANCES_0_DATABASE_URL: 第一个实例数据库URL
/// - APP_DATABASE_INSTANCES_1_NAME: 第二个实例名称
/// - APP_DATABASE_INSTANCES_1_DATABASE_URL: 第二个实例数据库URL
/// 以此类推...
#[derive(Deserialize, Debug, Clone)]
pub struct DatabasesInstancesConfig {
/// 实例名称
pub name: String,
/// 数据库配置
pub database: DatabaseConfig,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/model/mod.rs | server/config/src/model/mod.rs | pub use config::Config;
pub use database_config::{DatabaseConfig, DatabasesInstancesConfig};
pub use jwt_config::JwtConfig;
pub use mongo_config::{MongoConfig, MongoInstancesConfig};
pub use redis_config::{RedisConfig, RedisInstancesConfig, RedisMode};
pub use s3_config::{S3Config, S3InstancesConfig};
pub use server_config::ServerConfig;
/// 可选配置集合的包装类
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct OptionalConfigs<T> {
pub configs: Option<Vec<T>>,
}
impl<T> From<Option<Vec<T>>> for OptionalConfigs<T> {
fn from(configs: Option<Vec<T>>) -> Self {
Self { configs }
}
}
mod config;
mod database_config;
mod jwt_config;
mod mongo_config;
mod redis_config;
mod s3_config;
mod server_config;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/model/jwt_config.rs | server/config/src/model/jwt_config.rs | use serde::Deserialize;
/// JWT 配置
///
/// 支持的环境变量:
/// - APP_JWT_JWT_SECRET: JWT 密钥
/// - APP_JWT_ISSUER: JWT 签发者
/// - APP_JWT_EXPIRE: JWT 过期时间(秒)
#[derive(Deserialize, Debug, Clone)]
pub struct JwtConfig {
/// JWT 密钥
/// 环境变量: APP_JWT_JWT_SECRET
pub jwt_secret: String,
/// JWT 签发者
/// 环境变量: APP_JWT_ISSUER
pub issuer: String,
/// JWT 过期时间(秒)
/// 环境变量: APP_JWT_EXPIRE
pub expire: i64,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/model/server_config.rs | server/config/src/model/server_config.rs | use serde::Deserialize;
/// 服务器配置
///
/// 支持的环境变量:
/// - APP_SERVER_HOST: 服务器监听地址
/// - APP_SERVER_PORT: 服务器监听端口
#[derive(Deserialize, Debug, Clone)]
pub struct ServerConfig {
/// 服务器监听地址
/// 环境变量: APP_SERVER_HOST
pub host: String,
/// 服务器监听端口
/// 环境变量: APP_SERVER_PORT
pub port: u32,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/config/src/model/mongo_config.rs | server/config/src/model/mongo_config.rs | use serde::Deserialize;
/// MongoDB 配置
///
/// 支持的环境变量:
/// - APP_MONGO_URI: MongoDB 连接 URI
#[derive(Debug, Clone, Deserialize)]
pub struct MongoConfig {
/// MongoDB 连接 URI
/// 环境变量: APP_MONGO_URI
/// 支持以下格式:
/// mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
///
/// 示例:
/// - 基本连接:mongodb://localhost:27017/mydb
/// - 带认证:mongodb://user:pass@localhost:27017/mydb
/// - 带参数:mongodb://localhost:27017/mydb?maxPoolSize=20&w=majority
pub uri: String,
}
/// MongoDB 实例配置
///
/// 支持的环境变量(数组形式):
/// - APP_MONGO_INSTANCES_0_NAME: 第一个实例名称
/// - APP_MONGO_INSTANCES_0_MONGO_URI: 第一个实例URI
/// - APP_MONGO_INSTANCES_1_NAME: 第二个实例名称
/// - APP_MONGO_INSTANCES_1_MONGO_URI: 第二个实例URI
/// 以此类推...
#[derive(Debug, Clone, Deserialize)]
pub struct MongoInstancesConfig {
/// 实例名称
pub name: String,
/// MongoDB 配置
pub mongo: MongoConfig,
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/lib.rs | server/router/src/lib.rs | pub mod admin;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/admin/sys_endpoint_route.rs | server/router/src/admin/sys_endpoint_route.rs | use axum::{http::Method, routing::get, Router};
use server_api::admin::SysEndpointApi;
use server_global::global::{add_route, RouteInfo};
pub struct SysEndpointRouter;
impl SysEndpointRouter {
pub async fn init_endpoint_router() -> Router {
let base_path = "/api-endpoint";
let service_name = "SysEndpointApi";
let routes = vec![
RouteInfo::new(base_path, Method::GET, service_name, "获取接口列表"),
RouteInfo::new(
&format!("{}/auth-api-endpoint/:roleCode", base_path),
Method::GET,
service_name,
"获取角色API权限",
),
RouteInfo::new(
&format!("{}/tree", base_path),
Method::GET,
service_name,
"获取接口树",
),
];
for route in routes {
add_route(route).await;
}
let router = Router::new()
.route("/", get(SysEndpointApi::get_paginated_endpoints))
.route(
"/auth-api-endpoint/{roleCode}",
get(SysEndpointApi::get_auth_endpoints),
)
.route("/tree", get(SysEndpointApi::tree_endpoint));
Router::new().nest(base_path, router)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/admin/sys_organization_route.rs | server/router/src/admin/sys_organization_route.rs | use axum::{http::Method, routing::get, Router};
use server_api::admin::SysOrganizationApi;
use server_global::global::{add_route, RouteInfo};
pub struct SysOrganizationRouter;
impl SysOrganizationRouter {
pub async fn init_organization_router() -> Router {
let base_path = "/org";
let service_name = "SysOrganizationApi";
let routes = vec![RouteInfo::new(
base_path,
Method::GET,
service_name,
"获取组织列表",
)];
for route in routes {
add_route(route).await;
}
let router = Router::new().route("/", get(SysOrganizationApi::get_paginated_organizations));
Router::new().nest(base_path, router)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/admin/sys_authentication_route.rs | server/router/src/admin/sys_authentication_route.rs | use axum::{
http::Method,
routing::{get, post},
Router,
};
use server_api::admin::SysAuthenticationApi;
use server_global::global::{add_route, RouteInfo};
pub struct SysAuthenticationRouter;
impl SysAuthenticationRouter {
pub async fn init_authentication_router() -> Router {
let router = Router::new().route("/login", post(SysAuthenticationApi::login_handler));
Router::new().nest("/auth", router)
}
pub async fn init_protected_router() -> Router {
let router = Router::new()
.route("/getUserInfo", get(SysAuthenticationApi::get_user_info))
.route("/getUserRoutes", get(SysAuthenticationApi::get_user_routes));
Router::new().nest("/auth", router)
}
pub async fn init_authorization_router() -> Router {
let base_path = "/authorization";
let service_name = "SysAuthorizationApi";
let routes = vec![
RouteInfo::new(
&format!("{}/assign-permission", base_path),
Method::POST,
service_name,
"分配权限",
),
RouteInfo::new(
&format!("{}/assign-routes", base_path),
Method::POST,
service_name,
"分配路由",
),
];
for route in routes {
add_route(route).await;
}
let authorization_router = Router::new()
.route("/getUserRoutes", get(SysAuthenticationApi::get_user_routes))
.route(
"/assign-permission",
post(SysAuthenticationApi::assign_permission),
)
.route("/assign-routes", post(SysAuthenticationApi::assign_routes));
Router::new().nest(base_path, authorization_router)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/admin/sys_domain_route.rs | server/router/src/admin/sys_domain_route.rs | use axum::{
http::Method,
routing::{delete, get, post, put},
Router,
};
use server_api::admin::SysDomainApi;
use server_global::global::{add_route, RouteInfo};
pub struct SysDomainRouter;
impl SysDomainRouter {
pub async fn init_domain_router() -> Router {
let base_path = "/domain";
let service_name = "SysDomainApi";
let routes = vec![
RouteInfo::new(base_path, Method::GET, service_name, "获取域名列表"),
RouteInfo::new(base_path, Method::POST, service_name, "创建域名"),
RouteInfo::new(
&format!("{}/:id", base_path),
Method::GET,
service_name,
"获取域名详情",
),
RouteInfo::new(base_path, Method::PUT, service_name, "更新域名"),
RouteInfo::new(
&format!("{}/:id", base_path),
Method::DELETE,
service_name,
"删除域名",
),
];
for route in routes {
add_route(route).await;
}
let router = Router::new()
.route("/", get(SysDomainApi::get_paginated_domains))
.route("/", post(SysDomainApi::create_domain))
.route("/{id}", get(SysDomainApi::get_domain))
.route("/", put(SysDomainApi::update_domain))
.route("/{id}", delete(SysDomainApi::delete_domain));
Router::new().nest(base_path, router)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/admin/sys_login_log_route.rs | server/router/src/admin/sys_login_log_route.rs | use axum::{http::Method, routing::get, Router};
use server_api::admin::SysLoginLogApi;
use server_global::global::{add_route, RouteInfo};
pub struct SysLoginLogRouter;
impl SysLoginLogRouter {
pub async fn init_login_log_router() -> Router {
let base_path = "/login-log";
let service_name = "SysLoginLogApi";
let routes = vec![RouteInfo::new(
base_path,
Method::GET,
service_name,
"获取登录日志列表",
)];
for route in routes {
add_route(route).await;
}
let router = Router::new().route("/", get(SysLoginLogApi::get_paginated_login_logs));
Router::new().nest(base_path, router)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/admin/sys_role_route.rs | server/router/src/admin/sys_role_route.rs | use axum::{
http::Method,
routing::{delete, get, post, put},
Router,
};
use server_api::admin::SysRoleApi;
use server_global::global::{add_route, RouteInfo};
pub struct SysRoleRouter;
impl SysRoleRouter {
pub async fn init_role_router() -> Router {
let base_path = "/role";
let service_name = "SysRoleApi";
let routes = vec![
RouteInfo::new(base_path, Method::GET, service_name, "获取角色列表"),
RouteInfo::new(base_path, Method::POST, service_name, "创建角色"),
RouteInfo::new(
&format!("{}/:id", base_path),
Method::GET,
service_name,
"获取角色详情",
),
RouteInfo::new(base_path, Method::PUT, service_name, "更新角色"),
RouteInfo::new(
&format!("{}/:id", base_path),
Method::DELETE,
service_name,
"删除角色",
),
];
for route in routes {
add_route(route).await;
}
let router = Router::new()
.route("/", get(SysRoleApi::get_paginated_roles))
.route("/", post(SysRoleApi::create_role))
.route("/{id}", get(SysRoleApi::get_role))
.route("/", put(SysRoleApi::update_role))
.route("/{id}", delete(SysRoleApi::delete_role));
Router::new().nest(base_path, router)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/admin/mod.rs | server/router/src/admin/mod.rs | pub use sys_access_key_route::SysAccessKeyRouter;
pub use sys_authentication_route::SysAuthenticationRouter;
pub use sys_domain_route::SysDomainRouter;
pub use sys_endpoint_route::SysEndpointRouter;
pub use sys_login_log_route::SysLoginLogRouter;
pub use sys_menu_route::SysMenuRouter;
pub use sys_operation_log_route::SysOperationLogRouter;
pub use sys_organization_route::SysOrganizationRouter;
pub use sys_role_route::SysRoleRouter;
pub use sys_sandbox_route::SysSandboxRouter;
pub use sys_user_route::SysUserRouter;
mod sys_access_key_route;
mod sys_authentication_route;
mod sys_domain_route;
mod sys_endpoint_route;
mod sys_login_log_route;
mod sys_menu_route;
mod sys_operation_log_route;
mod sys_organization_route;
mod sys_role_route;
mod sys_sandbox_route;
mod sys_user_route;
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
soybeanjs/soybean-admin-rust | https://github.com/soybeanjs/soybean-admin-rust/blob/a560191ee087ba509e2060f17937b9f2c8f9be33/server/router/src/admin/sys_operation_log_route.rs | server/router/src/admin/sys_operation_log_route.rs | use axum::{http::Method, routing::get, Router};
use server_api::admin::SysOperationLogApi;
use server_global::global::{add_route, RouteInfo};
pub struct SysOperationLogRouter;
impl SysOperationLogRouter {
pub async fn init_operation_log_router() -> Router {
let base_path = "/operation-log";
let service_name = "SysOperationLogApi";
let routes = vec![RouteInfo::new(
base_path,
Method::GET,
service_name,
"获取操作日志列表",
)];
for route in routes {
add_route(route).await;
}
let router =
Router::new().route("/", get(SysOperationLogApi::get_paginated_operation_logs));
Router::new().nest(base_path, router)
}
}
| rust | Apache-2.0 | a560191ee087ba509e2060f17937b9f2c8f9be33 | 2026-01-04T20:21:43.261270Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.