100 lines
2.9 KiB
C#
100 lines
2.9 KiB
C#
using Hutopy.Domain.Constants;
|
|
using Hutopy.Domain.Entities;
|
|
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" };
|
|
|
|
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 });
|
|
}
|
|
}
|
|
|
|
// Default data
|
|
// Seed, if necessary
|
|
if (!context.TodoLists.Any())
|
|
{
|
|
context.TodoLists.Add(new TodoList
|
|
{
|
|
Title = "Todo List",
|
|
Items =
|
|
{
|
|
new TodoItem { Title = "Make a todo list 📃" },
|
|
new TodoItem { Title = "Check off the first item ✅" },
|
|
new TodoItem { Title = "Realise you've already done two things on the list! 🤯"},
|
|
new TodoItem { Title = "Reward yourself with a nice, long nap 🏆" },
|
|
}
|
|
});
|
|
|
|
await context.SaveChangesAsync();
|
|
}
|
|
}
|
|
}
|