< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 124
Coverable lines: 124
Total lines: 179
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>();
 64
 65// Registro de servicios
 066builder.Services.AddScoped<IAuthService, AuthService>();
 067builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 068builder.Services.AddScoped<IRolService, RolService>();
 069builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 070builder.Services.AddScoped<IBancoService, BancoService>();
 071builder.Services.AddScoped<IPersonalService, PersonalService>();
 072builder.Services.AddScoped<ITipoBeneficioService, TipoBeneficioService>();
 73
 74// Add services to the container.
 075builder.Services.AddControllers();
 76
 77// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 078builder.Services.AddEndpointsApiExplorer();
 079builder.Services.AddHealthChecks();
 080builder.Services.AddSwaggerGen(c =>
 081{
 082    c.SwaggerDoc("v1", new OpenApiInfo
 083    {
 084        Title = "FAU Liquidación API",
 085        Version = "v1",
 086        Description = "API para el sistema de liquidación de la FAU"
 087    });
 088
 089    // Configurar Swagger para usar JWT
 090    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 091    {
 092        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 093        Name = "Authorization",
 094        In = ParameterLocation.Header,
 095        Type = SecuritySchemeType.ApiKey,
 096        Scheme = "Bearer"
 097    });
 098
 099    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 0100    {
 0101        {
 0102            new OpenApiSecurityScheme
 0103            {
 0104                Reference = new OpenApiReference
 0105                {
 0106                    Type = ReferenceType.SecurityScheme,
 0107                    Id = "Bearer"
 0108                }
 0109            },
 0110            Array.Empty<string>()
 0111        }
 0112    });
 0113});
 114
 115// Configuración de CORS (opcional, para desarrollo)
 0116builder.Services.AddCors(options =>
 0117{
 0118    options.AddPolicy("AllowAll", policy =>
 0119    {
 0120        policy.AllowAnyOrigin()
 0121              .AllowAnyMethod()
 0122              .AllowAnyHeader();
 0123    });
 0124});
 125
 0126var app = builder.Build();
 127
 128// Comando de seeding: dotnet run --seed-admin
 129// Crea el primer usuario Administrador y termina sin levantar el servidor HTTP.
 0130if (args.Contains("--seed-admin"))
 131{
 0132    using var scope = app.Services.CreateScope();
 0133    var exitCode = await SuperAdminSeeder.RunAsync(args, scope.ServiceProvider);
 0134    Environment.Exit(exitCode);
 0135    return;
 136}
 137
 138// Validar conexión a la base de datos al inicio
 0139using (var scope = app.Services.CreateScope())
 140{
 0141    var services = scope.ServiceProvider;
 142    try
 143    {
 0144        var context = services.GetRequiredService<ApplicationDbContext>();
 0145        var canConnect = context.Database.CanConnect();
 146
 0147        if (!canConnect)
 148        {
 0149            app.Logger.LogError("No se pudo conectar a la base de datos");
 0150            throw new Exception("No se pudo establecer conexión con la base de datos");
 151        }
 0152    }
 0153    catch (Exception ex)
 154    {
 0155        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0156        throw;
 157    }
 0158}
 159
 160// Configure the HTTP request pipeline.
 161// Habilitar Swagger en todos los ambientes (útil para Docker)
 0162app.UseSwagger();
 0163app.UseSwaggerUI(c =>
 0164{
 0165    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0166});
 167
 0168app.UseHttpsRedirection();
 169
 0170app.UseCors("AllowAll");
 171
 0172app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0173app.UseAuthorization();
 174
 175
 0176app.MapHealthChecks("/health");
 0177app.MapControllers();
 178
 0179app.Run();

Methods/Properties

<Main>$()