| | | 1 | | using System.Text; |
| | | 2 | | using FAU.DataAccess; |
| | | 3 | | using FAU.DataAccess.Repositories; |
| | | 4 | | using FAU.Entidades.Auditoria; |
| | | 5 | | using FAU.Logica.Services; |
| | | 6 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | | 7 | | using Microsoft.EntityFrameworkCore; |
| | | 8 | | using Microsoft.IdentityModel.Tokens; |
| | | 9 | | using Microsoft.OpenApi.Models; |
| | | 10 | | |
| | 0 | 11 | | var builder = WebApplication.CreateBuilder(args); |
| | | 12 | | |
| | | 13 | | // Log del ambiente y configuración cargada |
| | 0 | 14 | | var environment = builder.Environment.EnvironmentName; |
| | 0 | 15 | | var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); |
| | | 16 | | |
| | 0 | 17 | | Console.WriteLine("====================================="); |
| | 0 | 18 | | Console.WriteLine($"Ambiente: {environment}"); |
| | 0 | 19 | | Console.WriteLine("====================================="); |
| | | 20 | | |
| | 0 | 21 | | builder.Services.AddDbContext<ApplicationDbContext>(options => |
| | 0 | 22 | | options.UseNpgsql(connectionString)); |
| | | 23 | | |
| | 0 | 24 | | Auditoria.IniciarAuditoria(builder.Configuration); |
| | | 25 | | |
| | | 26 | | // Configuración de JWT |
| | 0 | 27 | | var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key no configurada"); |
| | 0 | 28 | | var jwtIssuer = builder.Configuration["Jwt:Issuer"]; |
| | 0 | 29 | | var jwtAudience = builder.Configuration["Jwt:Audience"]; |
| | | 30 | | |
| | 0 | 31 | | builder.Services.AddAuthentication(options => |
| | 0 | 32 | | { |
| | 0 | 33 | | options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; |
| | 0 | 34 | | options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; |
| | 0 | 35 | | }) |
| | 0 | 36 | | .AddJwtBearer(options => |
| | 0 | 37 | | { |
| | 0 | 38 | | options.RequireHttpsMetadata = false; // En producción debe ser true |
| | 0 | 39 | | options.SaveToken = true; |
| | 0 | 40 | | options.TokenValidationParameters = new TokenValidationParameters |
| | 0 | 41 | | { |
| | 0 | 42 | | ValidateIssuerSigningKey = true, |
| | 0 | 43 | | IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)), |
| | 0 | 44 | | ValidateIssuer = true, |
| | 0 | 45 | | ValidIssuer = jwtIssuer, |
| | 0 | 46 | | ValidateAudience = true, |
| | 0 | 47 | | ValidAudience = jwtAudience, |
| | 0 | 48 | | ValidateLifetime = true, |
| | 0 | 49 | | ClockSkew = TimeSpan.Zero |
| | 0 | 50 | | }; |
| | 0 | 51 | | }); |
| | | 52 | | |
| | 0 | 53 | | builder.Services.AddAuthorization(); |
| | | 54 | | |
| | | 55 | | // Registro de repositorios |
| | 0 | 56 | | builder.Services.AddScoped<IUsuarioRepository, UsuarioRepository>(); |
| | 0 | 57 | | builder.Services.AddScoped<IRolRepository, RolRepository>(); |
| | 0 | 58 | | builder.Services.AddScoped<IPermisoRepository, PermisoRepository>(); |
| | 0 | 59 | | builder.Services.AddScoped<IBancoRepository, BancoRepository>(); |
| | | 60 | | |
| | | 61 | | // Registro de servicios |
| | 0 | 62 | | builder.Services.AddScoped<IAuthService, AuthService>(); |
| | 0 | 63 | | builder.Services.AddScoped<IUsuarioService, UsuarioService>(); |
| | 0 | 64 | | builder.Services.AddScoped<IRolService, RolService>(); |
| | 0 | 65 | | builder.Services.AddScoped<IAuditoriaService, AuditoriaService>(); |
| | 0 | 66 | | builder.Services.AddScoped<IBancoService, BancoService>(); |
| | | 67 | | |
| | | 68 | | // Add services to the container. |
| | 0 | 69 | | builder.Services.AddControllers(); |
| | | 70 | | |
| | | 71 | | // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle |
| | 0 | 72 | | builder.Services.AddEndpointsApiExplorer(); |
| | 0 | 73 | | builder.Services.AddHealthChecks(); |
| | 0 | 74 | | builder.Services.AddSwaggerGen(c => |
| | 0 | 75 | | { |
| | 0 | 76 | | c.SwaggerDoc("v1", new OpenApiInfo |
| | 0 | 77 | | { |
| | 0 | 78 | | Title = "FAU Liquidación API", |
| | 0 | 79 | | Version = "v1", |
| | 0 | 80 | | Description = "API para el sistema de liquidación de la FAU" |
| | 0 | 81 | | }); |
| | 0 | 82 | | |
| | 0 | 83 | | // Configurar Swagger para usar JWT |
| | 0 | 84 | | c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme |
| | 0 | 85 | | { |
| | 0 | 86 | | Description = "JWT Authorization header usando el esquema Bearer. Ejemplo: \"Bearer {token}\"", |
| | 0 | 87 | | Name = "Authorization", |
| | 0 | 88 | | In = ParameterLocation.Header, |
| | 0 | 89 | | Type = SecuritySchemeType.ApiKey, |
| | 0 | 90 | | Scheme = "Bearer" |
| | 0 | 91 | | }); |
| | 0 | 92 | | |
| | 0 | 93 | | c.AddSecurityRequirement(new OpenApiSecurityRequirement |
| | 0 | 94 | | { |
| | 0 | 95 | | { |
| | 0 | 96 | | new OpenApiSecurityScheme |
| | 0 | 97 | | { |
| | 0 | 98 | | Reference = new OpenApiReference |
| | 0 | 99 | | { |
| | 0 | 100 | | Type = ReferenceType.SecurityScheme, |
| | 0 | 101 | | Id = "Bearer" |
| | 0 | 102 | | } |
| | 0 | 103 | | }, |
| | 0 | 104 | | Array.Empty<string>() |
| | 0 | 105 | | } |
| | 0 | 106 | | }); |
| | 0 | 107 | | }); |
| | | 108 | | |
| | | 109 | | // Configuración de CORS (opcional, para desarrollo) |
| | 0 | 110 | | builder.Services.AddCors(options => |
| | 0 | 111 | | { |
| | 0 | 112 | | options.AddPolicy("AllowAll", policy => |
| | 0 | 113 | | { |
| | 0 | 114 | | policy.AllowAnyOrigin() |
| | 0 | 115 | | .AllowAnyMethod() |
| | 0 | 116 | | .AllowAnyHeader(); |
| | 0 | 117 | | }); |
| | 0 | 118 | | }); |
| | | 119 | | |
| | 0 | 120 | | var app = builder.Build(); |
| | | 121 | | |
| | | 122 | | // Validar conexión a la base de datos al inicio |
| | 0 | 123 | | using (var scope = app.Services.CreateScope()) |
| | | 124 | | { |
| | 0 | 125 | | var services = scope.ServiceProvider; |
| | | 126 | | try |
| | | 127 | | { |
| | 0 | 128 | | var context = services.GetRequiredService<ApplicationDbContext>(); |
| | 0 | 129 | | var canConnect = context.Database.CanConnect(); |
| | | 130 | | |
| | 0 | 131 | | if (!canConnect) |
| | | 132 | | { |
| | 0 | 133 | | app.Logger.LogError("No se pudo conectar a la base de datos"); |
| | 0 | 134 | | throw new Exception("No se pudo establecer conexión con la base de datos"); |
| | | 135 | | } |
| | 0 | 136 | | } |
| | 0 | 137 | | catch (Exception ex) |
| | | 138 | | { |
| | 0 | 139 | | app.Logger.LogError(ex, "Error al validar la conexión a la base de datos: {Message}", ex.Message); |
| | 0 | 140 | | throw; |
| | | 141 | | } |
| | | 142 | | } |
| | | 143 | | |
| | | 144 | | // Configure the HTTP request pipeline. |
| | | 145 | | // Habilitar Swagger en todos los ambientes (útil para Docker) |
| | 0 | 146 | | app.UseSwagger(); |
| | 0 | 147 | | app.UseSwaggerUI(c => |
| | 0 | 148 | | { |
| | 0 | 149 | | c.SwaggerEndpoint("/swagger/v1/swagger.json", "FAU Liquidación API v1"); |
| | 0 | 150 | | }); |
| | | 151 | | |
| | 0 | 152 | | app.UseHttpsRedirection(); |
| | | 153 | | |
| | 0 | 154 | | app.UseCors("AllowAll"); |
| | | 155 | | |
| | 0 | 156 | | app.UseAuthentication(); // IMPORTANTE: debe ir antes de UseAuthorization |
| | 0 | 157 | | app.UseAuthorization(); |
| | | 158 | | |
| | | 159 | | |
| | 0 | 160 | | app.MapHealthChecks("/health"); |
| | 0 | 161 | | app.MapControllers(); |
| | | 162 | | |
| | 0 | 163 | | app.Run(); |