checkpoint

This commit is contained in:
2026-10-28 14:22:27 +02:00
parent 33dad8ca5a
commit bd22fa86b7
11 changed files with 161 additions and 52 deletions
+4 -15
View File
@@ -6,27 +6,16 @@ namespace StatiKosev.Data;
public static class DbSeeder
{
public const string UserRole = "User";
public const string AdminRole = "Admin";
//applies pending migrations, creates the roles and makes the configured AdminEmail account an admin
public static async Task SeedAsync(IServiceProvider services, string? adminEmail)
//applies pending migrations and creates the role every registered visitor gets
public static async Task SeedAsync(IServiceProvider services)
{
using var scope = services.CreateScope();
var sp = scope.ServiceProvider;
await sp.GetRequiredService<AppDbContext>().Database.MigrateAsync();
var roles = sp.GetRequiredService<RoleManager<IdentityRole>>();
foreach (var role in new[] { UserRole, AdminRole })
if (!await roles.RoleExistsAsync(role))
await roles.CreateAsync(new IdentityRole(role));
if (string.IsNullOrWhiteSpace(adminEmail)) return;
var users = sp.GetRequiredService<UserManager<IdentityUser>>();
var admin = await users.FindByEmailAsync(adminEmail);
if (admin is not null && !await users.IsInRoleAsync(admin, AdminRole))
await users.AddToRoleAsync(admin, AdminRole);
if (!await roles.RoleExistsAsync(UserRole))
await roles.CreateAsync(new IdentityRole(UserRole));
}
public static bool IsAdminEmail(string? email, string? adminEmail) =>
!string.IsNullOrWhiteSpace(adminEmail) && string.Equals(email, adminEmail, StringComparison.OrdinalIgnoreCase);
}