< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 113
Coverable lines: 113
Total lines: 163
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>();
 60
 61// Registro de servicios
 062builder.Services.AddScoped<IAuthService, AuthService>();
 063builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 064builder.Services.AddScoped<IRolService, RolService>();
 065builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 066builder.Services.AddScoped<IBancoService, BancoService>();
 67
 68// Add services to the container.
 069builder.Services.AddControllers();
 70
 71// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 072builder.Services.AddEndpointsApiExplorer();
 073builder.Services.AddHealthChecks();
 074builder.Services.AddSwaggerGen(c =>
 075{
 076    c.SwaggerDoc("v1", new OpenApiInfo
 077    {
 078        Title = "FAU Liquidación API",
 079        Version = "v1",
 080        Description = "API para el sistema de liquidación de la FAU"
 081    });
 082
 083    // Configurar Swagger para usar JWT
 084    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 085    {
 086        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 087        Name = "Authorization",
 088        In = ParameterLocation.Header,
 089        Type = SecuritySchemeType.ApiKey,
 090        Scheme = "Bearer"
 091    });
 092
 093    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 094    {
 095        {
 096            new OpenApiSecurityScheme
 097            {
 098                Reference = new OpenApiReference
 099                {
 0100                    Type = ReferenceType.SecurityScheme,
 0101                    Id = "Bearer"
 0102                }
 0103            },
 0104            Array.Empty<string>()
 0105        }
 0106    });
 0107});
 108
 109// Configuración de CORS (opcional, para desarrollo)
 0110builder.Services.AddCors(options =>
 0111{
 0112    options.AddPolicy("AllowAll", policy =>
 0113    {
 0114        policy.AllowAnyOrigin()
 0115              .AllowAnyMethod()
 0116              .AllowAnyHeader();
 0117    });
 0118});
 119
 0120var app = builder.Build();
 121
 122// Validar conexión a la base de datos al inicio
 0123using (var scope = app.Services.CreateScope())
 124{
 0125    var services = scope.ServiceProvider;
 126    try
 127    {
 0128        var context = services.GetRequiredService<ApplicationDbContext>();
 0129        var canConnect = context.Database.CanConnect();
 130
 0131        if (!canConnect)
 132        {
 0133            app.Logger.LogError("No se pudo conectar a la base de datos");
 0134            throw new Exception("No se pudo establecer conexión con la base de datos");
 135        }
 0136    }
 0137    catch (Exception ex)
 138    {
 0139        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0140        throw;
 141    }
 142}
 143
 144// Configure the HTTP request pipeline.
 145// Habilitar Swagger en todos los ambientes (útil para Docker)
 0146app.UseSwagger();
 0147app.UseSwaggerUI(c =>
 0148{
 0149    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0150});
 151
 0152app.UseHttpsRedirection();
 153
 0154app.UseCors("AllowAll");
 155
 0156app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0157app.UseAuthorization();
 158
 159
 0160app.MapHealthChecks("/health");
 0161app.MapControllers();
 162
 0163app.Run();

Methods/Properties

<Main>$(System.String[])