提交代码

This commit is contained in:
ldh
2026-11-16 17:03:18 +08:00
parent ba22189a46
commit 4e80b593de
13 changed files with 1813 additions and 2 deletions
@@ -0,0 +1,200 @@
using HardwareControl.Core;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareWeb.Models;
using HardwareWeb.Services;
using Microsoft.AspNetCore.Mvc;
namespace HardwareWeb.Controllers
{
/// <summary>
/// 系统参数配置 Web 接口。
/// 除密码校验外,其余接口都需要在请求头携带 X-Admin-Token。
/// </summary>
[ApiController]
[Route("api/system-config")]
public class SystemConfigController : ControllerBase
{
private const string TokenHeader = "X-Admin-Token";
private readonly ISystemConfigService _service;
private readonly AdminAccessService _access;
private readonly ILogger<SystemConfigController> _logger;
public SystemConfigController(
ISystemConfigService service,
AdminAccessService access,
ILogger<SystemConfigController> logger)
{
_service = service;
_access = access;
_logger = logger;
}
/// <summary>校验管理密码,通过后返回访问令牌。</summary>
[HttpPost("auth")]
[ProducesResponseType(typeof(AdminAuthPayload), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
public IActionResult Auth([FromBody] AdminAuthRequest? request)
{
var session = _access.SignIn(request?.Password);
if (session is null)
{
_logger.LogWarning("系统参数管理密码校验失败");
return Unauthorized(new
{
error = "Unauthorized",
message = "密码错误"
});
}
_logger.LogInformation("系统参数管理密码校验通过");
return Ok(new AdminAuthPayload(session.Token, session.ExpiresAt));
}
/// <summary>读取系统参数列表,可按关键字过滤。</summary>
[HttpGet]
[ProducesResponseType(typeof(IReadOnlyList<SystemConfigPayload>), StatusCodes.Status200OK)]
public IActionResult List([FromQuery] string? keyword)
{
if (!IsAuthorized())
{
return AdminUnauthorized();
}
var items = _service
.GetAll(keyword)
.Select(SystemConfigPayload.From)
.ToList();
return Ok(items);
}
/// <summary>按主键读取单条系统参数。</summary>
[HttpGet("{id:int}")]
[ProducesResponseType(typeof(SystemConfigPayload), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult Get(int id)
{
if (!IsAuthorized())
{
return AdminUnauthorized();
}
var config = _service.GetById(id);
return config is null
? NotFound(new { error = "NotFound", message = $"系统参数 {id} 不存在" })
: Ok(SystemConfigPayload.From(config));
}
/// <summary>新增系统参数。</summary>
[HttpPost]
[ProducesResponseType(typeof(SystemConfigPayload), StatusCodes.Status200OK)]
public IActionResult Create([FromBody] SystemConfigUpsertRequest? request)
{
if (!IsAuthorized())
{
return AdminUnauthorized();
}
if (request is null)
{
return BadRequest(new { error = "InvalidArgument", message = "请求体不能为空" });
}
try
{
var created = _service.Create(request.ToEntity());
return Ok(SystemConfigPayload.From(created));
}
catch (HardwareException ex)
{
return ServiceError(ex);
}
}
/// <summary>按主键更新系统参数。</summary>
[HttpPut("{id:int}")]
[ProducesResponseType(typeof(SystemConfigPayload), StatusCodes.Status200OK)]
public IActionResult Update(int id, [FromBody] SystemConfigUpsertRequest? request)
{
if (!IsAuthorized())
{
return AdminUnauthorized();
}
if (request is null)
{
return BadRequest(new { error = "InvalidArgument", message = "请求体不能为空" });
}
try
{
var updated = _service.Update(request.ToEntity(id));
return Ok(SystemConfigPayload.From(updated));
}
catch (HardwareException ex)
{
return ServiceError(ex);
}
}
/// <summary>按主键删除系统参数。</summary>
[HttpDelete("{id:int}")]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult Delete(int id)
{
if (!IsAuthorized())
{
return AdminUnauthorized();
}
try
{
return _service.Delete(id)
? NoContent()
: NotFound(new { error = "NotFound", message = $"系统参数 {id} 不存在" });
}
catch (HardwareException ex)
{
return ServiceError(ex);
}
}
private bool IsAuthorized() => _access.Validate(Request.Headers[TokenHeader]);
private IActionResult AdminUnauthorized() =>
Unauthorized(new
{
error = "Unauthorized",
message = "管理员凭证无效或已过期,请重新输入密码"
});
private IActionResult ServiceError(HardwareException ex)
{
var statusCode = ex.Kind switch
{
HardwareErrorKind.InvalidArgument => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError,
};
if (statusCode >= 500)
{
_logger.LogError(ex, "系统参数接口失败:{Message}", ex.Message);
}
else
{
_logger.LogWarning("系统参数接口失败:{Message}", ex.Message);
}
return new ObjectResult(new
{
error = ex.Kind.ToString(),
message = ex.Message
})
{
StatusCode = statusCode
};
}
}
}
+45
View File
@@ -0,0 +1,45 @@
using HardwareControl.Core.SystemSetting;
namespace HardwareWeb.Models
{
/// <summary>系统参数配置的 Web 传输对象。</summary>
public sealed record SystemConfigPayload(
int ConfigId,
string ConfigClass,
string ConfigName,
string ConfigValue,
string ConfigDescript)
{
public static SystemConfigPayload From(SystemConfig config) =>
new(
config.ConfigId,
config.ConfigClass ?? string.Empty,
config.ConfigName ?? string.Empty,
config.ConfigValue ?? string.Empty,
config.ConfigDescript ?? string.Empty);
}
/// <summary>新增 / 更新系统参数的请求体。</summary>
public sealed record SystemConfigUpsertRequest(
string? ConfigClass,
string? ConfigName,
string? ConfigValue,
string? ConfigDescript)
{
public SystemConfig ToEntity(int configId = 0) =>
new()
{
ConfigId = configId,
ConfigClass = ConfigClass ?? string.Empty,
ConfigName = ConfigName ?? string.Empty,
ConfigValue = ConfigValue ?? string.Empty,
ConfigDescript = ConfigDescript ?? string.Empty,
};
}
/// <summary>管理员密码校验请求。</summary>
public sealed record AdminAuthRequest(string? Password);
/// <summary>管理员密码校验通过后签发的令牌。</summary>
public sealed record AdminAuthPayload(string Token, DateTimeOffset ExpiresAt);
}
+12
View File
@@ -1,6 +1,7 @@
using HardwareControl.Core.HardwareServiceImpl;
using HardwareControl.Core.HardwareServiceImpl.HardwareService;
using HardwareControl.Core.Spectrometer;
using HardwareControl.Core.SystemSetting;
using HardwareControl.Core.UsbCamera;
using HardwareWeb.Hubs;
using HardwareWeb.Services;
@@ -36,6 +37,17 @@ builder.Services.AddSignalR(options =>
builder.Services.AddSingleton<CameraBroadcastChannel>();
builder.Services.AddHostedService<CameraBroadcastService>();
// 7. 系统参数:LiteDB 本地库 + 管理密码校验
var systemConfigDbPath = builder.Configuration["SystemSetting:DatabasePath"];
if (string.IsNullOrWhiteSpace(systemConfigDbPath))
{
systemConfigDbPath = Path.Combine(
AppContext.BaseDirectory, "Data", "system-config.db");
}
builder.Services.AddSingleton(_ => new SystemConfigRepository(systemConfigDbPath));
builder.Services.AddSingleton<ISystemConfigService, SystemConfigService>();
builder.Services.AddSingleton<AdminAccessService>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
@@ -0,0 +1,92 @@
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
namespace HardwareWeb.Services
{
/// <summary>
/// 系统参数管理的轻量访问控制。
/// 密码来自配置 SystemSetting:AdminPassword,未配置时使用默认密码;
/// 校验通过后签发一个进程内有效、固定时长的令牌。
/// </summary>
public sealed class AdminAccessService
{
public const string DefaultPassword = "flzx3QC!1";
private static readonly TimeSpan TokenLifetime = TimeSpan.FromMinutes(30);
private readonly string _password;
private readonly ConcurrentDictionary<string, DateTimeOffset> _tokens =
new(StringComparer.Ordinal);
public AdminAccessService(IConfiguration configuration)
{
var configured = configuration["SystemSetting:AdminPassword"];
_password = string.IsNullOrEmpty(configured) ? DefaultPassword : configured;
}
/// <summary>校验密码,成功时返回新令牌,失败时返回 null。</summary>
public AdminSession? SignIn(string? password)
{
if (!FixedTimeEquals(password, _password))
{
return null;
}
CleanupExpired();
var token = Convert.ToHexString(RandomNumberGenerator.GetBytes(32));
var expiresAt = DateTimeOffset.UtcNow.Add(TokenLifetime);
_tokens[token] = expiresAt;
return new AdminSession(token, expiresAt);
}
/// <summary>判断令牌是否存在且未过期。</summary>
public bool Validate(string? token)
{
if (string.IsNullOrWhiteSpace(token))
{
return false;
}
if (!_tokens.TryGetValue(token, out var expiresAt))
{
return false;
}
if (expiresAt > DateTimeOffset.UtcNow)
{
return true;
}
_tokens.TryRemove(token, out _);
return false;
}
private void CleanupExpired()
{
var now = DateTimeOffset.UtcNow;
foreach (var pair in _tokens)
{
if (pair.Value <= now)
{
_tokens.TryRemove(pair.Key, out _);
}
}
}
private static bool FixedTimeEquals(string? left, string right)
{
if (left is null)
{
return false;
}
return CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(left),
Encoding.UTF8.GetBytes(right));
}
}
public sealed record AdminSession(string Token, DateTimeOffset ExpiresAt);
}
+4
View File
@@ -32,5 +32,9 @@
"SendOnlyWhenViewers": true,
"MaxFrameAgeMs": 1500,
"MaxFrameBytes": 8388608
},
"SystemSetting": {
"DatabasePath": null,
"AdminPassword": "flzx3QC!1"
}
}