Files
2026-11-16 17:03:18 +08:00

93 lines
2.8 KiB
C#

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);
}