DotNet_Capstone_Project/.Net Capstone Project/Program.cs
2026-10-19 09:11:57 +00:00

229 lines
7.8 KiB
C#

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<JwtSettings>(configuration.GetSection("Jwt"));
builder.Services.Configure<SchedulingSettings>(configuration.GetSection("Scheduling"));
var jwt = configuration.GetSection("Jwt").Get<JwtSettings>()
?? 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<AppDbContext>(options =>
{
if (useSqlite)
{
options.UseSqlite(configuration.GetConnectionString("Sqlite"));
}
else
{
options.UseSqlServer(configuration.GetConnectionString("Default"));
}
});
// ---- Dependency injection ----
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ICurrentUser, CurrentUser>();
builder.Services.AddScoped<ITokenService, TokenService>();
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IPatientRepository, PatientRepository>();
builder.Services.AddScoped<IDoctorRepository, DoctorRepository>();
builder.Services.AddScoped<IAppointmentRepository, AppointmentRepository>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IPatientService, PatientService>();
builder.Services.AddScoped<IDoctorService, DoctorService>();
builder.Services.AddScoped<IAppointmentService, AppointmentService>();
// ---- AutoMapper ----
builder.Services.AddSingleton<IMapper>(_ =>
new MapperConfiguration(cfg => cfg.AddProfile<MappingProfile>()).CreateMapper());
// ---- FluentValidation ----
builder.Services.AddValidatorsFromAssemblyContaining<LoginRequestValidator>();
// ---- Controllers + JSON ----
builder.Services
.AddControllers(options =>
{
options.Filters.Add<ValidationFilter>();
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<string[]>()
?? 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<string>()
}
});
});
var app = builder.Build();
// ---- Create the database (Code First) and seed demo data ----
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
if (configuration.GetValue<bool>("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<GlobalExceptionMiddleware>();
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();