feat:首次启动创建默认账户

This commit is contained in:
ShaoHua
2026-05-11 01:48:17 +08:00
parent 3dbd97103c
commit c54f2e2ecc
12 changed files with 850 additions and 25 deletions
+45 -6
View File
@@ -24,7 +24,8 @@ builder.Services.AddCors(options =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
.AllowAnyHeader()
.SetPreflightMaxAge(TimeSpan.FromMinutes(30));
});
});
@@ -37,16 +38,54 @@ using (var scope = app.Services.CreateScope())
var dbContext = services.GetRequiredService<Hua.Todo.Application.Data.TodoDbContext>();
dbContext.Database.Migrate();
// Seed default admin from configuration
var config = services.GetRequiredService<IConfiguration>();
var authService = services.GetRequiredService<CloudAuthService>();
var adminConfig = config.GetSection("DefaultAdmin");
var adminUserName = adminConfig["UserName"];
var adminPassword = adminConfig["Password"];
if (!string.IsNullOrWhiteSpace(adminUserName) && !string.IsNullOrWhiteSpace(adminPassword))
if (!string.IsNullOrWhiteSpace(adminUserName))
{
var authService = services.GetRequiredService<CloudAuthService>();
await authService.BootstrapAdminAsync(adminUserName, adminPassword, "system", "seeding", CancellationToken.None);
var result = await authService.BootstrapAdminAsync(adminUserName, adminPassword, "system", "seeding", CancellationToken.None);
if (result != null)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("========================================");
Console.WriteLine("首次启动:已创建默认管理员账号");
Console.WriteLine($"用户名: {result.UserName}");
if (!string.IsNullOrEmpty(adminPassword))
{
Console.WriteLine($"密码: {adminPassword}(已在配置中设置)");
}
else
{
Console.WriteLine($"临时密码: {result.GeneratedPassword}");
Console.WriteLine("请立即登录并修改密码!");
}
Console.WriteLine("========================================");
Console.ResetColor();
}
}
else
{
var hasAnyCloudUser = await dbContext.Users.AsNoTracking().AnyAsync(u => u.Role != "local");
if (!hasAnyCloudUser)
{
var defaultUserName = "admin";
var result = await authService.BootstrapAdminAsync(defaultUserName, null, "system", "auto-seeding", CancellationToken.None);
if (result != null)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("========================================");
Console.WriteLine("首次启动:已自动创建管理员账号");
Console.WriteLine($"用户名: {result.UserName}");
Console.WriteLine($"临时密码: {result.GeneratedPassword}");
Console.WriteLine("请立即登录并修改密码!");
Console.WriteLine("========================================");
Console.ResetColor();
}
}
}
}
@@ -56,9 +95,9 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI();
}
app.UseCors("AllowAll");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors("AllowAll");
app.UseAuthentication();
app.UseAuthorization();