source: ChapterX.API/Program.cs@ acf690c

main
Last change on this file since acf690c was acf690c, checked in by kikisrbinoska <srbinoskakristina07@…>, 4 months ago

Added fixes for the login,stories management and reading lists

  • Property mode set to 100644
File size: 4.0 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
10builder.Services.AddCors(options =>
11{
12 options.AddPolicy("Frontend", policy =>
13 policy.WithOrigins("http://localhost:5173", "https://localhost:5173")
14 .AllowAnyHeader()
15 .AllowAnyMethod());
16});
17
18builder.Services.AddControllers()
19 .AddJsonOptions(options =>
20 {
21 options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.IgnoreCycles;
22 });
23builder.Services.AddEndpointsApiExplorer();
24builder.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
52builder.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 });
67builder.Services.AddAuthorization();
68
69builder.Services.AddApplication();
70builder.Services.AddInfrastructure(builder.Configuration);
71
72var app = builder.Build();
73
74app.UseCors("Frontend");
75
76if (app.Environment.IsDevelopment())
77{
78 app.UseSwagger();
79 app.UseSwaggerUI();
80}
81
82app.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
121app.UseAuthentication();
122app.UseAuthorization();
123try
124{
125 app.MapControllers();
126}
127catch (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
138app.Run();
Note: See TracBrowser for help on using the repository browser.