using System; using System.Security.Claims; using IOL.Fagprove.Data; using IOL.Fagprove.Data.Enums; using IOL.Fagprove.Services; using IOL.Fagprove.Services.Interfaces; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using StackExchange.Redis; namespace IOL.Fagprove.Utilities { public static class ServicesCollectionExtensions { public static void AddServices(this IServiceCollection services) { services.AddScoped(); services.AddScoped(); } public static void AddAppDbContext(this IServiceCollection services, IConfiguration config) { services.AddDbContext(options => { options.UseMySql(config.GetConnectionString(), builder => builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(60), null)); #if DEBUG options.EnableSensitiveDataLogging(); #endif }); } public static void AddDataProtectionWithRedis(this IServiceCollection services, IConfiguration config) { var accessKey = config.GetValue("REDIS_KEY"); if (!accessKey.IsPresent()) return; var redis = ConnectionMultiplexer.Connect( $"aredis.cache.net:6380,password={accessKey},ssl=True,abortConnect=False"); services.AddDataProtection().PersistKeysToStackExchangeRedis(redis, "IOL.Fagprove.DataProtectionKeys"); } public static void AddInternalUserPolicies(this IServiceCollection services) { services.Configure(options => { options.AddPolicy(UserRole.Administrator.ToString(), policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(ClaimTypes.Role, UserRole.Administrator.ToString()); }); options.AddPolicy(UserRole.Basic.ToString(), policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim(ClaimTypes.Role, new string[] {UserRole.Basic.ToString()}); }); }); } } }