source: ChapterX.API/Program.cs@ 99c1e45

main
Last change on this file since 99c1e45 was 99c1e45, checked in by kikisrbinoska <srbinoskakristina07@…>, 11 days ago

Fixed writer section and admin management

  • Property mode set to 100644
File size: 4.5 KB
Line 
1using ChapterX.Application;
2using ChapterX.Infrastructure;
3using Microsoft.AspNetCore.Authentication.JwtBearer;
4using Microsoft.IdentityModel.Tokens;
5using System.Reflection;
6using System.Text;
7
8var builder = WebApplication.CreateBuilder(args);
9
10var jwtKey = builder.Configuration["Jwt:Key"];
11if (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
14builder.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
23builder.Services.AddControllers()
24 .AddJsonOptions(options =>
25 {
26 options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
27 });
28builder.Services.AddEndpointsApiExplorer();
29builder.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
57builder.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 });
72builder.Services.AddAuthorization();
73
74builder.Services.AddApplication();
75builder.Services.AddInfrastructure(builder.Configuration);
76
77var app = builder.Build();
78
79app.UseExceptionHandler(err => err.Run(async ctx =>
80{
81 var ex = ctx.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>()?.Error;
82 ctx.Response.ContentType = "application/json";
83
84 var logger = ctx.RequestServices.GetRequiredService<ILogger<Program>>();
85
86 string message;
87 int status;
88
89 if (ex is UnauthorizedAccessException)
90 {
91 status = 401;
92 message = ex.Message;
93 }
94 else if (ex is InvalidOperationException)
95 {
96 status = 400;
97 message = ex.Message;
98 }
99 else if (ex is Microsoft.EntityFrameworkCore.DbUpdateException dbEx)
100 {
101 status = 400;
102 var inner = dbEx.InnerException?.Message ?? "";
103 if (inner.Contains("email_format"))
104 message = "Invalid email format.";
105 else if (inner.Contains("unique") || inner.Contains("duplicate") || inner.Contains("23505"))
106 message = "A user with this email or username already exists.";
107 else
108 {
109 logger.LogError(dbEx, "Unhandled database error");
110 message = "A database error occurred. Please try again.";
111 }
112 }
113 else
114 {
115 logger.LogError(ex, "Unhandled exception");
116 status = 500;
117 message = "An unexpected error occurred.";
118 }
119
120 ctx.Response.StatusCode = status;
121 await ctx.Response.WriteAsJsonAsync(new { message });
122}));
123
124app.UseCors("Frontend");
125
126if (app.Environment.IsDevelopment())
127{
128 app.UseSwagger();
129 app.UseSwaggerUI();
130}
131
132app.UseAuthentication();
133app.UseAuthorization();
134try
135{
136 app.MapControllers();
137}
138catch (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
149app.Run();
Note: See TracBrowser for help on using the repository browser.