| | 1 | | using System.Text; |
| | 2 | | using Backend.Services.Impl; |
| | 3 | | using Microsoft.AspNetCore.Authentication.JwtBearer; |
| | 4 | | using Microsoft.EntityFrameworkCore; |
| | 5 | | using Microsoft.IdentityModel.Tokens; |
| | 6 | | using Backend.Model; |
| | 7 | | using Backend.Services; |
| | 8 | | using Serilog; |
| | 9 | | using Microsoft.AspNetCore.Diagnostics; |
| | 10 | |
|
| 0 | 11 | | var builder = WebApplication.CreateBuilder(args); |
| | 12 | |
|
| | 13 | | // Configure logging |
| | 14 | | // Use Serilog in production, built-in logging in development |
| 0 | 15 | | if (builder.Environment.IsDevelopment()) |
| | 16 | | { |
| | 17 | | // Development: built-in logging (console + debug) |
| 0 | 18 | | builder.Logging.ClearProviders(); |
| 0 | 19 | | builder.Logging.AddConsole(); |
| 0 | 20 | | builder.Logging.AddDebug(); |
| 0 | 21 | | builder.Logging.AddJsonConsole(); // optional structured output |
| | 22 | | } |
| | 23 | | else |
| | 24 | | { |
| | 25 | | // Production: use Serilog |
| 0 | 26 | | Log.Logger = new LoggerConfiguration() |
| 0 | 27 | | .Enrich.FromLogContext() |
| 0 | 28 | | .ReadFrom.Configuration(builder.Configuration) // read settings from appsettings.Production.json |
| 0 | 29 | | .WriteTo.Console() |
| 0 | 30 | | .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) |
| 0 | 31 | | .CreateLogger(); |
| | 32 | |
|
| 0 | 33 | | builder.Host.UseSerilog(); |
| | 34 | | } |
| | 35 | |
|
| | 36 | | // Pull the connection string from configuration (works for both dev & prod) |
| 0 | 37 | | var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); |
| | 38 | |
|
| 0 | 39 | | if (string.IsNullOrEmpty(connectionString)) |
| 0 | 40 | | throw new InvalidOperationException("Connection string 'DefaultConnection' is not configured in appsettings.json"); |
| | 41 | |
|
| 0 | 42 | | builder.Services.AddDbContext<Backend.PlannerContext>(options => |
| 0 | 43 | | options.UseNpgsql(connectionString)); |
| | 44 | |
|
| | 45 | |
|
| 0 | 46 | | builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) |
| 0 | 47 | | .AddJwtBearer(options => |
| 0 | 48 | | { |
| 0 | 49 | | var rawKey = builder.Configuration["Jwt:Key"]; |
| 0 | 50 | | if (string.IsNullOrEmpty(rawKey)) |
| 0 | 51 | | throw new InvalidOperationException("JWT Key is not configured in appsettings.json"); |
| 0 | 52 | |
|
| 0 | 53 | | var key = Encoding.UTF8.GetBytes(rawKey); |
| 0 | 54 | | options.TokenValidationParameters = new TokenValidationParameters |
| 0 | 55 | | { |
| 0 | 56 | | ValidateIssuer = true, |
| 0 | 57 | | ValidateAudience = true, |
| 0 | 58 | | ValidateLifetime = true, |
| 0 | 59 | | ValidateIssuerSigningKey = true, |
| 0 | 60 | | ValidIssuer = builder.Configuration["Jwt:Issuer"] ?? "Backend", |
| 0 | 61 | | ValidAudience = builder.Configuration["Jwt:Audience"] ?? "SmartMealPlannerUsers", |
| 0 | 62 | | IssuerSigningKey = new SymmetricSecurityKey(key), |
| 0 | 63 | | ClockSkew = TimeSpan.Zero // Optional: Set to zero to avoid delay in token expiration |
| 0 | 64 | | }; |
| 0 | 65 | | }); |
| | 66 | |
|
| 0 | 67 | | builder.Services.AddAuthorization(); |
| 0 | 68 | | builder.Services.AddControllers(); |
| 0 | 69 | | builder.Services.AddEndpointsApiExplorer(); |
| 0 | 70 | | builder.Services.AddSwaggerGen(); |
| | 71 | |
|
| 0 | 72 | | builder.Services.AddScoped<ITokenService, TokenService>(); |
| 0 | 73 | | builder.Services.AddScoped<ICategoryService, CategoryService>(); |
| 0 | 74 | | builder.Services.AddScoped<IUserService, UserSerivce>(); |
| 0 | 75 | | builder.Services.AddScoped<IEmailService, BrevoEmailService>(); |
| | 76 | |
|
| 0 | 77 | | var app = builder.Build(); |
| | 78 | |
|
| 0 | 79 | | app.UseSwagger(); |
| 0 | 80 | | app.UseSwaggerUI(); |
| 0 | 81 | | app.UseHttpsRedirection(); |
| 0 | 82 | | app.UseAuthentication(); |
| 0 | 83 | | app.UseAuthorization(); |
| 0 | 84 | | app.UseSerilogRequestLogging(); |
| | 85 | |
|
| 0 | 86 | | app.UseExceptionHandler(errorApp => |
| 0 | 87 | | { |
| 0 | 88 | | errorApp.Run(async context => |
| 0 | 89 | | { |
| 0 | 90 | | var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>(); |
| 0 | 91 | | var exception = exceptionHandlerPathFeature?.Error; |
| 0 | 92 | |
|
| 0 | 93 | | var logger = app.Services.GetRequiredService<ILogger<Program>>(); |
| 0 | 94 | | logger.LogError(exception, "An unhandled exception occurred."); |
| 0 | 95 | |
|
| 0 | 96 | | context.Response.StatusCode = 500; |
| 0 | 97 | | await context.Response.WriteAsJsonAsync(new { error = "An unexpected error occurred." }); |
| 0 | 98 | | }); |
| 0 | 99 | | }); |
| | 100 | |
|
| 0 | 101 | | app.MapControllers(); |
| 0 | 102 | | app.Run(); |