85 lines
2.4 KiB
C#
85 lines
2.4 KiB
C#
using Hutopy.Domain.Constants;
|
|
using Hutopy.Infrastructure.Identity;
|
|
using Microsoft.AspNetCore.Builder;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Hutopy.Infrastructure.Data;
|
|
|
|
public static class InitializerExtensions
|
|
{
|
|
public static async Task InitialiseDatabaseAsync(this WebApplication app)
|
|
{
|
|
using var scope = app.Services.CreateScope();
|
|
|
|
var initializer = scope.ServiceProvider.GetRequiredService<ApplicationDbContextInitializer>();
|
|
|
|
await initializer.InitialiseAsync();
|
|
|
|
await initializer.SeedAsync();
|
|
}
|
|
}
|
|
|
|
public class ApplicationDbContextInitializer(
|
|
ILogger<ApplicationDbContextInitializer> logger,
|
|
ApplicationDbContext context,
|
|
UserManager<ApplicationUser> userManager,
|
|
RoleManager<IdentityRole> roleManager)
|
|
{
|
|
public async Task InitialiseAsync()
|
|
{
|
|
try
|
|
{
|
|
await context.Database.MigrateAsync();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "An error occurred while initialising the database.");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
public async Task SeedAsync()
|
|
{
|
|
try
|
|
{
|
|
await TrySeedAsync();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "An error occurred while seeding the database.");
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private async Task TrySeedAsync()
|
|
{
|
|
// Default roles
|
|
var administratorRole = new IdentityRole(Roles.Administrator);
|
|
|
|
if (roleManager.Roles.All(r => r.Name != administratorRole.Name))
|
|
{
|
|
await roleManager.CreateAsync(administratorRole);
|
|
}
|
|
|
|
// Default users
|
|
var administrator = new ApplicationUser
|
|
{
|
|
UserName = "administrator@localhost",
|
|
Email = "administrator@localhost",
|
|
PortraitUrl = "images/usersmedia/anonyme/profilepictures/profilePascal.jpg"
|
|
};
|
|
|
|
if (userManager.Users.All(u => u.UserName != administrator.UserName))
|
|
{
|
|
await userManager.CreateAsync(administrator, "Administrator1!");
|
|
if (!string.IsNullOrWhiteSpace(administratorRole.Name))
|
|
{
|
|
await userManager.AddToRolesAsync(administrator, new[] { administratorRole.Name });
|
|
}
|
|
}
|
|
}
|
|
}
|