using MiaoJiZhang.Domain.Entities; using MiaoJiZhang.Infrastructure.Persistence; using Microsoft.EntityFrameworkCore; namespace MiaoJiZhang.Api.Services; public sealed class AdminBootstrapService( AppDbContext db, IConfiguration configuration, ILogger logger) { public async Task EnsureAsync(CancellationToken ct = default) { if (await db.AdminUsers.AnyAsync(ct)) return; var username = configuration["Admin:BootstrapUsername"]?.Trim(); var password = configuration["Admin:BootstrapPassword"]; if (string.IsNullOrWhiteSpace(username) || username.Length is < 3 or > 64 || string.IsNullOrWhiteSpace(password) || password.Length < 12) { throw new InvalidOperationException( "首次启动必须通过 Admin__BootstrapUsername 和 Admin__BootstrapPassword 配置管理员,密码至少 12 位"); } var now = DateTime.UtcNow; db.AdminUsers.Add(new AdminUser { Username = username, PasswordHash = AdminSessionService.HashPassword(password), Role = AdminRoles.SuperAdmin, IsActive = true, MustChangePassword = true, CreatedAt = now, UpdatedAt = now, }); await db.SaveChangesAsync(ct); logger.LogWarning("Bootstrapped the first super administrator account: {Username}", username); } }