< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 115
Coverable lines: 115
Total lines: 165
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<IBancoRepository, BancoRepository>();
 060builder.Services.AddScoped<IPersonalRepository, PersonalRepository>();
 61
 62// Registro de servicios
 063builder.Services.AddScoped<IAuthService, AuthService>();
 064builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 065builder.Services.AddScoped<IRolService, RolService>();
 066builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 067builder.Services.AddScoped<IBancoService, BancoService>();
 068builder.Services.AddScoped<IPersonalService, PersonalService>();
 69
 70// Add services to the container.
 071builder.Services.AddControllers();
 72
 73// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 074builder.Services.AddEndpointsApiExplorer();
 075builder.Services.AddHealthChecks();
 076builder.Services.AddSwaggerGen(c =>
 077{
 078    c.SwaggerDoc("v1", new OpenApiInfo
 079    {
 080        Title = "FAU Liquidación API",
 081        Version = "v1",
 082        Description = "API para el sistema de liquidación de la FAU"
 083    });
 084
 085    // Configurar Swagger para usar JWT
 086    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 087    {
 088        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 089        Name = "Authorization",
 090        In = ParameterLocation.Header,
 091        Type = SecuritySchemeType.ApiKey,
 092        Scheme = "Bearer"
 093    });
 094
 095    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 096    {
 097        {
 098            new OpenApiSecurityScheme
 099            {
 0100                Reference = new OpenApiReference
 0101                {
 0102                    Type = ReferenceType.SecurityScheme,
 0103                    Id = "Bearer"
 0104                }
 0105            },
 0106            Array.Empty<string>()
 0107        }
 0108    });
 0109});
 110
 111// Configuración de CORS (opcional, para desarrollo)
 0112builder.Services.AddCors(options =>
 0113{
 0114    options.AddPolicy("AllowAll", policy =>
 0115    {
 0116        policy.AllowAnyOrigin()
 0117              .AllowAnyMethod()
 0118              .AllowAnyHeader();
 0119    });
 0120});
 121
 0122var app = builder.Build();
 123
 124// Validar conexión a la base de datos al inicio
 0125using (var scope = app.Services.CreateScope())
 126{
 0127    var services = scope.ServiceProvider;
 128    try
 129    {
 0130        var context = services.GetRequiredService<ApplicationDbContext>();
 0131        var canConnect = context.Database.CanConnect();
 132
 0133        if (!canConnect)
 134        {
 0135            app.Logger.LogError("No se pudo conectar a la base de datos");
 0136            throw new Exception("No se pudo establecer conexión con la base de datos");
 137        }
 0138    }
 0139    catch (Exception ex)
 140    {
 0141        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0142        throw;
 143    }
 144}
 145
 146// Configure the HTTP request pipeline.
 147// Habilitar Swagger en todos los ambientes (útil para Docker)
 0148app.UseSwagger();
 0149app.UseSwaggerUI(c =>
 0150{
 0151    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0152});
 153
 0154app.UseHttpsRedirection();
 155
 0156app.UseCors("AllowAll");
 157
 0158app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0159app.UseAuthorization();
 160
 161
 0162app.MapHealthChecks("/health");
 0163app.MapControllers();
 164
 0165app.Run();

Methods/Properties

<Main>$(System.String[])