-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
234 lines (209 loc) · 9.72 KB
/
Program.cs
File metadata and controls
234 lines (209 loc) · 9.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Scalar.AspNetCore;
using System.Security.Claims;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.RateLimiting;
using Waster.Helpers;
using Waster.Hubs;
using Waster.Interfaces;
using Waster.Migrations;
using Waster.Models;
using Waster.Models.DTOs;
using Waster.Services;
namespace Waster
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add services to the container with JSON configuration
builder.Services.AddControllers()
.AddJsonOptions(options =>
{
// Handle circular references
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
// Increase max depth to handle deeply nested objects
options.JsonSerializerOptions.MaxDepth = 128;
// Optional: write indented for readability
options.JsonSerializerOptions.WriteIndented = false;
});
// Configure JWT settings
builder.Services.Configure<Jwt>(builder.Configuration.GetSection("Jwt"));
// Configure Identity
builder.Services.AddIdentity<AppUser, IdentityRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequiredLength = 8;
options.Password.RequiredUniqueChars = 1;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(3);
options.Lockout.MaxFailedAccessAttempts = 6;
options.Lockout.AllowedForNewUsers = true;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
// Configure Rate Limiting
builder.Services.AddRateLimiter(options =>
{
options.GlobalLimiter = PartitionedRateLimiter.Create<HttpContext, string>(httpContext =>
{
return RateLimitPartition.GetFixedWindowLimiter("GlobalLimiter", _ => new FixedWindowRateLimiterOptions
{
PermitLimit = 100,
Window = TimeSpan.FromMinutes(1),
QueueProcessingOrder = QueueProcessingOrder.OldestFirst,
QueueLimit = 50
});
});
options.OnRejected = async (context, cancellationToken) =>
{
context.HttpContext.Response.StatusCode = 429;
await context.HttpContext.Response.WriteAsync("Too many requests. Please try again later.", cancellationToken);
};
});
// Database Context
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
// Register Services
builder.Services.AddScoped<IClaimPostService, ClaimPostService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IFileStorageService, FileStorageService>();
builder.Services.AddScoped<IBookMarkRepository, BookMarkRepository>();
builder.Services.AddScoped<IBrowseService, BrowseService>();
builder.Services.AddScoped<IUnitOfWork, UnitOfWork>();
builder.Services.AddTransient(typeof(IBaseReporesitory<>), typeof(BaseReporesitory<>));
builder.Services.AddScoped<INotificationService, NotificationService>();
builder.Services.AddScoped<IPostService, PostService>();
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("RedisConnection");
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddAutoMapper(typeof(Program).Assembly);
builder.Services.AddScoped<IDashboardService, DashboardService>();
builder.Services.AddScoped<IAccountService, AccountService>();
// Add SignalR
builder.Services.AddSignalR();
// Configure Authentication (JWT + Google OAuth)
builder.Services.AddAuthentication(options =>
{
// JWT is the default for API endpoints
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false; // Set to true in production if using HTTPS
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(builder.Configuration["Jwt:Key"])
),ClockSkew = TimeSpan.Zero // Remove default 5 min clock skew
};
})
.AddGoogle(googleOptions =>
{
googleOptions.ClientId = builder.Configuration["Authentication:Google:ClientId"];
googleOptions.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
googleOptions.SaveTokens = true;
googleOptions.CallbackPath = "/signin-google";
});
// Configure CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowFrontend", policy =>
{
var allowedOrigins = builder.Configuration.GetSection("AllowedOrigins").Get<string[]>()
?? new[] { "http://localhost:3000" };
policy.WithOrigins(allowedOrigins)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
// Configure JSON options globally for OpenAPI
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
options.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
options.SerializerOptions.MaxDepth = 256;
});
// Add OpenAPI with type exclusions
builder.Services.AddOpenApi(options =>
{
options.AddSchemaTransformer((schema, context, cancellationToken) =>
{
// Exclude problematic Identity types from schema generation
if (context.JsonTypeInfo.Type == typeof(Microsoft.AspNetCore.Identity.IdentityUser) ||
context.JsonTypeInfo.Type == typeof(AppUser))
{
return Task.CompletedTask;
}
return Task.CompletedTask;
});
});
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Static Files with CORS
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Headers.Append("Access-Control-Allow-Origin", "*");
ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=600");
}
});
// Enable CORS
app.UseCors("AllowFrontend");
// HTTPS Redirection
app.UseHttpsRedirection();
// Routing
app.UseRouting();
// Authentication & Authorization (Order matters!)
app.UseAuthentication();
app.UseAuthorization();
// Map Controllers
app.MapHub<NotificationHub>("/notificationHub");
app.MapControllers();
// Map OpenAPI endpoint
app.MapOpenApi();
// Map Scalar API Documentation
app.MapScalarApiReference(options =>
{
options
.WithTitle("Waster API Documentation")
.WithTheme(ScalarTheme.Mars)
.WithDefaultHttpClient(ScalarTarget.CSharp, ScalarClient.HttpClient);
});
// Root endpoint redirects to documentation
app.MapGet("/", () => Results.Redirect("/scalar/v1"))
.ExcludeFromDescription();
app.MapGet("/docs", () => Results.Redirect("/scalar/v1"))
.ExcludeFromDescription();
app.MapGet("/api-docs", () => Results.Redirect("/scalar/v1"))
.ExcludeFromDescription();
app.Run();
}
}
}