/// <summary> /// Metodo que ejecuta la migracion y seed en BBDD si hubiera y si el parametro enable del fichero de configuracion lo permite /// </summary> /// <param name="app"></param> /// <param name="hostingContext"></param> /// <param name="container"></param> /// <param name="environment"></param> public static void ConfigureMigration(this IApplicationBuilder app, WebHostBuilderContext hostingContext, IServiceProvider container, IWebHostEnvironment environment) { var configSectionMigration = hostingContext.Configuration.GetSection("Migration"); var configSectionSeed = hostingContext.Configuration.GetSection("Seed"); bool migrationEnable = configSectionMigration.GetValue <bool>("Enable"); bool seedEnable = configSectionSeed.GetValue <bool>("Enable"); if (migrationEnable) { using (var serviceScope = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>().CreateScope()) { AccionaCovidContext database = serviceScope.ServiceProvider.GetService <AccionaCovidContext>(); database.Database.Migrate(); } } if (seedEnable) { string path = System.IO.Directory.GetCurrentDirectory(); string rawJson = System.IO.File.ReadAllText(Path.Combine(path, $"seed.{environment.EnvironmentName}.json")); JObject parsed = JObject.Parse(rawJson); container.GetService <DataSeeder>().Seed(parsed); } }
/// <summary> /// Metodo que reasigna un nuevo contexto al repositorio. Se usa para compartir un mismo contexto entre diferentes repositorios /// para usar transacciones. /// </summary> /// <param name="newContext">Nuevo contexto a usar en el repositorio.</param> public void AssignNewContext(IUnitOfWork newContext) { //Context.Dispose(); Context = null; if (newContext is AccionaCovidContext) { Context = newContext as AccionaCovidContext; } }
public ResultadosIntegracionRepository(AccionaCovidContext context, IUserInfoAccesor userInfoAccesor, bool logicalRemove) : base(context, userInfoAccesor, logicalRemove) { }
/// <summary> /// Constructor con la inyección del contexto. /// </summary> /// <param name="context"></param> public GenericRepository(AccionaCovidContext context, IUserInfoAccesor userInfoAccesor, bool logicalRemove) { this.Context = context ?? throw new ArgumentNullException(nameof(context)); this.logicalRemove = logicalRemove; this.userInfoAccesor = userInfoAccesor ?? throw new ArgumentNullException(nameof(userInfoAccesor)); }
/// <summary> /// Constructor /// </summary> /// <param name="context"></param> /// <param name="environment"></param> /// <param name="logger"></param> public DataSeeder(AccionaCovidContext context, ILogger <DataSeeder> logger) { this.context = context; this.logger = logger; }
/// <summary> /// Añade la autenticación personalizada para la web API de Covid-19 /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <param name="infrastructureSettings"></param> public static void AddCovid19Authentication(this IServiceCollection services, IConfiguration configuration, InfrastructureSettings infrastructureSettings, IConfiguration config, Serilog.ILogger logger) { services.AddAuthentication() .AddIdentityServerAuthentication("IdentityServer", options => { configuration.Bind("InfrastructureSettings:Authentication:IdentityServerApiAuthentication", options); options.JwtBearerEvents = new JwtBearerEvents { OnTokenValidated = async context => { var claimIdentity = (ClaimsIdentity)context.Principal.Identity; var userClaim = context.Principal.Claims.FirstOrDefault(c => c.Type == "IdUser"); bool isAdmin = context.Principal.Claims.Any(c => c.Type == "role" && c.Value == "Administrator"); /* If its an admin, it doesn't have an employee */ if (isAdmin) { logger.Information("{User} is Admin", userClaim); return; } if (userClaim == null || userClaim.Value == "-1") { logger.Error("IDENTITY SERVER FAIL AUTHENTICATION -> UPN CLAIM not found in System"); context.Fail("Usuario no encontrado en el sistema"); } else { var optionsBuilder = new DbContextOptionsBuilder <AccionaCovidContext>(); optionsBuilder.UseSqlServer(config.GetConnectionString("AccionaCovidConnection")); using (ServiceProvider serviceProvider = services.BuildServiceProvider()) using (var dbContext = new AccionaCovidContext(optionsBuilder.Options, new UserInfoAccesor(), serviceProvider.GetService <IHttpContextAccessor>())) { Empleado emp = await dbContext.Empleado .Include(c => c.EmpleadoRole) .ThenInclude(c => c.IdRoleNavigation) .FirstOrDefaultAsync(c => c.Id == int.Parse(userClaim.Value)).ConfigureAwait(false); if (emp != null) { logger.Information($"IDENTITY SERVER SUCCESFULL AUTHENTICATION -> IdEmpleado {userClaim.Value}"); // añado los claims de roles foreach (var role in emp.EmpleadoRole) { claimIdentity.AddClaim(new Claim(claimIdentity.RoleClaimType, role.IdRoleNavigation.Nombre)); } } else { logger.Error($"IDENTITY SERVER FAIL AUTHENTICATION -> IdEmpleado {userClaim.Value} not found in System"); context.Fail("Usuario no econtrado en BBDD"); } } } }, }; }) .AddAzureADAuthentication("AzureAD", infrastructureSettings, config, services, logger) .AddApiKeySupport("ApiKey", infrastructureSettings.Authentication.ApiSecret); }
/// <summary> /// Añade autenticación por Azure AD a partir de las settins de infraestructura. /// </summary> /// <param name="builder"></param> /// <param name="authenticationSchema"></param> /// <param name="infrastructureSettings"></param> public static AuthenticationBuilder AddAzureADAuthentication(this AuthenticationBuilder builder, string authenticationSchema, InfrastructureSettings infrastructureSettings, IConfiguration config, IServiceCollection services, Serilog.ILogger logger) { builder.AddJwtBearer(authenticationSchema, o => { o.Authority = infrastructureSettings.Authentication.AzureADApiAuthentication.Authority; o.SaveToken = true; o.TokenValidationParameters = new TokenValidationParameters { ValidAudiences = new List <string> { infrastructureSettings.Authentication.AzureADApiAuthentication.Backend.ClientId, infrastructureSettings.Authentication.AzureADApiAuthentication.Backend.AppIdUri }, ValidateIssuer = false }; o.Events = new JwtBearerEvents { OnTokenValidated = async context => { var claimIdentity = (ClaimsIdentity)context.Principal.Identity; // obtengo info del empleado en la BBDD var optionsBuilder = new DbContextOptionsBuilder <AccionaCovidContext>(); optionsBuilder.UseSqlServer(config.GetConnectionString("AccionaCovidConnection")); using (ServiceProvider serviceProvider = services.BuildServiceProvider()) using (var dbContext = new AccionaCovidContext(optionsBuilder.Options, new UserInfoAccesor(), serviceProvider.GetService <IHttpContextAccessor>())) { var upnClaim = context.Principal.FindFirst(c => c.Type == ClaimTypes.Upn) ?? (context.Principal.FindFirst(c => c.Type == ClaimTypes.Email) ?? context.Principal.FindFirst(c => c.Type == "preferred_username")); if (upnClaim != null) { Empleado emp = await dbContext.Empleado .Include(c => c.EmpleadoRole) .ThenInclude(c => c.IdRoleNavigation) .FirstOrDefaultAsync(c => c.Upn.Trim().ToUpper() == upnClaim.Value.Trim().ToUpper()).ConfigureAwait(false); if (emp != null) { // añado los claims internos claimIdentity.AddClaim(new Claim("IdUser", emp.Id.ToString())); claimIdentity.AddClaim(new Claim("UserFullName", emp.NombreCompleto)); // añado los claims de roles foreach (var role in emp.EmpleadoRole) { claimIdentity.AddClaim(new Claim(claimIdentity.RoleClaimType, role.IdRoleNavigation.Nombre)); } } else { logger.Error($"AZURE AD FAIL AUTENTICATION -> UPN {upnClaim} not found in System"); context.Fail("Usuario no encontrado en workday"); } } else { logger.Error($"AZURE AD FAIL AUTENTICATION -> UPN IS NULL {string.Join(",", context.Principal.Claims.Select(c => $"{c.Type} - {c.Value}"))}"); context.Fail("Usuario no encontrado en el sistema"); } } }, }; }); return(builder); }