| 1 | using ChapterX.Application;
|
|---|
| 2 | using ChapterX.Infrastructure;
|
|---|
| 3 | using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|---|
| 4 | using Microsoft.IdentityModel.Tokens;
|
|---|
| 5 | using System.Reflection;
|
|---|
| 6 | using System.Text;
|
|---|
| 7 |
|
|---|
| 8 | var builder = WebApplication.CreateBuilder(args);
|
|---|
| 9 |
|
|---|
| 10 | var jwtKey = builder.Configuration["Jwt:Key"];
|
|---|
| 11 | if (string.IsNullOrWhiteSpace(jwtKey))
|
|---|
| 12 | throw new InvalidOperationException("Jwt:Key is not configured. Set it via environment variable DOTNET_Jwt__Key before starting the application.");
|
|---|
| 13 |
|
|---|
| 14 | builder.Services.AddCors(options =>
|
|---|
| 15 | {
|
|---|
| 16 | options.AddPolicy("Frontend", policy =>
|
|---|
| 17 | policy.WithOrigins("http://localhost:5173", "https://localhost:5173")
|
|---|
| 18 | .AllowAnyHeader()
|
|---|
| 19 | .AllowAnyMethod()
|
|---|
| 20 | .AllowCredentials());
|
|---|
| 21 | });
|
|---|
| 22 |
|
|---|
| 23 | builder.Services.AddControllers()
|
|---|
| 24 | .AddJsonOptions(options =>
|
|---|
| 25 | {
|
|---|
| 26 | options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
|
|---|
| 27 | });
|
|---|
| 28 | builder.Services.AddEndpointsApiExplorer();
|
|---|
| 29 | builder.Services.AddSwaggerGen(options =>
|
|---|
| 30 | {
|
|---|
| 31 | options.CustomSchemaIds(type => type.FullName);
|
|---|
| 32 | options.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme
|
|---|
| 33 | {
|
|---|
| 34 | Name = "Authorization",
|
|---|
| 35 | Type = Microsoft.OpenApi.Models.SecuritySchemeType.Http,
|
|---|
| 36 | Scheme = "Bearer",
|
|---|
| 37 | BearerFormat = "JWT",
|
|---|
| 38 | In = Microsoft.OpenApi.Models.ParameterLocation.Header,
|
|---|
| 39 | Description = "Enter your JWT token"
|
|---|
| 40 | });
|
|---|
| 41 | options.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
|
|---|
| 42 | {
|
|---|
| 43 | {
|
|---|
| 44 | new Microsoft.OpenApi.Models.OpenApiSecurityScheme
|
|---|
| 45 | {
|
|---|
| 46 | Reference = new Microsoft.OpenApi.Models.OpenApiReference
|
|---|
| 47 | {
|
|---|
| 48 | Type = Microsoft.OpenApi.Models.ReferenceType.SecurityScheme,
|
|---|
| 49 | Id = "Bearer"
|
|---|
| 50 | }
|
|---|
| 51 | },
|
|---|
| 52 | Array.Empty<string>()
|
|---|
| 53 | }
|
|---|
| 54 | });
|
|---|
| 55 | });
|
|---|
| 56 |
|
|---|
| 57 | builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
|---|
| 58 | .AddJwtBearer(options =>
|
|---|
| 59 | {
|
|---|
| 60 | options.TokenValidationParameters = new TokenValidationParameters
|
|---|
| 61 | {
|
|---|
| 62 | ValidateIssuer = true,
|
|---|
| 63 | ValidateAudience = true,
|
|---|
| 64 | ValidateLifetime = true,
|
|---|
| 65 | ValidateIssuerSigningKey = true,
|
|---|
| 66 | ValidIssuer = builder.Configuration["Jwt:Issuer"],
|
|---|
| 67 | ValidAudience = builder.Configuration["Jwt:Audience"],
|
|---|
| 68 | IssuerSigningKey = new SymmetricSecurityKey(
|
|---|
| 69 | Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"]!))
|
|---|
| 70 | };
|
|---|
| 71 | });
|
|---|
| 72 | builder.Services.AddAuthorization();
|
|---|
| 73 |
|
|---|
| 74 | builder.Services.AddApplication();
|
|---|
| 75 | builder.Services.AddInfrastructure(builder.Configuration);
|
|---|
| 76 |
|
|---|
| 77 | var app = builder.Build();
|
|---|
| 78 |
|
|---|
| 79 | app.UseCors("Frontend");
|
|---|
| 80 |
|
|---|
| 81 | if (app.Environment.IsDevelopment())
|
|---|
| 82 | {
|
|---|
| 83 | app.UseSwagger();
|
|---|
| 84 | app.UseSwaggerUI();
|
|---|
| 85 | }
|
|---|
| 86 |
|
|---|
| 87 | app.UseExceptionHandler(err => err.Run(async ctx =>
|
|---|
| 88 | {
|
|---|
| 89 | var ex = ctx.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>()?.Error;
|
|---|
| 90 | ctx.Response.ContentType = "application/json";
|
|---|
| 91 |
|
|---|
| 92 | var logger = ctx.RequestServices.GetRequiredService<ILogger<Program>>();
|
|---|
| 93 |
|
|---|
| 94 | string message;
|
|---|
| 95 | int status;
|
|---|
| 96 |
|
|---|
| 97 | if (ex is UnauthorizedAccessException)
|
|---|
| 98 | {
|
|---|
| 99 | status = 401;
|
|---|
| 100 | message = ex.Message;
|
|---|
| 101 | }
|
|---|
| 102 | else if (ex is InvalidOperationException)
|
|---|
| 103 | {
|
|---|
| 104 | status = 400;
|
|---|
| 105 | message = ex.Message;
|
|---|
| 106 | }
|
|---|
| 107 | else if (ex is Microsoft.EntityFrameworkCore.DbUpdateException dbEx)
|
|---|
| 108 | {
|
|---|
| 109 | status = 400;
|
|---|
| 110 | var inner = dbEx.InnerException?.Message ?? "";
|
|---|
| 111 | if (inner.Contains("email_format"))
|
|---|
| 112 | message = "Invalid email format.";
|
|---|
| 113 | else if (inner.Contains("unique") || inner.Contains("duplicate") || inner.Contains("23505"))
|
|---|
| 114 | message = "A user with this email or username already exists.";
|
|---|
| 115 | else
|
|---|
| 116 | {
|
|---|
| 117 | logger.LogError(dbEx, "Unhandled database error");
|
|---|
| 118 | message = "A database error occurred. Please try again.";
|
|---|
| 119 | }
|
|---|
| 120 | }
|
|---|
| 121 | else
|
|---|
| 122 | {
|
|---|
| 123 | logger.LogError(ex, "Unhandled exception");
|
|---|
| 124 | status = 500;
|
|---|
| 125 | message = "An unexpected error occurred.";
|
|---|
| 126 | }
|
|---|
| 127 |
|
|---|
| 128 | ctx.Response.StatusCode = status;
|
|---|
| 129 | await ctx.Response.WriteAsJsonAsync(new { message });
|
|---|
| 130 | }));
|
|---|
| 131 |
|
|---|
| 132 | app.UseAuthentication();
|
|---|
| 133 | app.UseAuthorization();
|
|---|
| 134 | try
|
|---|
| 135 | {
|
|---|
| 136 | app.MapControllers();
|
|---|
| 137 | }
|
|---|
| 138 | catch (ReflectionTypeLoadException ex)
|
|---|
| 139 | {
|
|---|
| 140 | Console.Error.WriteLine("ReflectionTypeLoadException while mapping controllers:");
|
|---|
| 141 | foreach (var loaderEx in ex.LoaderExceptions ?? [])
|
|---|
| 142 | {
|
|---|
| 143 | Console.Error.WriteLine(loaderEx.ToString());
|
|---|
| 144 | }
|
|---|
| 145 |
|
|---|
| 146 | throw;
|
|---|
| 147 | }
|
|---|
| 148 |
|
|---|
| 149 | app.Run();
|
|---|