source: ChapterX.API/Program.cs@ 0b502c2

main
Last change on this file since 0b502c2 was 0b502c2, checked in by kikisrbinoska <srbinoskakristina07@…>, 12 days ago

Fixed user profile and reading lists

  • 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.UseCors("Frontend");
80
81if (app.Environment.IsDevelopment())
82{
83 app.UseSwagger();
84 app.UseSwaggerUI();
85}
86
87app.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
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.