Skip to content

Commit

Permalink
Move Seed Users to Db.Migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
mythz committed Nov 1, 2023
1 parent 81c2e5a commit 2a8d48d
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 95 deletions.
93 changes: 1 addition & 92 deletions MyApp/Configure.Auth.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
using Microsoft.AspNetCore.Identity;
using ServiceStack;
using ServiceStack.Auth;
using MyApp.Data;
using MyApp.ServiceModel;

[assembly: HostingStartup(typeof(MyApp.ConfigureAuth))]

Expand All @@ -11,98 +8,10 @@ namespace MyApp;
public class ConfigureAuth : IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder
.ConfigureAppHost(appHost =>
.ConfigureAppHost(appHost =>
{
appHost.Plugins.Add(new AuthFeature(IdentityAuth.For<ApplicationUser>(options => {
options.EnableCredentialsAuth = true;
})));

AddSeedUsers(appHost.GetApp()).Wait();
});

private async Task AddSeedUsers(IApplicationBuilder app)
{
var scopeFactory = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>();

using var scope = scopeFactory.CreateScope();
// Ensure EF Migrations has created Identity tables before using them.
var dbContext = scope.ServiceProvider.GetService<ApplicationDbContext>();
var dbCreated = await dbContext?.Database.EnsureCreatedAsync()!;
if (!dbCreated)
return;
//initializing custom roles
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] allRoles = [Roles.Admin, Roles.Manager, Roles.Employee];

void assertResult(IdentityResult result)
{
if (!result.Succeeded)
throw new Exception(result.Errors.First().Description);
}

async Task EnsureUserAsync(ApplicationUser user, string password, string[]? roles = null)
{
var existingUser = await userManager.FindByEmailAsync(user.Email!);
if (existingUser != null) return;

await userManager!.CreateAsync(user, password);
if (roles?.Length > 0)
{
var newUser = await userManager.FindByEmailAsync(user.Email!);
assertResult(await userManager.AddToRolesAsync(user, roles));
}
}

foreach (var roleName in allRoles)
{
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
assertResult(await roleManager.CreateAsync(new IdentityRole(roleName)));
}
}

await EnsureUserAsync(new ApplicationUser
{
DisplayName = "Test User",
Email = "[email protected]",
UserName = "[email protected]",
FirstName = "Test",
LastName = "User",
EmailConfirmed = true,
}, "p@55wOrd");

await EnsureUserAsync(new ApplicationUser
{
DisplayName = "Test Employee",
Email = "[email protected]",
UserName = "[email protected]",
FirstName = "Test",
LastName = "Employee",
EmailConfirmed = true,
}, "p@55wOrd", [Roles.Employee]);

await EnsureUserAsync(new ApplicationUser
{
DisplayName = "Test Manager",
Email = "[email protected]",
UserName = "[email protected]",
FirstName = "Test",
LastName = "Manager",
EmailConfirmed = true,
}, "p@55wOrd", [Roles.Manager]);

await EnsureUserAsync(new ApplicationUser
{
DisplayName = "Admin User",
Email = "[email protected]",
UserName = "[email protected]",
FirstName = "Admin",
LastName = "User",
EmailConfirmed = true,
}, "p@55wOrd", allRoles);
}

}
99 changes: 96 additions & 3 deletions MyApp/Configure.Db.Migrations.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MyApp.Data;
using MyApp.Migrations;
using MyApp.ServiceModel;
using ServiceStack;
using ServiceStack.Data;
using ServiceStack.OrmLite;
Expand All @@ -16,17 +19,107 @@ public void Configure(IWebHostBuilder builder) => builder
var migrator = new Migrator(appHost.Resolve<IDbConnectionFactory>(), typeof(Migration1000).Assembly);
AppTasks.Register("migrate", _ =>
{
// Run EF Migrations
var log = appHost.GetApplicationServices().GetRequiredService<ILogger<ConfigureDbMigrations>>();

log.LogInformation("Running EF Migrations...");
var scopeFactory = appHost.GetApplicationServices().GetRequiredService<IServiceScopeFactory>();
using (var scope = scopeFactory.CreateScope())
{
using var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
db.Database.EnsureCreated();
var dbJustCreated = db.Database.EnsureCreated();
db.Database.Migrate();

// Only seed users if DB was just created
if (dbJustCreated)
{
log.LogInformation("Adding Seed Users...");
AddSeedUsers(scope.ServiceProvider).Wait();
}
}
// Run OrmLite Migrations

log.LogInformation("Running OrmLite Migrations...");
migrator.Run();
});
AppTasks.Register("migrate.revert", args => migrator.Revert(args[0]));
AppTasks.Run();
});

private async Task AddSeedUsers(IServiceProvider services)
{
var scopeFactory = services.GetRequiredService<IServiceScopeFactory>();

//initializing custom roles
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
string[] allRoles = [Roles.Admin, Roles.Manager, Roles.Employee];

void assertResult(IdentityResult result)
{
if (!result.Succeeded)
throw new Exception(result.Errors.First().Description);
}

async Task EnsureUserAsync(ApplicationUser user, string password, string[]? roles = null)
{
var existingUser = await userManager.FindByEmailAsync(user.Email!);
if (existingUser != null) return;

await userManager!.CreateAsync(user, password);
if (roles?.Length > 0)
{
var newUser = await userManager.FindByEmailAsync(user.Email!);
assertResult(await userManager.AddToRolesAsync(user, roles));
}
}

foreach (var roleName in allRoles)
{
var roleExist = await roleManager.RoleExistsAsync(roleName);
if (!roleExist)
{
//create the roles and seed them to the database: Question 1
assertResult(await roleManager.CreateAsync(new IdentityRole(roleName)));
}
}

await EnsureUserAsync(new ApplicationUser
{
DisplayName = "Test User",
Email = "[email protected]",
UserName = "[email protected]",
FirstName = "Test",
LastName = "User",
EmailConfirmed = true,
}, "p@55wOrd");

await EnsureUserAsync(new ApplicationUser
{
DisplayName = "Test Employee",
Email = "[email protected]",
UserName = "[email protected]",
FirstName = "Test",
LastName = "Employee",
EmailConfirmed = true,
}, "p@55wOrd", [Roles.Employee]);

await EnsureUserAsync(new ApplicationUser
{
DisplayName = "Test Manager",
Email = "[email protected]",
UserName = "[email protected]",
FirstName = "Test",
LastName = "Manager",
EmailConfirmed = true,
}, "p@55wOrd", [Roles.Manager]);

await EnsureUserAsync(new ApplicationUser
{
DisplayName = "Admin User",
Email = "[email protected]",
UserName = "[email protected]",
FirstName = "Admin",
LastName = "User",
EmailConfirmed = true,
}, "p@55wOrd", allRoles);
}
}

0 comments on commit 2a8d48d

Please sign in to comment.