feat(audit): Q2 Chunk 3 — 审计日志补全

- 登录成功/失败均写入审计日志(含 IP、User-Agent)
- 登出、密码修改添加审计日志
- 用户/角色 update 记录变更前后值(old_value/new_value)
- 插件数据 CRUD(create/update/delete)添加审计日志
- auth handler 提取 X-Forwarded-For/X-Real-IP/User-Agent
This commit is contained in:
iven
2026-04-17 19:21:43 +08:00
parent 080d2cb3d6
commit 7c14bf83ca
5 changed files with 139 additions and 7 deletions

View File

@@ -5,6 +5,8 @@ use uuid::Uuid;
use crate::dto::{LoginResp, RoleResp, UserResp};
use crate::entity::{role, user, user_credential, user_role};
use crate::error::AuthError;
use erp_core::audit::AuditLog;
use erp_core::audit_service;
use erp_core::events::EventBus;
use crate::error::AuthResult;
@@ -12,6 +14,12 @@ use crate::error::AuthResult;
use super::password;
use super::token_service::TokenService;
/// 请求来源信息,用于审计日志记录。
pub struct RequestInfo {
pub ip: Option<String>,
pub user_agent: Option<String>,
}
/// JWT configuration needed for token signing.
pub struct JwtConfig<'a> {
pub secret: &'a str,
@@ -41,16 +49,32 @@ impl AuthService {
db: &sea_orm::DatabaseConnection,
jwt: &JwtConfig<'_>,
event_bus: &EventBus,
req_info: Option<&RequestInfo>,
) -> AuthResult<LoginResp> {
// 1. Find user by tenant_id + username
let user_model = user::Entity::find()
let user_model = match user::Entity::find()
.filter(user::Column::TenantId.eq(tenant_id))
.filter(user::Column::Username.eq(username))
.filter(user::Column::DeletedAt.is_null())
.one(db)
.await
.map_err(|e| AuthError::Validation(e.to_string()))?
.ok_or(AuthError::InvalidCredentials)?;
{
Some(m) => m,
None => {
// 审计:用户不存在(登录失败)
audit_service::record(
AuditLog::new(tenant_id, None, "user.login_failed", "user")
.with_request_info(
req_info.as_ref().and_then(|r| r.ip.clone()),
req_info.as_ref().and_then(|r| r.user_agent.clone()),
),
db,
)
.await;
return Err(AuthError::InvalidCredentials);
}
};
// 2. Check user status
if user_model.status != "active" {
@@ -75,6 +99,16 @@ impl AuthService {
.ok_or(AuthError::InvalidCredentials)?;
if !password::verify_password(password_plain, stored_hash)? {
// 审计:密码错误(登录失败)
audit_service::record(
AuditLog::new(tenant_id, Some(user_model.id), "user.login_failed", "user")
.with_request_info(
req_info.as_ref().and_then(|r| r.ip.clone()),
req_info.as_ref().and_then(|r| r.user_agent.clone()),
),
db,
)
.await;
return Err(AuthError::InvalidCredentials);
}
@@ -130,6 +164,18 @@ impl AuthService {
serde_json::json!({ "user_id": user_model.id, "username": user_model.username }),
), db).await;
// 审计:登录成功
audit_service::record(
AuditLog::new(tenant_id, Some(user_model.id), "user.login", "user")
.with_resource_id(user_model.id)
.with_request_info(
req_info.as_ref().and_then(|r| r.ip.clone()),
req_info.as_ref().and_then(|r| r.user_agent.clone()),
),
db,
)
.await;
Ok(LoginResp {
access_token,
refresh_token,
@@ -217,8 +263,23 @@ impl AuthService {
user_id: Uuid,
tenant_id: Uuid,
db: &sea_orm::DatabaseConnection,
req_info: Option<&RequestInfo>,
) -> AuthResult<()> {
TokenService::revoke_all_user_tokens(user_id, tenant_id, db).await
TokenService::revoke_all_user_tokens(user_id, tenant_id, db).await?;
// 审计:登出
audit_service::record(
AuditLog::new(tenant_id, Some(user_id), "user.logout", "user")
.with_resource_id(user_id)
.with_request_info(
req_info.as_ref().and_then(|r| r.ip.clone()),
req_info.as_ref().and_then(|r| r.user_agent.clone()),
),
db,
)
.await;
Ok(())
}
/// Change password for the authenticated user.
@@ -234,6 +295,7 @@ impl AuthService {
current_password: &str,
new_password: &str,
db: &sea_orm::DatabaseConnection,
req_info: Option<&RequestInfo>,
) -> AuthResult<()> {
// 1. Find the user's password credential
let cred = user_credential::Entity::find()
@@ -271,6 +333,18 @@ impl AuthService {
// 4. Revoke all refresh tokens — force re-login on all devices
TokenService::revoke_all_user_tokens(user_id, tenant_id, db).await?;
// 审计:密码修改
audit_service::record(
AuditLog::new(tenant_id, Some(user_id), "user.change_password", "user")
.with_resource_id(user_id)
.with_request_info(
req_info.as_ref().and_then(|r| r.ip.clone()),
req_info.as_ref().and_then(|r| r.user_agent.clone()),
),
db,
)
.await;
tracing::info!(user_id = %user_id, "Password changed successfully");
Ok(())
}

View File

@@ -171,6 +171,8 @@ impl RoleService {
.filter(|r| r.tenant_id == tenant_id && r.deleted_at.is_none())
.ok_or_else(|| AuthError::Validation("角色不存在".to_string()))?;
let old_json = serde_json::to_value(&model).unwrap_or(serde_json::Value::Null);
let next_ver = check_version(version, model.version)
.map_err(|e| AuthError::Validation(e.to_string()))?;
@@ -192,8 +194,12 @@ impl RoleService {
.await
.map_err(|e| AuthError::Validation(e.to_string()))?;
let new_json = serde_json::to_value(&updated).unwrap_or(serde_json::Value::Null);
audit_service::record(
AuditLog::new(tenant_id, Some(operator_id), "role.update", "role").with_resource_id(id),
AuditLog::new(tenant_id, Some(operator_id), "role.update", "role")
.with_resource_id(id)
.with_changes(Some(old_json), Some(new_json)),
db,
)
.await;

View File

@@ -204,6 +204,8 @@ impl UserService {
.map_err(|e| AuthError::Validation(e.to_string()))?
.ok_or_else(|| AuthError::Validation("用户不存在".to_string()))?;
let old_json = serde_json::to_value(&user_model).unwrap_or(serde_json::Value::Null);
let next_ver = check_version(req.version, user_model.version)
.map_err(|e| AuthError::Validation(e.to_string()))?;
@@ -233,8 +235,12 @@ impl UserService {
.await
.map_err(|e| AuthError::Validation(e.to_string()))?;
let new_json = serde_json::to_value(&updated).unwrap_or(serde_json::Value::Null);
audit_service::record(
AuditLog::new(tenant_id, Some(operator_id), "user.update", "user").with_resource_id(id),
AuditLog::new(tenant_id, Some(operator_id), "user.update", "user")
.with_resource_id(id)
.with_changes(Some(old_json), Some(new_json)),
db,
)
.await;