hanyadikhetvan-dotnethf/HanyadikHetVan/Program.cs
Torma Kristóf 634488c2d8
All checks were successful
continuous-integration/drone/push Build is passing
addfunfacts
2021-05-19 17:56:56 +02:00

72 lines
2.6 KiB
C#

using HanyadikHetVan.Data;
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
{
public class Program
{
public static async Task Main(string[] args)
{
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
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();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}