use crate::error::GarrisonResult;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserRow {
pub id: String,
pub username: String,
pub password_hash: String,
pub status: String,
pub tenant_id: i64,
pub created_at: String,
pub updated_at: String,
pub last_login_at: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserListRow {
pub id: String,
pub username: String,
pub status: String,
pub tenant_id: i64,
pub created_at: String,
pub updated_at: String,
pub last_login_at: Option<String>,
}
#[derive(Debug, Clone)]
pub struct NewUser {
pub username: String,
pub password_hash: String,
pub status: String,
}
#[derive(Debug, Clone, Default)]
pub struct UpdateUser {
pub username: Option<String>,
pub password_hash: Option<String>,
pub status: Option<String>,
pub last_login_at: Option<String>,
}
mod hash_import;
pub use hash_import::{
validate_imported_hash, ARGON2_IMPORT_MAX_M_COST, ARGON2_IMPORT_MAX_P, ARGON2_IMPORT_MAX_T,
BCRYPT_IMPORT_MAX_COST,
};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoleRow {
pub id: String,
pub code: String,
pub name: String,
pub description: Option<String>,
pub tenant_id: i64,
pub is_system: bool,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone)]
pub struct NewRole {
pub code: String,
pub name: String,
pub description: Option<String>,
pub is_system: bool,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PermissionRow {
pub id: String,
pub code: String,
pub name: String,
pub resource_type: Option<String>,
pub action: Option<String>,
pub created_at: String,
pub updated_at: String,
}
#[derive(Debug, Clone)]
pub struct NewPermission {
pub code: String,
pub name: String,
pub resource_type: Option<String>,
pub action: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserRoleRow {
pub user_id: String,
pub role_id: String,
pub scope: Option<String>,
pub grant_time: String,
pub tenant_id: i64,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RolePermissionRow {
pub role_id: String,
pub permission_id: String,
pub tenant_id: i64,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AuthMethodRow {
pub id: String,
pub user_id: String,
pub method_type: String,
pub external_id: Option<String>,
pub metadata: Option<String>,
pub create_time: String,
pub tenant_id: i64,
}
#[derive(Debug, Clone)]
pub struct NewAuthMethod {
pub user_id: String,
pub method_type: String,
pub external_id: Option<String>,
pub metadata: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SessionRow {
pub session_id: String,
pub user_id: String,
pub device_id: Option<String>,
pub ip: Option<String>,
pub user_agent: Option<String>,
pub login_time: String,
pub last_active: String,
pub expire_time: Option<String>,
pub tenant_id: i64,
}
#[derive(Debug, Clone)]
pub struct NewSession {
pub session_id: String,
pub user_id: String,
pub device_id: Option<String>,
pub ip: Option<String>,
pub user_agent: Option<String>,
pub expire_time: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct LoginLogRow {
pub id: String,
pub user_id: Option<String>,
pub action: String,
pub ip: Option<String>,
pub device_id: Option<String>,
pub success: bool,
pub fail_reason: Option<String>,
pub create_time: String,
pub tenant_id: i64,
}
#[derive(Debug, Clone)]
pub struct NewLoginLog {
pub user_id: Option<String>,
pub action: String,
pub ip: Option<String>,
pub device_id: Option<String>,
pub success: bool,
pub fail_reason: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserExtRow {
pub id: String,
pub user_id: String,
pub field_key: String,
pub field_value: Option<String>,
pub field_type: String,
pub created_at: String,
pub updated_at: String,
pub tenant_id: i64,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct UserDeviceRow {
pub id: String,
pub tenant_id: i64,
pub login_id: String,
pub device_identifier: String,
pub device_name: Option<String>,
pub user_agent: Option<String>,
pub is_blocked: bool,
pub last_seen_at: Option<i64>,
pub created_at: i64,
}
#[async_trait::async_trait]
pub trait UserRepository: Send + Sync {
async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<UserRow>>;
async fn find_by_username(
&self,
tenant_id: i64,
username: &str,
) -> GarrisonResult<Option<UserRow>>;
async fn create(&self, tenant_id: i64, user: NewUser) -> GarrisonResult<String>;
async fn update(&self, tenant_id: i64, id: &str, user: UpdateUser) -> GarrisonResult<()>;
async fn delete(&self, tenant_id: i64, id: &str) -> GarrisonResult<()>;
async fn list(
&self,
tenant_id: i64,
offset: i64,
limit: i64,
) -> GarrisonResult<Vec<UserListRow>>;
}
#[async_trait::async_trait]
pub trait RoleRepository: Send + Sync {
async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<RoleRow>>;
async fn find_by_code(&self, tenant_id: i64, code: &str) -> GarrisonResult<Option<RoleRow>>;
async fn create(&self, tenant_id: i64, role: NewRole) -> GarrisonResult<String>;
async fn update(
&self,
tenant_id: i64,
id: &str,
code: Option<String>,
name: Option<String>,
description: Option<String>,
) -> GarrisonResult<()>;
async fn delete(&self, tenant_id: i64, id: &str) -> GarrisonResult<()>;
async fn list(&self, tenant_id: i64, offset: i64, limit: i64) -> GarrisonResult<Vec<RoleRow>>;
}
#[async_trait::async_trait]
pub trait PermissionRepository: Send + Sync {
async fn find_by_id(&self, id: &str) -> GarrisonResult<Option<PermissionRow>>;
async fn find_by_code(&self, code: &str) -> GarrisonResult<Option<PermissionRow>>;
async fn create(&self, permission: NewPermission) -> GarrisonResult<String>;
async fn update(
&self,
id: &str,
name: Option<String>,
resource_type: Option<String>,
action: Option<String>,
) -> GarrisonResult<()>;
async fn delete(&self, id: &str) -> GarrisonResult<()>;
async fn list(&self, offset: i64, limit: i64) -> GarrisonResult<Vec<PermissionRow>>;
}
#[async_trait::async_trait]
pub trait UserRoleRepository: Send + Sync {
async fn find_by_user_id(
&self,
tenant_id: i64,
user_id: &str,
) -> GarrisonResult<Vec<UserRoleRow>>;
async fn find_by_role_id(
&self,
tenant_id: i64,
role_id: &str,
) -> GarrisonResult<Vec<UserRoleRow>>;
async fn assign(
&self,
tenant_id: i64,
user_id: &str,
role_id: &str,
scope: Option<String>,
) -> GarrisonResult<()>;
async fn revoke(&self, tenant_id: i64, user_id: &str, role_id: &str) -> GarrisonResult<()>;
async fn list(
&self,
tenant_id: i64,
offset: i64,
limit: i64,
) -> GarrisonResult<Vec<UserRoleRow>>;
}
#[async_trait::async_trait]
pub trait RolePermissionRepository: Send + Sync {
async fn find_by_role_id(
&self,
tenant_id: i64,
role_id: &str,
) -> GarrisonResult<Vec<RolePermissionRow>>;
async fn find_by_permission_id(
&self,
tenant_id: i64,
permission_id: &str,
) -> GarrisonResult<Vec<RolePermissionRow>>;
async fn assign(
&self,
tenant_id: i64,
role_id: &str,
permission_id: &str,
) -> GarrisonResult<()>;
async fn revoke(
&self,
tenant_id: i64,
role_id: &str,
permission_id: &str,
) -> GarrisonResult<()>;
async fn list(
&self,
tenant_id: i64,
offset: i64,
limit: i64,
) -> GarrisonResult<Vec<RolePermissionRow>>;
}
#[async_trait::async_trait]
pub trait AuthMethodRepository: Send + Sync {
async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<AuthMethodRow>>;
async fn find_by_user_id(
&self,
tenant_id: i64,
user_id: &str,
) -> GarrisonResult<Vec<AuthMethodRow>>;
async fn create(&self, tenant_id: i64, method: NewAuthMethod) -> GarrisonResult<String>;
async fn delete(&self, tenant_id: i64, id: &str) -> GarrisonResult<()>;
async fn list(
&self,
tenant_id: i64,
offset: i64,
limit: i64,
) -> GarrisonResult<Vec<AuthMethodRow>>;
}
#[async_trait::async_trait]
pub trait SessionRepository: Send + Sync {
async fn find_by_session_id(
&self,
tenant_id: i64,
session_id: &str,
) -> GarrisonResult<Option<SessionRow>>;
async fn find_by_user_id(
&self,
tenant_id: i64,
user_id: &str,
) -> GarrisonResult<Vec<SessionRow>>;
async fn create(&self, tenant_id: i64, session: NewSession) -> GarrisonResult<String>;
async fn update_last_active(&self, tenant_id: i64, session_id: &str) -> GarrisonResult<()>;
async fn delete(&self, tenant_id: i64, session_id: &str) -> GarrisonResult<()>;
async fn list(
&self,
tenant_id: i64,
offset: i64,
limit: i64,
) -> GarrisonResult<Vec<SessionRow>>;
}
#[async_trait::async_trait]
pub trait LoginLogRepository: Send + Sync {
async fn find_by_id(&self, tenant_id: i64, id: &str) -> GarrisonResult<Option<LoginLogRow>>;
async fn find_by_user_id(
&self,
tenant_id: i64,
user_id: &str,
offset: i64,
limit: i64,
) -> GarrisonResult<Vec<LoginLogRow>>;
async fn create(&self, tenant_id: i64, log: NewLoginLog) -> GarrisonResult<String>;
async fn list(
&self,
tenant_id: i64,
offset: i64,
limit: i64,
) -> GarrisonResult<Vec<LoginLogRow>>;
}
#[async_trait::async_trait]
pub trait UserExtRepository: Send + Sync {
async fn find_by_user_id(
&self,
tenant_id: i64,
user_id: &str,
) -> GarrisonResult<Vec<UserExtRow>>;
async fn find_by_user_and_key(
&self,
tenant_id: i64,
user_id: &str,
field_key: &str,
) -> GarrisonResult<Option<UserExtRow>>;
async fn upsert(
&self,
tenant_id: i64,
user_id: &str,
field_key: &str,
field_value: Option<String>,
field_type: &str,
) -> GarrisonResult<()>;
async fn delete(&self, tenant_id: i64, user_id: &str, field_key: &str) -> GarrisonResult<()>;
async fn list(
&self,
tenant_id: i64,
offset: i64,
limit: i64,
) -> GarrisonResult<Vec<UserExtRow>>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegisterOutcome {
Registered,
Taken {
by_user_id: String,
},
}
#[async_trait::async_trait]
pub trait UserIdentifierRepository: Send + Sync {
async fn register(
&self,
tenant_id: i64,
id_type: &str,
id_value: &str,
user_id: &str,
) -> GarrisonResult<RegisterOutcome>;
async fn find_owner(&self, id_type: &str, id_value: &str) -> GarrisonResult<Option<String>>;
async fn find_owner_in_tenant(
&self,
tenant_id: i64,
id_type: &str,
id_value: &str,
) -> GarrisonResult<Option<String>>;
}
pub const MAX_DEVICES: usize = 5;
#[async_trait::async_trait]
pub trait UserDeviceRepository: Send + Sync {
async fn register_device(
&self,
tenant_id: i64,
login_id: &str,
identifier: &str,
ua: &str,
) -> GarrisonResult<String>;
async fn block_device(&self, tenant_id: i64, device_id: &str) -> GarrisonResult<()>;
async fn unblock_device(&self, tenant_id: i64, device_id: &str) -> GarrisonResult<()>;
async fn list_user_devices(
&self,
tenant_id: i64,
login_id: &str,
) -> GarrisonResult<Vec<UserDeviceRow>>;
async fn count_user_devices(&self, tenant_id: i64, login_id: &str) -> GarrisonResult<usize>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WebauthnBindOutcome {
Bound,
AlreadyBound {
by_user_id: String,
},
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct WebauthnCredentialRow {
pub tenant_id: i64,
pub user_id: String,
pub credential_id: String,
pub public_key: String,
pub sign_count: u32,
pub backup_eligible: bool,
pub backup_state: bool,
pub attestation: Option<String>,
pub created_at: i64,
pub updated_at: i64,
}
#[async_trait::async_trait]
pub trait WebauthnCredentialRepository: Send + Sync {
async fn create(&self, row: &WebauthnCredentialRow) -> GarrisonResult<WebauthnBindOutcome>;
async fn find_by_credential_id(
&self,
tenant_id: i64,
credential_id: &str,
) -> GarrisonResult<Option<WebauthnCredentialRow>>;
async fn list_by_user(
&self,
tenant_id: i64,
user_id: &str,
) -> GarrisonResult<Vec<WebauthnCredentialRow>>;
async fn update_authenticator_state(
&self,
tenant_id: i64,
credential_id: &str,
sign_count: u32,
backup_eligible: bool,
backup_state: bool,
) -> GarrisonResult<()>;
async fn delete(&self, tenant_id: i64, credential_id: &str) -> GarrisonResult<()>;
}
#[async_trait::async_trait]
pub trait PasswordHistoryRepository: Send + Sync {
async fn append(
&self,
tenant_id: i64,
user_id: &str,
password_hash: &str,
) -> GarrisonResult<()>;
async fn recent(
&self,
tenant_id: i64,
user_id: &str,
limit: u32,
) -> GarrisonResult<Vec<String>>;
}
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub mod sqlite;
#[cfg(feature = "db-postgres")]
pub mod postgres;
#[cfg(feature = "db-mysql")]
pub mod mysql;
pub mod role_hierarchy;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
mod dialect;
#[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
pub use dialect::{convert_placeholders, make_statement};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn user_row_constructs_with_all_fields() {
let row = UserRow {
id: "u-001".to_string(),
username: "alice".to_string(),
password_hash: "$argon2id$...".to_string(),
status: "active".to_string(),
tenant_id: 0,
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
last_login_at: None,
};
assert_eq!(row.id, "u-001");
assert_eq!(row.username, "alice");
assert_eq!(row.status, "active");
}
#[test]
fn role_row_constructs_with_is_system_false() {
let row = RoleRow {
id: "r-001".to_string(),
code: "admin".to_string(),
name: "Administrator".to_string(),
description: None,
tenant_id: 0,
is_system: false,
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
};
assert_eq!(row.code, "admin");
assert!(!row.is_system);
}
#[test]
fn permission_row_constructs_without_tenant_id() {
let row = PermissionRow {
id: "p-001".to_string(),
code: "user:read".to_string(),
name: "Read User".to_string(),
resource_type: Some("user".to_string()),
action: Some("read".to_string()),
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
};
assert_eq!(row.code, "user:read");
}
#[test]
fn user_role_row_constructs() {
let row = UserRoleRow {
user_id: "u-001".to_string(),
role_id: "r-001".to_string(),
scope: None,
grant_time: "2026-07-04T00:00:00Z".to_string(),
tenant_id: 0,
};
assert_eq!(row.user_id, "u-001");
}
#[test]
fn role_permission_row_constructs() {
let row = RolePermissionRow {
role_id: "r-001".to_string(),
permission_id: "p-001".to_string(),
tenant_id: 0,
};
assert_eq!(row.role_id, "r-001");
}
#[test]
fn auth_method_row_constructs() {
let row = AuthMethodRow {
id: "am-001".to_string(),
user_id: "u-001".to_string(),
method_type: "password".to_string(),
external_id: None,
metadata: None,
create_time: "2026-07-04T00:00:00Z".to_string(),
tenant_id: 0,
};
assert_eq!(row.method_type, "password");
}
#[test]
fn session_row_constructs() {
let row = SessionRow {
session_id: "sess-001".to_string(),
user_id: "u-001".to_string(),
device_id: Some("web".to_string()),
ip: Some("127.0.0.1".to_string()),
user_agent: None,
login_time: "2026-07-04T00:00:00Z".to_string(),
last_active: "2026-07-04T00:00:00Z".to_string(),
expire_time: None,
tenant_id: 0,
};
assert_eq!(row.session_id, "sess-001");
}
#[test]
fn login_log_row_constructs_with_success_true() {
let row = LoginLogRow {
id: "log-001".to_string(),
user_id: Some("u-001".to_string()),
action: "login".to_string(),
ip: Some("127.0.0.1".to_string()),
device_id: None,
success: true,
fail_reason: None,
create_time: "2026-07-04T00:00:00Z".to_string(),
tenant_id: 0,
};
assert!(row.success);
assert_eq!(row.action, "login");
}
#[test]
fn user_ext_row_constructs() {
let row = UserExtRow {
id: "ext-001".to_string(),
user_id: "u-001".to_string(),
field_key: "email".to_string(),
field_value: Some("alice@example.com".to_string()),
field_type: "string".to_string(),
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
tenant_id: 0,
};
assert_eq!(row.field_key, "email");
}
#[test]
fn user_device_row_constructs() {
let row = UserDeviceRow {
id: "dev-001".to_string(),
tenant_id: 42,
login_id: "1001".to_string(),
device_identifier: "ua-hash-abc".to_string(),
device_name: Some("Chrome on Windows".to_string()),
user_agent: Some("Mozilla/5.0 (Windows NT 10.0)".to_string()),
is_blocked: false,
last_seen_at: Some(1750000000),
created_at: 1749000000,
};
assert_eq!(row.id, "dev-001");
assert_eq!(row.tenant_id, 42);
assert_eq!(row.login_id, "1001");
assert_eq!(row.device_identifier, "ua-hash-abc");
assert!(!row.is_blocked);
}
#[test]
fn max_devices_is_five() {
assert_eq!(MAX_DEVICES, 5);
}
#[test]
fn new_user_constructs() {
let new = NewUser {
username: "alice".to_string(),
password_hash: "$argon2id$...".to_string(),
status: "active".to_string(),
};
assert_eq!(new.username, "alice");
}
#[test]
fn new_role_constructs() {
let new = NewRole {
code: "admin".to_string(),
name: "Administrator".to_string(),
description: None,
is_system: false,
};
assert_eq!(new.code, "admin");
}
#[test]
fn new_permission_constructs() {
let new = NewPermission {
code: "user:read".to_string(),
name: "Read User".to_string(),
resource_type: Some("user".to_string()),
action: Some("read".to_string()),
};
assert_eq!(new.code, "user:read");
}
#[test]
fn new_auth_method_constructs() {
let new = NewAuthMethod {
user_id: "u-001".to_string(),
method_type: "password".to_string(),
external_id: None,
metadata: None,
};
assert_eq!(new.method_type, "password");
}
#[test]
fn new_session_constructs() {
let new = NewSession {
session_id: "sess-001".to_string(),
user_id: "u-001".to_string(),
device_id: Some("web".to_string()),
ip: None,
user_agent: None,
expire_time: None,
};
assert_eq!(new.session_id, "sess-001");
}
#[test]
fn new_login_log_constructs() {
let new = NewLoginLog {
user_id: Some("u-001".to_string()),
action: "login".to_string(),
ip: None,
device_id: None,
success: true,
fail_reason: None,
};
assert_eq!(new.action, "login");
}
#[test]
fn update_user_default_all_none() {
let update = UpdateUser::default();
assert!(update.username.is_none());
assert!(update.password_hash.is_none());
assert!(update.status.is_none());
assert!(update.last_login_at.is_none());
}
#[test]
fn user_row_serializes_and_deserializes() {
let row = UserRow {
id: "u-001".to_string(),
username: "alice".to_string(),
password_hash: "$argon2id$...".to_string(),
status: "active".to_string(),
tenant_id: 0,
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
last_login_at: None,
};
let json = serde_json::to_string(&row).unwrap();
let deserialized: UserRow = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.id, "u-001");
assert_eq!(deserialized.username, "alice");
}
#[test]
fn permission_row_serializes_without_tenant_id() {
let row = PermissionRow {
id: "p-001".to_string(),
code: "user:read".to_string(),
name: "Read User".to_string(),
resource_type: None,
action: None,
created_at: "2026-07-04T00:00:00Z".to_string(),
updated_at: "2026-07-04T00:00:00Z".to_string(),
};
let json = serde_json::to_string(&row).unwrap();
assert!(
!json.contains("tenant_id"),
"PermissionRow JSON 不应包含 tenant_id"
);
}
#[test]
fn all_repository_traits_are_send_sync() {
fn assert_send_sync<T: Send + Sync + ?Sized>() {}
assert_send_sync::<dyn UserRepository>();
assert_send_sync::<dyn RoleRepository>();
assert_send_sync::<dyn PermissionRepository>();
assert_send_sync::<dyn UserRoleRepository>();
assert_send_sync::<dyn RolePermissionRepository>();
assert_send_sync::<dyn AuthMethodRepository>();
assert_send_sync::<dyn SessionRepository>();
assert_send_sync::<dyn LoginLogRepository>();
assert_send_sync::<dyn UserExtRepository>();
assert_send_sync::<dyn UserDeviceRepository>();
}
#[cfg(feature = "db-postgres")]
#[tokio::test(flavor = "multi_thread")]
#[serial_test::serial]
#[ignore = "需要真实 PostgreSQL,设置 DATABASE_URL 后 cargo test -- --ignored 运行"]
async fn dbnexus_user_repository_works_with_postgres_backend() {
use crate::dao::init_dbnexus;
use crate::dao::repository::sqlite::DbnexusUserRepository;
use dbnexus::sea_orm::ConnectionTrait;
let database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| {
panic!("DATABASE_URL 未设置,请指向 PostgreSQL 连接字符串");
});
let pool = init_dbnexus(&database_url)
.await
.expect("初始化 PostgreSQL 连接池失败");
{
let session = pool.get_session("admin").await.expect("获取 session 失败");
let conn = session.connection().expect("获取 connection 失败");
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_user_ext")
.await;
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_login_log")
.await;
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_session")
.await;
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_auth_method")
.await;
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_role_permission")
.await;
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_user_role")
.await;
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_permission")
.await;
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_role")
.await;
let _ = conn
.execute_unprepared("DROP TABLE IF EXISTS app_user")
.await;
conn.execute_unprepared(
"CREATE TABLE app_user (
id TEXT PRIMARY KEY,
username TEXT NOT NULL,
password_hash TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'pending',
tenant_id BIGINT NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_login_at TEXT
)",
)
.await
.expect("创建 app_user 表失败");
}
let repo = DbnexusUserRepository::new(pool.clone());
let tenant_id: i64 = 42;
let user_id = repo
.create(
tenant_id,
NewUser {
username: "pg-test-user".to_string(),
password_hash: "$argon2id$m=8,t=1,p=1$fake-hash".to_string(),
status: "active".to_string(),
},
)
.await
.expect("插入测试用户失败");
let found = repo
.find_by_id(tenant_id, &user_id)
.await
.expect("find_by_id 查询失败")
.expect("测试用户未找到");
assert_eq!(found.id, user_id);
assert_eq!(found.username, "pg-test-user");
assert_eq!(found.password_hash, "$argon2id$m=8,t=1,p=1$fake-hash");
assert_eq!(found.status, "active");
assert_eq!(found.tenant_id, tenant_id);
repo.delete(tenant_id, &user_id)
.await
.expect("清理测试数据失败");
{
let session = pool.get_session("admin").await.expect("获取 session 失败");
let conn = session.connection().expect("获取 connection 失败");
conn.execute_unprepared("DROP TABLE IF EXISTS app_user")
.await
.expect("清理 app_user 表失败");
}
}
}