< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 132
Coverable lines: 132
Total lines: 187
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.Seeds;
 3using FAU.DataAccess;
 4using FAU.DataAccess.Repositories;
 5using FAU.Entidades.Auditoria;
 6using FAU.Logica.Services;
 7using Microsoft.AspNetCore.Authentication.JwtBearer;
 8using Microsoft.EntityFrameworkCore;
 9using Microsoft.IdentityModel.Tokens;
 10using Microsoft.OpenApi.Models;
 11
 012var builder = WebApplication.CreateBuilder(args);
 13
 14// Log del ambiente y configuración cargada
 015var environment = builder.Environment.EnvironmentName;
 016var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
 17
 018Console.WriteLine("=====================================");
 019Console.WriteLine($"Ambiente: {environment}");
 020Console.WriteLine("=====================================");
 21
 022builder.Services.AddDbContext<ApplicationDbContext>(options =>
 023    options.UseNpgsql(connectionString));
 24
 025Auditoria.IniciarAuditoria(builder.Configuration);
 26
 27// Configuración de JWT
 028var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key no configurada");
 029var jwtIssuer = builder.Configuration["Jwt:Issuer"];
 030var jwtAudience = builder.Configuration["Jwt:Audience"];
 31
 032builder.Services.AddAuthentication(options =>
 033{
 034    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
 035    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
 036})
 037.AddJwtBearer(options =>
 038{
 039    options.RequireHttpsMetadata = false; // En producción debe ser true
 040    options.SaveToken = true;
 041    options.TokenValidationParameters = new TokenValidationParameters
 042    {
 043        ValidateIssuerSigningKey = true,
 044        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
 045        ValidateIssuer = true,
 046        ValidIssuer = jwtIssuer,
 047        ValidateAudience = true,
 048        ValidAudience = jwtAudience,
 049        ValidateLifetime = true,
 050        ClockSkew = TimeSpan.Zero
 051    };
 052});
 53
 054builder.Services.AddAuthorization();
 55
 56// Registro de repositorios
 057builder.Services.AddScoped<IUsuarioRepository, UsuarioRepository>();
 058builder.Services.AddScoped<IRolRepository, RolRepository>();
 059builder.Services.AddScoped<IPermisoRepository, PermisoRepository>();
 060builder.Services.AddScoped<IAuditoriaRepository, AuditoriaRepository>();
 061builder.Services.AddScoped<IBancoRepository, BancoRepository>();
 062builder.Services.AddScoped<IPersonalRepository, PersonalRepository>();
 063builder.Services.AddScoped<ITipoBeneficioRepository, TipoBeneficioRepository>();
 064builder.Services.AddScoped<IBeneficioSocialRepository, BeneficioSocialRepository>();
 065builder.Services.AddScoped<IIrpfRepository, IrpfRepository>();
 066builder.Services.AddScoped<IDependienteRepository, DependienteRepository>();
 067builder.Services.AddScoped<ICompensacionRepository, CompensacionRepository>();
 68
 69// Registro de servicios
 070builder.Services.AddScoped<IAuthService, AuthService>();
 071builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 072builder.Services.AddScoped<IRolService, RolService>();
 073builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 074builder.Services.AddScoped<IBancoService, BancoService>();
 075builder.Services.AddScoped<IPersonalService, PersonalService>();
 076builder.Services.AddScoped<ITipoBeneficioService, TipoBeneficioService>();
 077builder.Services.AddScoped<IBeneficioSocialService, BeneficioSocialService>();
 078builder.Services.AddScoped<IIrpfService, IrpfService>();
 079builder.Services.AddScoped<IDependienteService, DependienteService>();
 080builder.Services.AddScoped<ICompensacionService, CompensacionService>();
 81
 82// Add services to the container.
 083builder.Services.AddControllers();
 84
 85// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 086builder.Services.AddEndpointsApiExplorer();
 087builder.Services.AddHealthChecks();
 088builder.Services.AddSwaggerGen(c =>
 089{
 090    c.SwaggerDoc("v1", new OpenApiInfo
 091    {
 092        Title = "FAU Liquidación API",
 093        Version = "v1",
 094        Description = "API para el sistema de liquidación de la FAU"
 095    });
 096
 097    // Configurar Swagger para usar JWT
 098    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 099    {
 0100        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 0101        Name = "Authorization",
 0102        In = ParameterLocation.Header,
 0103        Type = SecuritySchemeType.ApiKey,
 0104        Scheme = "Bearer"
 0105    });
 0106
 0107    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 0108    {
 0109        {
 0110            new OpenApiSecurityScheme
 0111            {
 0112                Reference = new OpenApiReference
 0113                {
 0114                    Type = ReferenceType.SecurityScheme,
 0115                    Id = "Bearer"
 0116                }
 0117            },
 0118            Array.Empty<string>()
 0119        }
 0120    });
 0121});
 122
 123// Configuración de CORS (opcional, para desarrollo)
 0124builder.Services.AddCors(options =>
 0125{
 0126    options.AddPolicy("AllowAll", policy =>
 0127    {
 0128        policy.AllowAnyOrigin()
 0129              .AllowAnyMethod()
 0130              .AllowAnyHeader();
 0131    });
 0132});
 133
 0134var app = builder.Build();
 135
 136// Comando de seeding: dotnet run --seed-admin
 137// Crea el primer usuario Administrador y termina sin levantar el servidor HTTP.
 0138if (args.Contains("--seed-admin"))
 139{
 0140    using var scope = app.Services.CreateScope();
 0141    var exitCode = await SuperAdminSeeder.RunAsync(args, scope.ServiceProvider);
 0142    Environment.Exit(exitCode);
 0143    return;
 144}
 145
 146// Validar conexión a la base de datos al inicio
 0147using (var scope = app.Services.CreateScope())
 148{
 0149    var services = scope.ServiceProvider;
 150    try
 151    {
 0152        var context = services.GetRequiredService<ApplicationDbContext>();
 0153        var canConnect = context.Database.CanConnect();
 154
 0155        if (!canConnect)
 156        {
 0157            app.Logger.LogError("No se pudo conectar a la base de datos");
 0158            throw new Exception("No se pudo establecer conexión con la base de datos");
 159        }
 0160    }
 0161    catch (Exception ex)
 162    {
 0163        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0164        throw;
 165    }
 0166}
 167
 168// Configure the HTTP request pipeline.
 169// Habilitar Swagger en todos los ambientes (útil para Docker)
 0170app.UseSwagger();
 0171app.UseSwaggerUI(c =>
 0172{
 0173    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0174});
 175
 0176app.UseHttpsRedirection();
 177
 0178app.UseCors("AllowAll");
 179
 0180app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0181app.UseAuthorization();
 182
 183
 0184app.MapHealthChecks("/health");
 0185app.MapControllers();
 186
 0187app.Run();

Methods/Properties

<Main>$()