This commit is contained in:
@@ -1,9 +1,12 @@
|
||||
using HanyadikHetVan.Data;
|
||||
using IdentityServer4.Models;
|
||||
using HanyadikHetVan.Data.Entities;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Identity;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace HanyadikHetVan
|
||||
@@ -18,8 +21,43 @@ namespace HanyadikHetVan
|
||||
{
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
await context.Database.MigrateAsync();
|
||||
var roleMgr = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
|
||||
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
|
||||
var configuration = scope.ServiceProvider.GetRequiredService<IConfiguration>();
|
||||
var adminRole = new IdentityRole("admin");
|
||||
|
||||
if (!await context.Roles.AnyAsync())
|
||||
{
|
||||
await roleMgr.CreateAsync(adminRole);
|
||||
}
|
||||
|
||||
if (!await userManager.Users.AnyAsync())
|
||||
{
|
||||
var defaultAdmin = new User
|
||||
{
|
||||
UserName = configuration.GetValue<string>("DefaultAdministrator:UserName"),
|
||||
Email = configuration.GetValue<string>("DefaultAdministrator:Email"),
|
||||
EmailConfirmed = true,
|
||||
|
||||
};
|
||||
|
||||
var result = await userManager.CreateAsync(defaultAdmin,
|
||||
configuration.GetValue<string>("DefaultAdministrator:Password"));
|
||||
if (!result.Succeeded)
|
||||
{
|
||||
throw new Exception("Failed to create the default user.");
|
||||
}
|
||||
else
|
||||
{
|
||||
var roleResult = await userManager.AddToRoleAsync(defaultAdmin, "admin");
|
||||
if (!roleResult.Succeeded)
|
||||
{
|
||||
throw new Exception("Failed to create the default user.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
await host.RunAsync();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user