feat(AuthService): assign admin role to the first registered user and clean up admin user creation logic

This commit is contained in:
shiyu
2025-05-23 20:22:13 +08:00
parent c9576d510e
commit 7932240bbb
2 changed files with 7 additions and 29 deletions

View File

@@ -27,7 +27,6 @@ public class AuthService(IDbContextFactory<MyDbContext> dbContextFactory, IConfi
{
return (false, "该用户名已被使用", null);
}
var user = new User
{
UserName = request.UserName,
@@ -36,6 +35,11 @@ public class AuthService(IDbContextFactory<MyDbContext> dbContextFactory, IConfi
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
var userCount = await context.Users.CountAsync();
if (userCount == 0)
{
user.RoleId = 1;
}
context.Users.Add(user);
await context.SaveChangesAsync();
return (true, "用户注册成功", user);
@@ -277,7 +281,7 @@ public class AuthService(IDbContextFactory<MyDbContext> dbContextFactory, IConfi
}
var (isSuccess, message, user) = await FindOrCreateGitHubUserAsync(githubUserId, name ?? loginName, email);
if (!isSuccess || user == null)
{
Console.WriteLine($"创建或查找GitHub用户失败: {message}");

View File

@@ -91,33 +91,7 @@ public class DatabaseInitializer(
await context.Roles.AddAsync(adminRole);
await context.SaveChangesAsync();
}
// 检查并创建管理员用户
var adminUser = await context.Users.FirstOrDefaultAsync(u => u.UserName == "Admin");
if (adminUser == null)
{
// 生成随机6位密码
string password = GenerateRandomPassword(6);
string passwordHash = HashPassword(password);
logger.LogInformation("创建管理员用户,邮箱: you@foxel.cc密码: {Password}", password);
adminUser = new User
{
UserName = "Admin",
Email = "you@foxel.cc",
PasswordHash = passwordHash,
RoleId = adminRole.Id,
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow
};
await context.Users.AddAsync(adminUser);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"[重要] 管理员账户初始密码: {password},请及时修改");
Console.WriteLine($"[重要] 请及时登录后台修改AI相关配置系统才可正常运行");
Console.ResetColor();
await context.SaveChangesAsync();
}
logger.LogInformation("请注意,第一个注册的用户将自动成为管理员");
}
private string GenerateRandomPassword(int length)