using Socialize.Data; using Socialize.Modules.Identity.Configuration; using Socialize.Modules.Identity.Contracts; using Socialize.Modules.Identity.Data; using Socialize.Modules.Identity.Services; using Microsoft.AspNetCore.Identity; namespace Socialize.Modules.Identity; public static class DependencyInjection { public static WebApplicationBuilder AddIdentityModule( this WebApplicationBuilder builder) { builder.Services.Configure( builder.Configuration.GetRequiredSection(JwtOptions.SectionName)); builder.Services.AddAuthentication() .AddBearerToken(IdentityConstants.BearerScheme); builder.Services.AddAuthorizationBuilder(); builder.Services .Configure(options => { if (!builder.Environment.IsDevelopment()) { return; } options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequiredLength = 3; options.Password.RequiredUniqueChars = 1; }) .AddIdentityCore() .AddUserManager() .AddRoles() .AddEntityFrameworkStores() .AddApiEndpoints() .AddDefaultTokenProviders(); // Singleton services builder.Services.AddSingleton(TimeProvider.System); // Scoped services builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); return builder; } public static async Task UseIdentityModuleAsync( this IApplicationBuilder app, CancellationToken cancellationToken = default) { IServiceScopeFactory scopeFactory = app.ApplicationServices.GetRequiredService(); using IServiceScope scope = scopeFactory.CreateScope(); RoleManager roleManager = scope.ServiceProvider.GetRequiredService>(); await TrySeedAsync(roleManager); return app; } private static async Task TrySeedAsync(RoleManager roleManager) { Role administratorRole = new(KnownRoles.Administrator); if (roleManager.Roles.All(r => r.Name != administratorRole.Name)) { await roleManager.CreateAsync(administratorRole); } Role managerRole = new(KnownRoles.Manager); if (roleManager.Roles.All(r => r.Name != managerRole.Name)) { await roleManager.CreateAsync(managerRole); } Role clientRole = new(KnownRoles.Client); if (roleManager.Roles.All(r => r.Name != clientRole.Name)) { await roleManager.CreateAsync(clientRole); } Role providerRole = new(KnownRoles.Provider); if (roleManager.Roles.All(r => r.Name != providerRole.Name)) { await roleManager.CreateAsync(providerRole); } Role workspaceMemberRole = new(KnownRoles.WorkspaceMember); if (roleManager.Roles.All(r => r.Name != workspaceMemberRole.Name)) { await roleManager.CreateAsync(workspaceMemberRole); } } }