-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
262 lines (211 loc) · 8.73 KB
/
Program.cs
File metadata and controls
262 lines (211 loc) · 8.73 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
using EgyptOnline.Data;
using Microsoft.AspNetCore.SignalR;
using EgyptOnline.Models;
using EgyptOnline.Extensions;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Serilog;
using Serilog.Events;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.Extensions.FileProviders;
using StackExchange.Redis;
using EgyptOnline.Utilities;
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
var builder = WebApplication.CreateBuilder(args);
// ---------- Serilog Configuration ----------
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.Console(
restrictedToMinimumLevel: LogEventLevel.Information,
outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.WriteTo.File(
"Logs/log-.txt",
rollingInterval: RollingInterval.Day,
restrictedToMinimumLevel: LogEventLevel.Debug,
outputTemplate: "[{Timestamp:yyyy-MM-dd HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}{NewLine}")
.CreateLogger();
builder.Host.UseSerilog();
try
{
Log.Information("Starting application in {Environment} environment", builder.Environment.EnvironmentName);
// ---------- Configuration ----------
builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
// ---------- Services ----------
builder.Services.AddControllers();
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration["RedisSettings:Configuration"];
options.InstanceName = builder.Configuration["RedisSettings:InstanceName"];
});
// IConnectionMultiplexer using settings from configuration
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
{
return ConnectionMultiplexer.Connect(builder.Configuration["RedisSettings:Configuration"]);
});
builder.Services.AddDistributedMemoryCache();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddIdentity<User, IdentityRole>(options =>
{
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"
+ "أابتثجحخدذرزسشصضطظعغفقكلمنهويءآأإىة٤٥٦٧٨٩٠"; // Arabic chars
options.User.RequireUniqueEmail = false; // Login/identify by phone; email is optional
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireUppercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 6;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Modular service registrations
builder.Services.AddHostedService<SubscriptionCheckerService>();
builder.Services.AddApplicationServices();
builder.Services.ApiVersioningSettings();
builder.Services.AddJwtAuthentication(builder.Configuration);
builder.Services.AddSwaggerWithJwt();
// SignalR & Chat
builder.Services.AddSignalR();
// Use custom user id provider so SignalR maps our JWT `uid` claim to user identifiers
builder.Services.AddSingleton<IUserIdProvider, EgyptOnline.Presentation.Hubs.UidUserIdProvider>();
builder.Services.AddSingleton<MongoDB.Driver.IMongoClient>(sp =>
new MongoDB.Driver.MongoClient(builder.Configuration["MongoDB:ConnectionString"])); // Placeholder
builder.Services.AddScoped<EgyptOnline.Services.ChatService>();
builder.Services.AddScoped<EgyptOnline.Services.NotificationMongoService>();
builder.Services.AddScoped<EgyptOnline.Services.OccupationService>();
builder.Services.AddSingleton<EgyptOnline.Services.PresenceService>();
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAll", policy =>
{
policy
.SetIsOriginAllowed(_ => true) // "allow all" that works with credentials
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials(); // required for SignalR WebSocket upgrade
});
});
if (builder.Environment.IsDevelopment())
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("serviceAccountKey.json")
});
}
else
{
FirebaseApp.Create(new AppOptions()
{
Credential = GoogleCredential.FromFile("/app/config/serviceAccountKey.json")
});
}
var app = builder.Build();
// ---------- Run Migrations ----------
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
try
{
Log.Information("Running database migrations...");
db.Database.Migrate();
Log.Information("Database migrations completed successfully");
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
await IdentityExtensions.SeedRoles(roleManager);
await IdentityExtensions.SeedAdmin(userManager, roleManager, builder.Configuration);
}
catch (Exception ex)
{
Log.Error(ex, "Database migration failed");
throw;
}
}
// ---------- Middleware ----------
app.UseStaticFiles(); // Serves from wwwroot by default
// Also explicitly serve images folder
var imagesPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images");
Console.WriteLine($"Images path: {imagesPath}");
Console.WriteLine($"Images path exists: {Directory.Exists(imagesPath)}");
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(imagesPath),
RequestPath = "/images"
});
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage(); // full details only in dev
}
else
{
app.UseExceptionHandler(errApp =>
{
errApp.Run(async context =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
// safe generic message
var json = System.Text.Json.JsonSerializer.Serialize(new
{
message = "An unexpected error occurred. Please contact support."
});
await context.Response.WriteAsync(json);
});
});
}
app.UseHttpsRedirection();
// ---------- Global Exception Handler ----------
app.UseExceptionHandler(errApp =>
{
errApp.Run(async context =>
{
context.Response.StatusCode = 500;
context.Response.ContentType = "application/json";
var exceptionHandlerPathFeature = context.Features.Get<IExceptionHandlerPathFeature>();
if (exceptionHandlerPathFeature != null)
{
// log full details internally
Log.Error(exceptionHandlerPathFeature.Error,
"Unhandled exception for request {Method} {Path}",
context.Request.Method, context.Request.Path);
}
// return safe generic message to client
var json = System.Text.Json.JsonSerializer.Serialize(new
{
message = "An unexpected error occurred. Please contact support."
});
await context.Response.WriteAsync(json);
});
});
app.UseRouting();
app.UseCors("AllowAll");
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
// app.UseMiddleware<SubscriptionCheckMiddleware>();
// ---------- Serilog Request Logging ----------
app.UseSerilogRequestLogging();
// ---------- Map Endpoints ----------
app.MapHub<EgyptOnline.Presentation.Hubs.ChatHub>("/chatHub");
app.MapHub<EgyptOnline.Presentation.Hubs.NotificationHub>("/notificationHub");
app.MapControllers().RequireRateLimiting("tokenBucket");
app.MapGet("/health", () => Results.Ok("Healthy"));
Log.Information("Application started successfully on {Environment}", app.Environment.EnvironmentName);
app.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application failed to start");
throw;
}
finally
{
Log.CloseAndFlush();
}
public partial class Program { }