< Summary

Information
Line coverage
0%
Covered lines: 0
Uncovered lines: 111
Coverable lines: 111
Total lines: 161
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>();
 59
 60// Registro de servicios
 061builder.Services.AddScoped<IAuthService, AuthService>();
 062builder.Services.AddScoped<IUsuarioService, UsuarioService>();
 063builder.Services.AddScoped<IRolService, RolService>();
 064builder.Services.AddScoped<IAuditoriaService, AuditoriaService>();
 65
 66// Add services to the container.
 067builder.Services.AddControllers();
 68
 69// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
 070builder.Services.AddEndpointsApiExplorer();
 071builder.Services.AddHealthChecks();
 072builder.Services.AddSwaggerGen(c =>
 073{
 074    c.SwaggerDoc("v1", new OpenApiInfo
 075    {
 076        Title = "FAU Liquidación API",
 077        Version = "v1",
 078        Description = "API para el sistema de liquidación de la FAU"
 079    });
 080
 081    // Configurar Swagger para usar JWT
 082    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
 083    {
 084        Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"",
 085        Name = "Authorization",
 086        In = ParameterLocation.Header,
 087        Type = SecuritySchemeType.ApiKey,
 088        Scheme = "Bearer"
 089    });
 090
 091    c.AddSecurityRequirement(new OpenApiSecurityRequirement
 092    {
 093        {
 094            new OpenApiSecurityScheme
 095            {
 096                Reference = new OpenApiReference
 097                {
 098                    Type = ReferenceType.SecurityScheme,
 099                    Id = "Bearer"
 0100                }
 0101            },
 0102            Array.Empty<string>()
 0103        }
 0104    });
 0105});
 106
 107// Configuración de CORS (opcional, para desarrollo)
 0108builder.Services.AddCors(options =>
 0109{
 0110    options.AddPolicy("AllowAll", policy =>
 0111    {
 0112        policy.AllowAnyOrigin()
 0113              .AllowAnyMethod()
 0114              .AllowAnyHeader();
 0115    });
 0116});
 117
 0118var app = builder.Build();
 119
 120// Validar conexión a la base de datos al inicio
 0121using (var scope = app.Services.CreateScope())
 122{
 0123    var services = scope.ServiceProvider;
 124    try
 125    {
 0126        var context = services.GetRequiredService<ApplicationDbContext>();
 0127        var canConnect = context.Database.CanConnect();
 128
 0129        if (!canConnect)
 130        {
 0131            app.Logger.LogError("No se pudo conectar a la base de datos");
 0132            throw new Exception("No se pudo establecer conexión con la base de datos");
 133        }
 0134    }
 0135    catch (Exception ex)
 136    {
 0137        app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message);
 0138        throw;
 139    }
 140}
 141
 142// Configure the HTTP request pipeline.
 143// Habilitar Swagger en todos los ambientes (útil para Docker)
 0144app.UseSwagger();
 0145app.UseSwaggerUI(c =>
 0146{
 0147    c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1");
 0148});
 149
 0150app.UseHttpsRedirection();
 151
 0152app.UseCors("AllowAll");
 153
 0154app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization
 0155app.UseAuthorization();
 156
 157
 0158app.MapHealthChecks("/health");
 0159app.MapControllers();
 160
 0161app.Run();

Methods/Properties

<Main>$(System.String[])