< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 159
Coverable lines: 159
Total lines: 230
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 6
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
<Main>$()0%4260%

File(s)

/home/runner/work/Sistema.Liquidacion.BE/Sistema.Liquidacion.BE/FAU.API/Program.cs

#LineLine coverage
 1using System.Text;
 2using FAU.API.Middleware;
 3using FAU.API.Security;
 4using FAU.API.Seeds;
 5using FAU.DataAccess;
 6using FAU.DataAccess.Repositories;
 7using FAU.Entidades.Auditoria;
 8using FAU.Logica.Services;
 9using FAU.Logica.Services.InsumoValidators;
 10using Microsoft.AspNetCore.Authentication.JwtBearer;
 11using Microsoft.AspNetCore.Authorization;
 12using Microsoft.EntityFrameworkCore;
 13using Microsoft.IdentityModel.Tokens;
 14using Microsoft.OpenApi.Models;
 15using Microsoft.AspNetCore.HttpOverrides;
 16using Serilog;
 17
 18// Npgsql 7+ requiere Kind=UTC para timestamptz; habilitar comportamiento legacy para columnas timestamp sin zona
 019AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
 20
 021var builder = WebApplication.CreateBuilder(args);
 22
 23// Log del ambiente y configuración cargada
 024var environment = builder.Environment.EnvironmentName;
 025var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
 26
 027Console.WriteLine("=====================================");
 028Console.WriteLine($"Ambiente: {environment}");
 029Console.WriteLine("=====================================");
 30
 031builder.Services.AddDbContext<ApplicationDbContext>(options =>
 032    options.UseNpgsql(connectionString, o => o.UseQuerySplittingBehavior(QuerySplittingBehavior.SplitQuery)));
 33
 034Auditoria.IniciarAuditoria(builder.Configuration);
 35
 36// Redirigir ILogger<T> de todos los servicios/controladores hacia Serilog
 037builder.Logging.ClearProviders();
 038builder.Logging.AddSerilog(Log.Logger);
 39
 40// Configuración de JWT
 041var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key no configurada");
 042var jwtIssuer = builder.Configuration["Jwt:Issuer"];
 043var jwtAudience = builder.Configuration["Jwt:Audience"];
 44
 045builder.Services.AddAuthentication(options =>
 046{
 047    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
 048    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
 049})
 050.AddJwtBearer(options =>
 051{
 052    options.RequireHttpsMetadata = false; // En producción debe ser true
 053    options.SaveToken = true;
 054    options.TokenValidationParameters = new TokenValidationParameters
 055    {
 056        ValidateIssuerSigningKey = true,
 057        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
 058        ValidateIssuer = true,
 059        ValidIssuer = jwtIssuer,
 060        ValidateAudience = true,
 061        ValidAudience = jwtAudience,
 062        ValidateLifetime = true,
 063        ClockSkew = TimeSpan.Zero
 064    };
 065});
 66
 067builder.Services.AddAuthorization();
 68
 69// Políticas dinámicas: Permission:xxx
 070builder.Services.AddSingleton<IAuthorizationPolicyProvider, PermissionPolicyProvider>();
 071builder.Services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
 72
 73// HttpContext + Current user context (auditoría)
 074builder.Services.AddHttpContextAccessor();
 075builder.Services.AddScoped<FAU.Logica.Services.ICurrentUserContext, FAU.API.Services.CurrentUserContext>();
 76
 77// Registro de repositorios
 078builder.Services.AddScoped<IUsuarioRepository, UsuarioRepository>();
 079builder.Services.AddScoped<IRolRepository, RolRepository>();
 080builder.Services.AddScoped<IPermisoRepository, PermisoRepository>();
 081builder.Services.AddScoped<IAuditoriaRepository, AuditoriaRepository>();
 082builder.Services.AddScoped<IBancoRepository, BancoRepository>();
 083builder.Services.AddScoped<IPersonalRepository, PersonalRepository>();
 084builder.Services.AddScoped<ITipoBeneficioRepository, TipoBeneficioRepository>();
 085builder.Services.AddScoped<IBeneficioSocialRepository, BeneficioSocialRepository>();
 086builder.Services.AddScoped<IIrpfRepository, IrpfRepository>();
 087builder.Services.AddScoped<IDependienteRepository, DependienteRepository>();
 088builder.Services.AddScoped<ICompensacionRepository, CompensacionRepository>();
 089builder.Services.AddScoped<IParametroLiquidacionRepository, ParametroLiquidacionRepository>();
 090builder.Services.AddScoped<IPeriodosRepository, PeriodosRepository>();
 091builder.Services.AddScoped<INovedadPeriodoRepository, NovedadPeriodoRepository>();
 092builder.Services.AddScoped<ISnapshotsRepository, SnapshotsRepository>();
 93
 94// Registro de servicios
 095builder.Services.AddScoped<IAuthService, AuthService>();
 096builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 097builder.Services.AddScoped<IRolService, RolService>();
 098builder.Services.AddScoped<IAuditoriaCatalogoResolver, AuditoriaCatalogoResolver>();
 099builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 0100builder.Services.AddScoped<IBancoService, BancoService>();
 0101builder.Services.AddScoped<IPersonalService, PersonalService>();
 0102builder.Services.AddScoped<ITipoBeneficioService, TipoBeneficioService>();
 0103builder.Services.AddScoped<IBeneficioSocialService, BeneficioSocialService>();
 0104builder.Services.AddScoped<IDependienteService, DependienteService>();
 0105builder.Services.AddScoped<ICompensacionService, CompensacionService>();
 0106builder.Services.AddScoped<IParametroLiquidacionService, ParametroLiquidacionService>();
 0107builder.Services.AddScoped<IInsumoValidator, LotesCompensacionValidator>();
 0108builder.Services.AddScoped<IInsumoValidator, BeneficiosSocialesValidator>();
 0109builder.Services.AddScoped<IInsumoValidator, NovedadesPeriodoValidator>();
 0110builder.Services.AddScoped<IInsumoValidator, TablasReferenciaValidator>();
 0111builder.Services.AddScoped<IInsumoEvaluador, InsumoEvaluador>();
 0112builder.Services.AddScoped<IInsumosPeriodoLoader, InsumosPeriodoLoader>();
 0113builder.Services.AddScoped<IPeriodoService, PeriodoService>();
 0114builder.Services.AddScoped<INovedadPeriodoService, NovedadPeriodoService>();
 0115builder.Services.AddScoped<IPeriodoGuard, PeriodoGuard>();
 0116builder.Services.AddScoped<ILiquidacionService, LiquidacionService>();
 117
 118// Add services to the container.
 0119builder.Services.AddControllers();
 120
 121// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 0122builder.Services.AddEndpointsApiExplorer();
 0123builder.Services.AddHealthChecks();
 0124builder.Services.AddSwaggerGen(c =>
 0125{
 0126    c.SwaggerDoc("v1", new OpenApiInfo
 0127    {
 0128        Title = "FAU Liquidación API",
 0129        Version = "v1",
 0130        Description = "API para el sistema de liquidación de la FAU"
 0131    });
 0132
 0133    // Configurar Swagger para usar JWT
 0134    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 0135    {
 0136        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 0137        Name = "Authorization",
 0138        In = ParameterLocation.Header,
 0139        Type = SecuritySchemeType.ApiKey,
 0140        Scheme = "Bearer"
 0141    });
 0142
 0143    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 0144    {
 0145        {
 0146            new OpenApiSecurityScheme
 0147            {
 0148                Reference = new OpenApiReference
 0149                {
 0150                    Type = ReferenceType.SecurityScheme,
 0151                    Id = "Bearer"
 0152                }
 0153            },
 0154            Array.Empty<string>()
 0155        }
 0156    });
 0157});
 158
 159// Configuración de CORS (opcional, para desarrollo)
 0160builder.Services.AddCors(options =>
 0161{
 0162    options.AddPolicy("AllowAll", policy =>
 0163    {
 0164        policy.AllowAnyOrigin()
 0165              .AllowAnyMethod()
 0166              .AllowAnyHeader();
 0167    });
 0168});
 169
 0170var app = builder.Build();
 171
 172// Forwarded headers (si está detrás de proxy / ingress)
 0173app.UseForwardedHeaders(new ForwardedHeadersOptions
 0174{
 0175    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
 0176});
 177
 178// Comando de seeding: dotnet run --seed-admin
 179// Crea el primer usuario Administrador y termina sin levantar el servidor HTTP.
 0180if (args.Contains("--seed-admin"))
 181{
 0182    using var scope = app.Services.CreateScope();
 0183    var exitCode = await SuperAdminSeeder.RunAsync(args, scope.ServiceProvider);
 0184    Environment.Exit(exitCode);
 0185    return;
 186}
 187
 188// Validar conexión a la base de datos al inicio
 0189using (var scope = app.Services.CreateScope())
 190{
 0191    var services = scope.ServiceProvider;
 192    try
 193    {
 0194        var context = services.GetRequiredService<ApplicationDbContext>();
 0195        var canConnect = context.Database.CanConnect();
 196
 0197        if (!canConnect)
 198        {
 0199            app.Logger.LogError("No se pudo conectar a la base de datos");
 0200            throw new Exception("No se pudo establecer conexión con la base de datos");
 201        }
 0202    }
 0203    catch (Exception ex)
 204    {
 0205        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0206        throw;
 207    }
 0208}
 209
 210// Configure the HTTP request pipeline.
 211// Habilitar Swagger en todos los ambientes (útil para Docker)
 0212app.UseSwagger();
 0213app.UseSwaggerUI(c =>
 0214{
 0215    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0216});
 217
 0218app.UseHttpsRedirection();
 219
 0220app.UseCors("AllowAll");
 221
 0222app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0223app.UseMiddleware<LogUserEnricherMiddleware>(); // Enriquece logs con el usuario autenticado
 0224app.UseAuthorization();
 225
 226
 0227app.MapHealthChecks("/health");
 0228app.MapControllers();
 229
 0230app.Run();

Methods/Properties

<Main>$()