You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
WebServices/src/IdentitySvc/SeedData.cs

82 lines
2.5 KiB

using System.Security.Claims;
using IdentityModel;
using IdentitySvc.Data;
using IdentitySvc.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Serilog;
namespace IdentitySvc;
public class SeedData
{
public static void EnsureSeedData(WebApplication app)
{
using var scope = app.Services.GetRequiredService<IServiceScopeFactory>().CreateScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
context.Database.Migrate();
var userMgr = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (userMgr.Users.Any()) return;
var alice = userMgr.FindByNameAsync("alice").Result;
if (alice == null)
{
alice = new ApplicationUser
{
UserName = "alice",
Email = "AliceSmith@email.com",
EmailConfirmed = true,
};
var result = userMgr.CreateAsync(alice, "Pass123$").Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
result = userMgr.AddClaimsAsync(alice, new Claim[]{
new Claim(JwtClaimTypes.Name, "Alice Smith"),
}).Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
Log.Debug("alice created");
}
else
{
Log.Debug("alice already exists");
}
var bob = userMgr.FindByNameAsync("bob").Result;
if (bob == null)
{
bob = new ApplicationUser
{
UserName = "bob",
Email = "BobSmith@email.com",
EmailConfirmed = true
};
var result = userMgr.CreateAsync(bob, "Pass123$").Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
result = userMgr.AddClaimsAsync(bob, new Claim[]{
new Claim(JwtClaimTypes.Name, "Bob Smith"),
}).Result;
if (!result.Succeeded)
{
throw new Exception(result.Errors.First().Description);
}
Log.Debug("bob created");
}
else
{
Log.Debug("bob already exists");
}
}
}