From a2ca63701b71eed2ffa3fff6de16b9babe8bba08 Mon Sep 17 00:00:00 2001 From: transtrike Date: Tue, 16 Feb 2021 14:46:58 +0200 Subject: Moved Default&Admin Roles insertion to DB Config --- .../Configurations/Extensions/ConfigureDatabase.cs | 27 +++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) (limited to 'src/Web/DevHive.Web') diff --git a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs index 9f02dd7..84108ae 100644 --- a/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs +++ b/src/Web/DevHive.Web/Configurations/Extensions/ConfigureDatabase.cs @@ -7,6 +7,8 @@ using Microsoft.AspNetCore.Builder; using System; using Microsoft.AspNetCore.Authentication.JwtBearer; using DevHive.Data; +using System.Linq; +using System.Threading.Tasks; namespace DevHive.Web.Configurations.Extensions { @@ -58,13 +60,36 @@ namespace DevHive.Web.Configurations.Extensions }); } - public static void UseDatabaseConfiguration(this IApplicationBuilder app) + public static async Task UseDatabaseConfiguration(this IApplicationBuilder app) { app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); + + using var serviceScope = app.ApplicationServices.CreateScope(); + using var dbContext = serviceScope.ServiceProvider.GetRequiredService(); + + dbContext.Database.Migrate(); + + var roleManager = (RoleManager)serviceScope.ServiceProvider.GetService(typeof(RoleManager)); + + if (!await dbContext.Roles.AnyAsync(x => x.Name == Role.DefaultRole)) + { + Role defaultRole = new() { Name = Role.DefaultRole }; + + await roleManager.CreateAsync(defaultRole); + } + + if (!await dbContext.Roles.AnyAsync(x => x.Name == Role.AdminRole)) + { + Role adminRole = new() { Name = Role.AdminRole }; + + await roleManager.CreateAsync(adminRole); + } + + await dbContext.SaveChangesAsync(); } } } -- cgit v1.2.3