From 4e80b593debced3c7ce4afd29e4167c35613dd38 Mon Sep 17 00:00:00 2001 From: ldh <17393183636@163.com> Date: Mon, 16 Nov 2026 17:03:18 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Hardware-Vue/src/api/systemConfig.ts | 155 ++++ .../src/components/AdminPasswordModal.vue | 286 +++++++ Hardware-Vue/src/router/index.ts | 15 + Hardware-Vue/src/views/HomeView.vue | 48 +- Hardware-Vue/src/views/SystemConfigView.vue | 743 ++++++++++++++++++ .../HardwareService/ISystemConfigService.cs | 25 + .../SystemConfigService.cs | 102 +++ .../SystemSetting/SystemConfigRepository.cs | 88 +++ .../Controllers/SystemConfigController.cs | 200 +++++ HardwareWeb/Models/SystemConfigPayload.cs | 45 ++ HardwareWeb/Program.cs | 12 + HardwareWeb/Services/AdminAccessService.cs | 92 +++ HardwareWeb/appsettings.json | 4 + 13 files changed, 1813 insertions(+), 2 deletions(-) create mode 100644 Hardware-Vue/src/api/systemConfig.ts create mode 100644 Hardware-Vue/src/components/AdminPasswordModal.vue create mode 100644 Hardware-Vue/src/views/SystemConfigView.vue create mode 100644 HardwareControl.Core/HardwareService/ISystemConfigService.cs create mode 100644 HardwareControl.Core/HardwareServiceImpl/SystemConfigService.cs create mode 100644 HardwareControl.Core/SystemSetting/SystemConfigRepository.cs create mode 100644 HardwareWeb/Controllers/SystemConfigController.cs create mode 100644 HardwareWeb/Models/SystemConfigPayload.cs create mode 100644 HardwareWeb/Services/AdminAccessService.cs diff --git a/Hardware-Vue/src/api/systemConfig.ts b/Hardware-Vue/src/api/systemConfig.ts new file mode 100644 index 0000000..42c4b5b --- /dev/null +++ b/Hardware-Vue/src/api/systemConfig.ts @@ -0,0 +1,155 @@ +/** + * 系统参数配置接口封装。 + * 后端实现见 HardwareWeb/Controllers/SystemConfigController.cs: + * POST /api/system-config/auth -> { token, expiresAt } + * GET /api/system-config -> SystemConfig[] + * POST /api/system-config -> SystemConfig + * PUT /api/system-config/{id} -> SystemConfig + * DELETE /api/system-config/{id} -> 204 + * 除密码校验外,其余接口都需要携带 X-Admin-Token 请求头。 + */ + +export interface SystemConfig { + configId: number + configClass: string + configName: string + configValue: string + configDescript: string +} + +export interface SystemConfigInput { + configClass: string + configName: string + configValue: string + configDescript: string +} + +interface AdminAuthResult { + token: string + expiresAt: string +} + +const API_BASE = (import.meta.env.VITE_API_BASE ?? '').replace(/\/$/, '') +const REQUEST_TIMEOUT = 8000 +const TOKEN_KEY = 'libs-admin-token' + +export class SystemConfigApiError extends Error { + readonly status: number + + constructor(message: string, status = 0) { + super(message) + this.name = 'SystemConfigApiError' + this.status = status + } +} + +export function getAdminToken(): string { + return window.sessionStorage.getItem(TOKEN_KEY) ?? '' +} + +export function hasAdminSession(): boolean { + return getAdminToken() !== '' +} + +export function clearAdminSession() { + window.sessionStorage.removeItem(TOKEN_KEY) +} + +function setAdminToken(token: string) { + window.sessionStorage.setItem(TOKEN_KEY, token) +} + +async function request( + path: string, + init?: RequestInit, + withToken = true, +): Promise { + const controller = new AbortController() + const timer = window.setTimeout(() => controller.abort(), REQUEST_TIMEOUT) + + try { + const token = withToken ? getAdminToken() : '' + const response = await fetch(`${API_BASE}${path}`, { + ...init, + cache: 'no-store', + signal: controller.signal, + headers: { + Accept: 'application/json', + ...(init?.body ? { 'Content-Type': 'application/json' } : {}), + ...(token ? { 'X-Admin-Token': token } : {}), + ...(init?.headers ?? {}), + }, + }) + + if (!response.ok) { + let detail = `HTTP ${response.status}` + try { + const body = (await response.json()) as { message?: string; error?: string } + detail = body.message ?? body.error ?? detail + } catch { + // 响应不是 JSON 时保留状态码信息 + } + + if (response.status === 401 && withToken) { + clearAdminSession() + } + + throw new SystemConfigApiError(detail, response.status) + } + + if (response.status === 204) { + return undefined as T + } + + return (await response.json()) as T + } catch (error) { + if (error instanceof SystemConfigApiError) throw error + if (error instanceof DOMException && error.name === 'AbortError') { + throw new SystemConfigApiError('系统参数服务响应超时') + } + throw new SystemConfigApiError( + error instanceof Error ? error.message : '无法连接系统参数服务', + ) + } finally { + window.clearTimeout(timer) + } +} + +/** 校验管理密码,成功后令牌会写入 sessionStorage。 */ +export async function verifyAdminPassword(password: string): Promise { + const result = await request( + '/api/system-config/auth', + { + method: 'POST', + body: JSON.stringify({ password }), + }, + false, + ) + setAdminToken(result.token) +} + +export function listSystemConfigs(keyword = ''): Promise { + const query = keyword ? `?keyword=${encodeURIComponent(keyword)}` : '' + return request(`/api/system-config${query}`) +} + +export function createSystemConfig(input: SystemConfigInput): Promise { + return request('/api/system-config', { + method: 'POST', + body: JSON.stringify(input), + }) +} + +export function updateSystemConfig( + configId: number, + input: SystemConfigInput, +): Promise { + return request(`/api/system-config/${configId}`, { + method: 'PUT', + body: JSON.stringify(input), + }) +} + +export function deleteSystemConfig(configId: number): Promise { + return request(`/api/system-config/${configId}`, { method: 'DELETE' }) +} diff --git a/Hardware-Vue/src/components/AdminPasswordModal.vue b/Hardware-Vue/src/components/AdminPasswordModal.vue new file mode 100644 index 0000000..470b8ec --- /dev/null +++ b/Hardware-Vue/src/components/AdminPasswordModal.vue @@ -0,0 +1,286 @@ + + + + + diff --git a/Hardware-Vue/src/router/index.ts b/Hardware-Vue/src/router/index.ts index 5199ae8..c38c9e5 100644 --- a/Hardware-Vue/src/router/index.ts +++ b/Hardware-Vue/src/router/index.ts @@ -1,5 +1,6 @@ import { createRouter, createWebHistory } from 'vue-router' import HomeView from '@/views/HomeView.vue' +import { hasAdminSession } from '@/api/systemConfig' const router = createRouter({ history: createWebHistory(import.meta.env.BASE_URL), @@ -38,6 +39,12 @@ const router = createRouter({ path: '/pay', redirect: { name: 'sample' }, }, + { + path: '/system-config', + name: 'systemConfig', + component: () => import('@/views/SystemConfigView.vue'), + meta: { title: '系统参数管理', requiresAdmin: true }, + }, { path: '/:pathMatch(.*)*', redirect: { name: 'home' }, @@ -45,6 +52,14 @@ const router = createRouter({ ], }) +router.beforeEach((to) => { + if (to.meta.requiresAdmin && !hasAdminSession()) { + return { name: 'home' } + } + + return true +}) + router.afterEach((to) => { document.title = (to.meta.title as string | undefined) ?? 'LIBS Lab' }) diff --git a/Hardware-Vue/src/views/HomeView.vue b/Hardware-Vue/src/views/HomeView.vue index fefe8df..934e33c 100644 --- a/Hardware-Vue/src/views/HomeView.vue +++ b/Hardware-Vue/src/views/HomeView.vue @@ -1,6 +1,7 @@ + + + + diff --git a/HardwareControl.Core/HardwareService/ISystemConfigService.cs b/HardwareControl.Core/HardwareService/ISystemConfigService.cs new file mode 100644 index 0000000..594d5ba --- /dev/null +++ b/HardwareControl.Core/HardwareService/ISystemConfigService.cs @@ -0,0 +1,25 @@ +using HardwareControl.Core.SystemSetting; + +namespace HardwareControl.Core.HardwareServiceImpl.HardwareService +{ + /// + /// 系统参数配置服务:对上层提供增删改查能力,屏蔽本地存储细节。 + /// + public interface ISystemConfigService + { + /// 读取全部配置,可按关键字过滤(分类、名称、值、描述)。 + IReadOnlyList GetAll(string? keyword = null); + + /// 按主键读取单条配置;不存在时返回 null。 + SystemConfig? GetById(int id); + + /// 新增配置,返回带主键的实体。 + SystemConfig Create(SystemConfig config); + + /// 更新配置;主键不存在时抛出 。 + SystemConfig Update(SystemConfig config); + + /// 删除配置;返回是否成功删除。 + bool Delete(int id); + } +} diff --git a/HardwareControl.Core/HardwareServiceImpl/SystemConfigService.cs b/HardwareControl.Core/HardwareServiceImpl/SystemConfigService.cs new file mode 100644 index 0000000..a92f921 --- /dev/null +++ b/HardwareControl.Core/HardwareServiceImpl/SystemConfigService.cs @@ -0,0 +1,102 @@ +using HardwareControl.Core.HardwareServiceImpl.HardwareService; +using HardwareControl.Core.SystemSetting; +using Microsoft.Extensions.Logging; + +namespace HardwareControl.Core.HardwareServiceImpl +{ + /// + /// 系统参数配置服务实现。负责入参校验与日志,持久化委托给 。 + /// + public sealed class SystemConfigService : ISystemConfigService + { + private readonly SystemConfigRepository _repository; + private readonly ILogger _logger; + + public SystemConfigService( + SystemConfigRepository repository, + ILogger logger) + { + _repository = repository; + _logger = logger; + } + + public IReadOnlyList GetAll(string? keyword = null) => + _repository.GetAll(keyword); + + public SystemConfig? GetById(int id) => _repository.FindById(id); + + public SystemConfig Create(SystemConfig config) + { + ArgumentNullException.ThrowIfNull(config); + Normalize(config); + + var created = _repository.Insert(config); + _logger.LogInformation( + "新增系统参数:{ConfigClass}/{ConfigName}(Id={ConfigId})", + created.ConfigClass, + created.ConfigName, + created.ConfigId); + + return created; + } + + public SystemConfig Update(SystemConfig config) + { + ArgumentNullException.ThrowIfNull(config); + + if (config.ConfigId <= 0) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, "系统参数 ID 无效"); + } + + Normalize(config); + + if (!_repository.Update(config)) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, + $"系统参数 {config.ConfigId} 不存在"); + } + + _logger.LogInformation( + "更新系统参数:{ConfigClass}/{ConfigName}(Id={ConfigId})", + config.ConfigClass, + config.ConfigName, + config.ConfigId); + + return config; + } + + public bool Delete(int id) + { + if (id <= 0) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, "系统参数 ID 无效"); + } + + var deleted = _repository.Delete(id); + if (deleted) + { + _logger.LogInformation("删除系统参数:Id={ConfigId}", id); + } + + return deleted; + } + + private static void Normalize(SystemConfig config) + { + if (string.IsNullOrWhiteSpace(config.ConfigName)) + { + throw new HardwareException( + HardwareErrorKind.InvalidArgument, "配置名称不能为空"); + } + + config.ConfigClass = config.ConfigClass?.Trim() ?? string.Empty; + config.ConfigName = config.ConfigName.Trim(); + config.ConfigValue = config.ConfigValue?.Trim() ?? string.Empty; + config.ConfigDescript = config.ConfigDescript?.Trim() ?? string.Empty; + } + } +} diff --git a/HardwareControl.Core/SystemSetting/SystemConfigRepository.cs b/HardwareControl.Core/SystemSetting/SystemConfigRepository.cs new file mode 100644 index 0000000..d91854d --- /dev/null +++ b/HardwareControl.Core/SystemSetting/SystemConfigRepository.cs @@ -0,0 +1,88 @@ +using LiteDB; + +namespace HardwareControl.Core.SystemSetting +{ + /// + /// 系统参数配置的本地存储层(LiteDB)。 + /// 数据库文件由调用方指定,建议整个进程只注册一个实例。 + /// + public sealed class SystemConfigRepository : IDisposable + { + private const string CollectionName = "system_config"; + + private readonly LiteDatabase _database; + private readonly ILiteCollection _collection; + + public SystemConfigRepository(string databasePath) + { + if (string.IsNullOrWhiteSpace(databasePath)) + { + throw new ArgumentException("数据库路径不能为空", nameof(databasePath)); + } + + var fullPath = Path.GetFullPath(databasePath); + var directory = Path.GetDirectoryName(fullPath); + if (!string.IsNullOrWhiteSpace(directory)) + { + Directory.CreateDirectory(directory); + } + + _database = new LiteDatabase(new ConnectionString + { + Filename = fullPath, + Connection = ConnectionType.Shared, + }); + _collection = _database.GetCollection(CollectionName); + } + + /// 读取全部配置,可按关键字过滤(分类、名称、值、描述)。 + public IReadOnlyList GetAll(string? keyword = null) + { + var items = _collection + .FindAll() + .OrderBy(x => x.ConfigClass) + .ThenBy(x => x.ConfigName) + .ToList(); + + if (string.IsNullOrWhiteSpace(keyword)) + { + return items; + } + + var value = keyword.Trim(); + return items + .Where(x => + Contains(x.ConfigClass, value) || + Contains(x.ConfigName, value) || + Contains(x.ConfigValue, value) || + Contains(x.ConfigDescript, value)) + .ToList(); + } + + public SystemConfig? FindById(int id) => _collection.FindById(id); + + public SystemConfig Insert(SystemConfig config) + { + ArgumentNullException.ThrowIfNull(config); + + config.ConfigId = 0; + var id = _collection.Insert(config); + config.ConfigId = id.AsInt32; + return config; + } + + public bool Update(SystemConfig config) + { + ArgumentNullException.ThrowIfNull(config); + return _collection.Update(config); + } + + public bool Delete(int id) => _collection.Delete(id); + + public void Dispose() => _database.Dispose(); + + private static bool Contains(string? source, string value) => + source is not null && + source.Contains(value, StringComparison.OrdinalIgnoreCase); + } +} diff --git a/HardwareWeb/Controllers/SystemConfigController.cs b/HardwareWeb/Controllers/SystemConfigController.cs new file mode 100644 index 0000000..206c7ef --- /dev/null +++ b/HardwareWeb/Controllers/SystemConfigController.cs @@ -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 +{ + /// + /// 系统参数配置 Web 接口。 + /// 除密码校验外,其余接口都需要在请求头携带 X-Admin-Token。 + /// + [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 _logger; + + public SystemConfigController( + ISystemConfigService service, + AdminAccessService access, + ILogger logger) + { + _service = service; + _access = access; + _logger = logger; + } + + /// 校验管理密码,通过后返回访问令牌。 + [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)); + } + + /// 读取系统参数列表,可按关键字过滤。 + [HttpGet] + [ProducesResponseType(typeof(IReadOnlyList), StatusCodes.Status200OK)] + public IActionResult List([FromQuery] string? keyword) + { + if (!IsAuthorized()) + { + return AdminUnauthorized(); + } + + var items = _service + .GetAll(keyword) + .Select(SystemConfigPayload.From) + .ToList(); + + return Ok(items); + } + + /// 按主键读取单条系统参数。 + [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)); + } + + /// 新增系统参数。 + [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); + } + } + + /// 按主键更新系统参数。 + [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); + } + } + + /// 按主键删除系统参数。 + [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 + }; + } + } +} diff --git a/HardwareWeb/Models/SystemConfigPayload.cs b/HardwareWeb/Models/SystemConfigPayload.cs new file mode 100644 index 0000000..80aceff --- /dev/null +++ b/HardwareWeb/Models/SystemConfigPayload.cs @@ -0,0 +1,45 @@ +using HardwareControl.Core.SystemSetting; + +namespace HardwareWeb.Models +{ + /// 系统参数配置的 Web 传输对象。 + 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); + } + + /// 新增 / 更新系统参数的请求体。 + 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, + }; + } + + /// 管理员密码校验请求。 + public sealed record AdminAuthRequest(string? Password); + + /// 管理员密码校验通过后签发的令牌。 + public sealed record AdminAuthPayload(string Token, DateTimeOffset ExpiresAt); +} diff --git a/HardwareWeb/Program.cs b/HardwareWeb/Program.cs index 8372dcd..043a669 100644 --- a/HardwareWeb/Program.cs +++ b/HardwareWeb/Program.cs @@ -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(); builder.Services.AddHostedService(); +// 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(); +builder.Services.AddSingleton(); + builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle diff --git a/HardwareWeb/Services/AdminAccessService.cs b/HardwareWeb/Services/AdminAccessService.cs new file mode 100644 index 0000000..becdb5b --- /dev/null +++ b/HardwareWeb/Services/AdminAccessService.cs @@ -0,0 +1,92 @@ +using System.Collections.Concurrent; +using System.Security.Cryptography; +using System.Text; + +namespace HardwareWeb.Services +{ + /// + /// 系统参数管理的轻量访问控制。 + /// 密码来自配置 SystemSetting:AdminPassword,未配置时使用默认密码; + /// 校验通过后签发一个进程内有效、固定时长的令牌。 + /// + 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 _tokens = + new(StringComparer.Ordinal); + + public AdminAccessService(IConfiguration configuration) + { + var configured = configuration["SystemSetting:AdminPassword"]; + _password = string.IsNullOrEmpty(configured) ? DefaultPassword : configured; + } + + /// 校验密码,成功时返回新令牌,失败时返回 null。 + 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); + } + + /// 判断令牌是否存在且未过期。 + 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); +} diff --git a/HardwareWeb/appsettings.json b/HardwareWeb/appsettings.json index 7326c98..3a72a87 100644 --- a/HardwareWeb/appsettings.json +++ b/HardwareWeb/appsettings.json @@ -32,5 +32,9 @@ "SendOnlyWhenViewers": true, "MaxFrameAgeMs": 1500, "MaxFrameBytes": 8388608 + }, + "SystemSetting": { + "DatabasePath": null, + "AdminPassword": "flzx3QC!1" } }