Newsbot.Collector/Newsbot.Collector.Api/Startup/DatabaseStartup.cs

62 lines
2.5 KiB
C#

using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Newsbot.Collector.Api.Domain.Consts;
using Newsbot.Collector.Database;
using Newsbot.Collector.Database.Repositories;
using Newsbot.Collector.Domain.Interfaces;
using Newsbot.Collector.Services;
namespace Newsbot.Collector.Api.Startup;
public class DatabaseStartup
{
public static void BuildDatabase(IServiceCollection services, IConfiguration config)
{
var dbconn = config.GetConnectionString("Database");
services.AddDbContext<DatabaseContext>(o => o.UseNpgsql(dbconn ?? ""));
// Add identity to our ef connection
services.AddIdentity<IdentityUser, IdentityRole>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DatabaseContext>();
}
public static void InjectTableClasses(IServiceCollection services)
{
services.AddScoped<IArticlesRepository, ArticlesTable>();
services.AddScoped<IDiscordQueueRepository, DiscordQueueTable>();
services.AddScoped<IDiscordWebHooksRepository, DiscordWebhooksTable>();
services.AddScoped<IIconsRepository, IconsTable>();
services.AddScoped<ISourcesRepository, SourcesTable>();
services.AddScoped<IDiscordNotificationRepository, DiscordNotificationTable>();
services.AddScoped<IUserSourceSubscription, UserSourceSubscriptionTable>();
services.AddScoped<IRefreshTokenRepository, RefreshTokenTable>();
services.AddScoped<IAuthorTable, AuthorsTable>();
}
public static void InjectIdentityService(IServiceCollection services)
{
// Configure Identity
services.AddScoped<IIdentityService, IdentityService>();
}
public static async Task RunDatabaseMigrationsAsync(IServiceScope serviceScope)
{
var dbContext = serviceScope.ServiceProvider.GetRequiredService<DatabaseContext>();
await dbContext.Database.MigrateAsync();
}
public static async Task InjectIdentityRolesAsync(IServiceScope serviceScope)
{
var roleManager = serviceScope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
if (!await roleManager.RoleExistsAsync(Authorization.AdministratorsRole))
{
await roleManager.CreateAsync(new IdentityRole(Authorization.AdministratorsRole));
}
if (!await roleManager.RoleExistsAsync(Authorization.UsersRole))
{
await roleManager.CreateAsync(new IdentityRole(Authorization.UsersRole));
}
}
}