diff --git a/src/Oms.Application/DataPerm/DataPermAccessAuditor.cs b/src/Oms.Application/DataPerm/DataPermAccessAuditor.cs
new file mode 100644
index 0000000..d28f1a8
--- /dev/null
+++ b/src/Oms.Application/DataPerm/DataPermAccessAuditor.cs
@@ -0,0 +1,93 @@
+using System.Diagnostics;
+using System.Text.Json;
+using Fake.DependencyInjection;
+using Microsoft.AspNetCore.Http;
+
+namespace Oms.Application.DataPerm;
+
+///
+/// 数据权限访问审计:按采样率写入 data_perm_access_log,失败不影响主流程。
+///
+public class DataPermAccessAuditor(
+ DataPermStore store,
+ IHttpContextAccessor httpContextAccessor) : IScopedDependency
+{
+ private static readonly JsonSerializerOptions JsonOptions = new()
+ {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase
+ };
+
+ ///
+ /// 尝试写入访问日志;采样未命中或无用户上下文时直接跳过。
+ ///
+ public async Task TryWriteAsync(
+ DataScopeContext? context,
+ string apiPath,
+ string httpMethod,
+ int? rowCount,
+ int? elapsedMs,
+ int samplePercent,
+ CancellationToken cancellationToken = default)
+ {
+ if (context == null || samplePercent <= 0)
+ {
+ return;
+ }
+
+ if (samplePercent < 100 && Random.Shared.Next(100) >= samplePercent)
+ {
+ return;
+ }
+
+ try
+ {
+ var appliedScopeJson = JsonSerializer.Serialize(
+ new
+ {
+ context.IsAdmin,
+ context.DataResourceCode,
+ context.DataScope,
+ OrganizationIds = context.OrganizationIds.Select(x => x.ToString()).ToList(),
+ SecretLevels = context.SecretLevels.OrderBy(x => x).ToList(),
+ BizFilters = context.BizFilters,
+ OwnerMapIds = context.ResolvedOwnerIds
+ },
+ JsonOptions);
+
+ await store.InsertAccessLogAsync(
+ context.UserId,
+ context.MapId,
+ context.DataResourceCode,
+ apiPath,
+ httpMethod,
+ appliedScopeJson,
+ rowCount,
+ elapsedMs,
+ ResolveClientIp(),
+ cancellationToken);
+ }
+ catch
+ {
+ // 审计失败不阻断业务
+ }
+ }
+
+ private string? ResolveClientIp()
+ {
+ var http = httpContextAccessor.HttpContext;
+ if (http == null)
+ {
+ return null;
+ }
+
+ var forwarded = http.Request.Headers["X-Forwarded-For"].FirstOrDefault();
+ if (!string.IsNullOrWhiteSpace(forwarded))
+ {
+ return forwarded.Split(',')[0].Trim();
+ }
+
+ return http.Connection.RemoteIpAddress?.ToString();
+ }
+
+ public static Stopwatch StartTimer() => Stopwatch.StartNew();
+}
diff --git a/src/Oms.Application/DataPerm/DataPermConstants.cs b/src/Oms.Application/DataPerm/DataPermConstants.cs
index 9c07a43..7d84733 100644
--- a/src/Oms.Application/DataPerm/DataPermConstants.cs
+++ b/src/Oms.Application/DataPerm/DataPermConstants.cs
@@ -73,4 +73,10 @@ public static class DataPermConstants
(5, "VIP4"),
(6, "VIP5")
];
+
+ /// 订单列表等查询访问日志采样百分比(0=关闭,100=全量)。
+ public const int AccessLogSamplePercentList = 10;
+
+ /// 导出等敏感操作访问日志采样百分比。
+ public const int AccessLogSamplePercentExport = 100;
}
diff --git a/src/Oms.Application/DataPerm/DataPermStore.cs b/src/Oms.Application/DataPerm/DataPermStore.cs
index fce007d..38ffb2d 100644
--- a/src/Oms.Application/DataPerm/DataPermStore.cs
+++ b/src/Oms.Application/DataPerm/DataPermStore.cs
@@ -478,9 +478,42 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
cancellationToken);
}
+ public async Task InsertAccessLogAsync(
+ Guid userId,
+ int mapId,
+ string dataResourceCode,
+ string apiPath,
+ string httpMethod,
+ string? appliedScopeJson,
+ int? rowCount,
+ int? elapsedMs,
+ string? clientIp,
+ CancellationToken cancellationToken = default)
+ {
+ await dbContext.Database.ExecuteSqlRawAsync("""
+ INSERT INTO `data_perm_access_log`
+ (`UserId`,`MapId`,`DataResourceCode`,`ApiPath`,`HttpMethod`,`AppliedScopeJson`,`RowCount`,`ElapsedMs`,`ClientIp`,`CreateTime`)
+ VALUES ({0},{1},{2},{3},{4},{5},{6},{7},{8},UTC_TIMESTAMP())
+ """,
+ [
+ userId.ToString(),
+ mapId,
+ dataResourceCode.Trim(),
+ apiPath.Trim(),
+ string.IsNullOrWhiteSpace(httpMethod) ? "GET" : httpMethod.Trim().ToUpperInvariant(),
+ SqlParam(appliedScopeJson),
+ SqlParam(rowCount),
+ SqlParam(elapsedMs),
+ SqlParam(clientIp)
+ ],
+ cancellationToken);
+ }
+
public async Task> GetChangeLogsAsync(
string? targetType,
string? targetId,
+ DateTime? startTime,
+ DateTime? endTime,
int page,
int pageSize,
CancellationToken cancellationToken = default)
@@ -499,6 +532,18 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
args.Add(targetId.Trim());
}
+ if (startTime.HasValue)
+ {
+ where += " AND l.`CreateTime` >= {" + args.Count + "}";
+ args.Add(startTime.Value);
+ }
+
+ if (endTime.HasValue)
+ {
+ where += " AND l.`CreateTime` <= {" + args.Count + "}";
+ args.Add(endTime.Value);
+ }
+
var countSql = $"SELECT COUNT(*) AS `Value` FROM `data_perm_change_log` l {where}";
var total = await dbContext.Database.SqlQueryRaw(countSql, args.ToArray()).FirstAsync(cancellationToken);
var offset = Math.Max(page - 1, 0) * pageSize;
@@ -567,22 +612,53 @@ public class DataPermStore(FakeRbacDbContext dbContext, DataPermContextCache cac
}
public async Task> GetAccessLogsAsync(
+ string? userId,
+ string? dataResourceCode,
+ DateTime? startTime,
+ DateTime? endTime,
int page,
int pageSize,
CancellationToken cancellationToken = default)
{
- const string countSql = "SELECT COUNT(*) AS `Value` FROM `data_perm_access_log`";
- var total = await dbContext.Database.SqlQueryRaw(countSql).FirstAsync(cancellationToken);
+ var where = "WHERE 1=1";
+ var args = new List