use crate::error::{GarrisonError, GarrisonResult};
use dbnexus::sea_orm::{QueryResult, Value};
use dbnexus::DbPool;
mod auth_method_repo;
mod login_log_repo;
mod password_history_repo;
mod permission_repo;
mod role_permission_repo;
mod role_repo;
mod session_repo;
mod user_device_repo;
mod user_ext_repo;
mod user_identifier_repo;
mod user_repo;
mod user_role_repo;
mod webauthn_credential_repo;
fn v_str(s: &str) -> Value {
Value::String(Some(s.to_string()))
}
fn v_opt_str(s: &Option<String>) -> Value {
Value::String(s.clone())
}
fn v_i64(n: i64) -> Value {
Value::BigInt(Some(n))
}
fn v_bool(b: bool) -> Value {
Value::BigInt(Some(if b { 1 } else { 0 }))
}
pub(crate) fn now_timestamp() -> String {
chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string()
}
fn read_bool(row: &QueryResult, col: &str) -> GarrisonResult<bool> {
row.try_get::<i64>("", col)
.map(|v| v != 0)
.map_err(|e| GarrisonError::Dao(format!("dao-repo-read-bool::{}::{}", col, e)))
}
pub struct DbnexusUserRepository {
pool: DbPool,
}
pub struct DbnexusRoleRepository {
pool: DbPool,
}
pub struct DbnexusPermissionRepository {
pool: DbPool,
}
pub struct DbnexusUserRoleRepository {
pool: DbPool,
}
pub struct DbnexusRolePermissionRepository {
pool: DbPool,
}
pub struct DbnexusAuthMethodRepository {
pool: DbPool,
}
pub struct DbnexusSessionRepository {
pool: DbPool,
}
pub struct DbnexusLoginLogRepository {
pool: DbPool,
}
pub struct DbnexusUserExtRepository {
pool: DbPool,
}
pub struct DbnexusUserIdentifierRepository {
pool: DbPool,
}
pub struct DbnexusUserDeviceRepository {
pool: DbPool,
}
pub struct DbnexusWebauthnCredentialRepository {
pool: DbPool,
}
pub struct DbnexusPasswordHistoryRepository {
pool: DbPool,
}
#[cfg(all(test, feature = "db-sqlite"))]
pub(crate) mod test_support {
use crate::dao::{init_dbnexus, GarrisonMigration};
use dbnexus::DbPool;
use std::path::PathBuf;
pub fn project_migrations_dir() -> PathBuf {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
PathBuf::from(manifest_dir)
.join("migrations")
.join("sqlite")
}
pub async fn setup_db() -> DbPool {
if std::env::var("GARRISON_TEST_SQLITE_MEMORY").as_deref() == Ok("1") {
let url = format!(
"sqlite:file:garrison_test_mem_{}?mode=memory&cache=shared",
uuid::Uuid::new_v4()
);
let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
let migration =
GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
let applied = migration.migrate_core().await.expect("migrate_core 应成功");
assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
return pool;
}
let db_path = std::env::temp_dir()
.join(format!("garrison_test_{}.db", uuid::Uuid::new_v4()))
.to_string_lossy()
.replace('\\', "/");
std::fs::File::create(&db_path).expect("创建测试库文件应成功");
let url = format!("sqlite://{db_path}");
let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
let migration = GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
let applied = migration.migrate_core().await.expect("migrate_core 应成功");
assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
pool
}
}
#[cfg(all(test, feature = "db-sqlite"))]
mod tests {
use super::*;
use crate::dao::repository::*;
use crate::dao::{init_dbnexus, GarrisonMigration};
use std::path::PathBuf;
fn project_migrations_dir() -> PathBuf {
let manifest_dir = env!("CARGO_MANIFEST_DIR");
PathBuf::from(manifest_dir)
.join("migrations")
.join("sqlite")
}
async fn setup_db() -> DbPool {
if std::env::var("GARRISON_TEST_SQLITE_MEMORY").as_deref() == Ok("1") {
let url = format!(
"sqlite:file:garrison_test_mem_{}?mode=memory&cache=shared",
uuid::Uuid::new_v4()
);
let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
let migration =
GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
let applied = migration.migrate_core().await.expect("migrate_core 应成功");
assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
return pool;
}
let db_path = std::env::temp_dir()
.join(format!("garrison_test_{}.db", uuid::Uuid::new_v4()))
.to_string_lossy()
.replace('\\', "/");
std::fs::File::create(&db_path).expect("创建测试库文件应成功");
let url = format!("sqlite://{db_path}");
let pool = init_dbnexus(&url).await.expect("init_dbnexus 应成功");
let migration = GarrisonMigration::with_base_dir(pool.clone(), project_migrations_dir());
let applied = migration.migrate_core().await.expect("migrate_core 应成功");
assert!(applied >= 1, "migrate_core 应至少执行 1 个文件");
pool
}
#[tokio::test(flavor = "multi_thread")]
async fn repository_filters_by_tenant_id_when_tenant_isolation_enabled() {
let pool = setup_db().await;
let repo = DbnexusUserRepository::new(pool);
let user_42 = repo
.create(
42,
NewUser {
username: "tenant-42-user".to_string(),
password_hash: "$argon2id$m=8,t=1,p=1$x".to_string(),
status: "active".to_string(),
},
)
.await
.expect("create tenant 42 用户应成功");
let user_1 = repo
.create(
1,
NewUser {
username: "tenant-1-user".to_string(),
password_hash: "$argon2id$m=8,t=1,p=1$x".to_string(),
status: "active".to_string(),
},
)
.await
.expect("create tenant 1 用户应成功");
let cross = repo.find_by_id(42, &user_1).await.unwrap();
assert!(
cross.is_none(),
"tenant 42 不应查到 tenant 1 的用户(SQL 过滤生效)"
);
let cross = repo.find_by_id(1, &user_42).await.unwrap();
assert!(
cross.is_none(),
"tenant 1 不应查到 tenant 42 的用户(SQL 过滤生效)"
);
let cross = repo.find_by_username(42, "tenant-1-user").await.unwrap();
assert!(
cross.is_none(),
"tenant 42 不应查到 tenant 1 的 username(SQL 过滤生效)"
);
let list_42 = repo.list(42, 0, 100).await.unwrap();
let list_1 = repo.list(1, 0, 100).await.unwrap();
let ids_42: Vec<_> = list_42.iter().map(|u| u.id.clone()).collect();
let ids_1: Vec<_> = list_1.iter().map(|u| u.id.clone()).collect();
assert!(
ids_42.contains(&user_42) && !ids_42.contains(&user_1),
"tenant 42 list 应仅含本租户用户"
);
assert!(
ids_1.contains(&user_1) && !ids_1.contains(&user_42),
"tenant 1 list 应仅含本租户用户"
);
let row_42 = repo.find_by_id(42, &user_42).await.unwrap().unwrap();
assert_eq!(row_42.tenant_id, 42, "返回行 tenant_id 应为 42");
}
#[tokio::test(flavor = "multi_thread")]
async fn create_generates_valid_uuid_v4() {
let pool = setup_db().await;
let repo = DbnexusUserRepository::new(pool);
let id = repo
.create(
42,
NewUser {
username: "uuid-test".to_string(),
password_hash: "$argon2id$m=8,t=1,p=1$x".to_string(),
status: "active".to_string(),
},
)
.await
.expect("create 应成功并返回 UUID v4");
let parsed = uuid::Uuid::parse_str(&id).expect("返回的 id 应为合法 UUID");
assert_eq!(
parsed.get_version(),
Some(uuid::Version::Random),
"返回的 id 应为 UUID v4,实际: {}",
id
);
}
#[tokio::test]
async fn user_identifier_register_conflict_returns_taken() {
let pool = setup_db().await;
let repo = DbnexusUserIdentifierRepository::new(pool);
let first = repo
.register(0, "phone", "13800001234", "user-aaa")
.await
.unwrap();
assert_eq!(first, RegisterOutcome::Registered);
let second = repo
.register(0, "phone", "13800001234", "user-bbb")
.await
.unwrap();
assert_eq!(
second,
RegisterOutcome::Taken {
by_user_id: "user-aaa".to_string()
}
);
let owner = repo.find_owner("phone", "13800001234").await.unwrap();
assert_eq!(owner.as_deref(), Some("user-aaa"));
let none = repo.find_owner("phone", "13900000000").await.unwrap();
assert!(none.is_none());
}
}