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