using System.Text; using System.Text.Json.Serialization; using AutoMapper; using FluentValidation; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using PatientScheduling.Api.Data; using PatientScheduling.Api.Filters; using PatientScheduling.Api.Infrastructure; using PatientScheduling.Api.Mappings; using PatientScheduling.Api.Middleware; using PatientScheduling.Api.Repositories; using PatientScheduling.Api.Security; using PatientScheduling.Api.Services; using PatientScheduling.Api.Validators; using Serilog; using Serilog.Events; var builder = WebApplication.CreateBuilder(args); // ---- Logging (Serilog). Request paths only: no query strings, no patient data. ---- builder.Host.UseSerilog((hostContext, services, loggerConfig) => loggerConfig .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning) .Enrich.FromLogContext() .WriteTo.Console() .WriteTo.File(Path.Combine("logs", "pas-.log"), rollingInterval: RollingInterval.Day)); var configuration = builder.Configuration; // ---- Settings ---- builder.Services.Configure(configuration.GetSection("Jwt")); builder.Services.Configure(configuration.GetSection("Scheduling")); var jwt = configuration.GetSection("Jwt").Get() ?? throw new InvalidOperationException("The 'Jwt' configuration section is missing."); if (string.IsNullOrWhiteSpace(jwt.Key) || Encoding.UTF8.GetByteCount(jwt.Key) < 32) { throw new InvalidOperationException("Jwt:Key must be at least 32 characters long."); } // ---- Database (SQL Server by default, SQLite optional) ---- var useSqlite = string.Equals(configuration["Database:Provider"], "Sqlite", StringComparison.OrdinalIgnoreCase); builder.Services.AddDbContext(options => { if (useSqlite) { options.UseSqlite(configuration.GetConnectionString("Sqlite")); } else { options.UseSqlServer(configuration.GetConnectionString("Default")); } }); // ---- Dependency injection ---- builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); // ---- AutoMapper ---- builder.Services.AddSingleton(_ => new MapperConfiguration(cfg => cfg.AddProfile()).CreateMapper()); // ---- FluentValidation ---- builder.Services.AddValidatorsFromAssemblyContaining(); // ---- Controllers + JSON ---- builder.Services .AddControllers(options => { options.Filters.Add(); options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true; }) .AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.Converters.Add(new TimeOnlyJsonConverter()); }); // ---- CORS (Angular app origin) ---- var origins = configuration.GetSection("Cors:Origins").Get() ?? new[] { "http://localhost:4200" }; builder.Services.AddCors(options => options.AddPolicy("Angular", policy => policy .SetIsOriginAllowed(origin => origins.Contains(origin) || (Uri.TryCreate(origin, UriKind.Absolute, out var uri) && uri.IsLoopback)) .AllowAnyHeader() .AllowAnyMethod())); // ---- JWT authentication + role authorization ---- builder.Services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.MapInboundClaims = false; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = jwt.Issuer, ValidAudience = jwt.Audience, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwt.Key)), NameClaimType = "name", RoleClaimType = "role", ClockSkew = TimeSpan.FromSeconds(30) }; options.Events = new JwtBearerEvents { OnChallenge = async context => { context.HandleResponse(); await ProblemWriter.WriteAsync( context.HttpContext, StatusCodes.Status401Unauthorized, "Unauthorized", "The authentication token is missing, invalid or expired."); }, OnForbidden = context => ProblemWriter.WriteAsync( context.HttpContext, StatusCodes.Status403Forbidden, "Forbidden", "Your role is not allowed to perform this action.") }; }); builder.Services.AddAuthorization(); // ---- Swagger / OpenAPI ---- builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "Patient Appointment Scheduling API", Version = "v1" }); options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Name = "Authorization", Type = SecuritySchemeType.Http, Scheme = "bearer", BearerFormat = "JWT", In = ParameterLocation.Header, Description = "Paste the JWT returned by POST /api/auth/login." }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" } }, Array.Empty() } }); }); var app = builder.Build(); // ---- Create the database (Code First) and seed demo data ---- using (var scope = app.Services.CreateScope()) { var db = scope.ServiceProvider.GetRequiredService(); if (configuration.GetValue("Database:ResetOnStart")) { // One-off helper after a schema change: drops and recreates the database. await db.Database.EnsureDeletedAsync(); } await db.Database.EnsureCreatedAsync(); try { // Detect a database created by an older version of the app (missing columns). await db.Patients.AsNoTracking().Select(p => p.FirstName).Take(1).ToListAsync(); await db.Appointments.AsNoTracking().Select(a => a.Department).Take(1).ToListAsync(); } catch (Exception ex) when (app.Environment.IsDevelopment()) { app.Logger.LogWarning(ex, "Database schema is out of date. Recreating the development database."); await db.Database.EnsureDeletedAsync(); await db.Database.EnsureCreatedAsync(); } await DbSeeder.SeedAsync(db); } // ---- Middleware pipeline: error handler · HTTPS · CORS · JWT · role authorization ---- app.UseSerilogRequestLogging(); app.UseMiddleware(); if (!app.Environment.IsDevelopment()) { app.UseHsts(); app.UseHttpsRedirection(); } app.UseSwagger(); app.UseSwaggerUI(); app.UseCors("Angular"); app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); app.MapGet("/", () => Results.Redirect("/swagger")).ExcludeFromDescription(); app.Run();