< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 116
Coverable lines: 116
Total lines: 166
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 4
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%2040%

File(s)

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

#LineLine coverage
 1using System.Text;
 2using FAU.DataAccess;
 3using FAU.DataAccess.Repositories;
 4using FAU.Entidades.Auditoria;
 5using FAU.Logica.Services;
 6using Microsoft.AspNetCore.Authentication.JwtBearer;
 7using Microsoft.EntityFrameworkCore;
 8using Microsoft.IdentityModel.Tokens;
 9using Microsoft.OpenApi.Models;
 10
 011var builder = WebApplication.CreateBuilder(args);
 12
 13// Log del ambiente y configuración cargada
 014var environment = builder.Environment.EnvironmentName;
 015var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
 16
 017Console.WriteLine("=====================================");
 018Console.WriteLine($"Ambiente: {environment}");
 019Console.WriteLine("=====================================");
 20
 021builder.Services.AddDbContext<ApplicationDbContext>(options =>
 022    options.UseNpgsql(connectionString));
 23
 024Auditoria.IniciarAuditoria(builder.Configuration);
 25
 26// Configuración de JWT
 027var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key no configurada");
 028var jwtIssuer = builder.Configuration["Jwt:Issuer"];
 029var jwtAudience = builder.Configuration["Jwt:Audience"];
 30
 031builder.Services.AddAuthentication(options =>
 032{
 033    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
 034    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
 035})
 036.AddJwtBearer(options =>
 037{
 038    options.RequireHttpsMetadata = false; // En producción debe ser true
 039    options.SaveToken = true;
 040    options.TokenValidationParameters = new TokenValidationParameters
 041    {
 042        ValidateIssuerSigningKey = true,
 043        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
 044        ValidateIssuer = true,
 045        ValidIssuer = jwtIssuer,
 046        ValidateAudience = true,
 047        ValidAudience = jwtAudience,
 048        ValidateLifetime = true,
 049        ClockSkew = TimeSpan.Zero
 050    };
 051});
 52
 053builder.Services.AddAuthorization();
 54
 55// Registro de repositorios
 056builder.Services.AddScoped<IUsuarioRepository, UsuarioRepository>();
 057builder.Services.AddScoped<IRolRepository, RolRepository>();
 058builder.Services.AddScoped<IPermisoRepository, PermisoRepository>();
 059builder.Services.AddScoped<IAuditoriaRepository, AuditoriaRepository>();
 060builder.Services.AddScoped<IBancoRepository, BancoRepository>();
 061builder.Services.AddScoped<IPersonalRepository, PersonalRepository>();
 62
 63// Registro de servicios
 064builder.Services.AddScoped<IAuthService, AuthService>();
 065builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 066builder.Services.AddScoped<IRolService, RolService>();
 067builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 068builder.Services.AddScoped<IBancoService, BancoService>();
 069builder.Services.AddScoped<IPersonalService, PersonalService>();
 70
 71// Add services to the container.
 072builder.Services.AddControllers();
 73
 74// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 075builder.Services.AddEndpointsApiExplorer();
 076builder.Services.AddHealthChecks();
 077builder.Services.AddSwaggerGen(c =>
 078{
 079    c.SwaggerDoc("v1", new OpenApiInfo
 080    {
 081        Title = "FAU Liquidación API",
 082        Version = "v1",
 083        Description = "API para el sistema de liquidación de la FAU"
 084    });
 085
 086    // Configurar Swagger para usar JWT
 087    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 088    {
 089        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 090        Name = "Authorization",
 091        In = ParameterLocation.Header,
 092        Type = SecuritySchemeType.ApiKey,
 093        Scheme = "Bearer"
 094    });
 095
 096    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 097    {
 098        {
 099            new OpenApiSecurityScheme
 0100            {
 0101                Reference = new OpenApiReference
 0102                {
 0103                    Type = ReferenceType.SecurityScheme,
 0104                    Id = "Bearer"
 0105                }
 0106            },
 0107            Array.Empty<string>()
 0108        }
 0109    });
 0110});
 111
 112// Configuración de CORS (opcional, para desarrollo)
 0113builder.Services.AddCors(options =>
 0114{
 0115    options.AddPolicy("AllowAll", policy =>
 0116    {
 0117        policy.AllowAnyOrigin()
 0118              .AllowAnyMethod()
 0119              .AllowAnyHeader();
 0120    });
 0121});
 122
 0123var app = builder.Build();
 124
 125// Validar conexión a la base de datos al inicio
 0126using (var scope = app.Services.CreateScope())
 127{
 0128    var services = scope.ServiceProvider;
 129    try
 130    {
 0131        var context = services.GetRequiredService<ApplicationDbContext>();
 0132        var canConnect = context.Database.CanConnect();
 133
 0134        if (!canConnect)
 135        {
 0136            app.Logger.LogError("No se pudo conectar a la base de datos");
 0137            throw new Exception("No se pudo establecer conexión con la base de datos");
 138        }
 0139    }
 0140    catch (Exception ex)
 141    {
 0142        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0143        throw;
 144    }
 145}
 146
 147// Configure the HTTP request pipeline.
 148// Habilitar Swagger en todos los ambientes (útil para Docker)
 0149app.UseSwagger();
 0150app.UseSwaggerUI(c =>
 0151{
 0152    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0153});
 154
 0155app.UseHttpsRedirection();
 156
 0157app.UseCors("AllowAll");
 158
 0159app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0160app.UseAuthorization();
 161
 162
 0163app.MapHealthChecks("/health");
 0164app.MapControllers();
 165
 0166app.Run();

Methods/Properties

<Main>$(System.String[])