-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
563 lines (486 loc) · 19.3 KB
/
Copy pathProgram.cs
File metadata and controls
563 lines (486 loc) · 19.3 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
using System.Globalization;
using System.Reflection;
using Castle.Core.Configuration;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Options;
using Polly;
using SpeakingClub.Data;
using SpeakingClub.Data.Abstract;
using SpeakingClub.Data.Concrete;
using SpeakingClub.Data.Configuration;
using SpeakingClub.Identity;
using SpeakingClub.Models;
using SpeakingClub.Services;
var builder = WebApplication.CreateBuilder(args);
#region Configuration
// Load configuration
var config = builder.Configuration;
builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddUserSecrets<Program>(optional: true)
.AddEnvironmentVariables();
Console.WriteLine("ENV: " + builder.Environment.EnvironmentName);
// Configure EmailSender settings
var emailSettings = config.GetSection("EmailSender");
var port = emailSettings.GetValue<int>("Port");
var host = emailSettings.GetValue<string>("SMTPMail") ?? "localhost";
var enablessl = true;
var username = emailSettings.GetValue<string>("Username") ?? "dummy@example.com";
var password = emailSettings.GetValue<string>("Password") ?? "dummy-password";
var fromEmail = emailSettings.GetValue<string>("FromEmail") ?? username;
var fromName = emailSettings.GetValue<string>("FromName") ?? "Speaking Club";
var replyToEmail = emailSettings.GetValue<string>("ReplyToEmail");
var provider = new FileExtensionContentTypeProvider();
// If .glb is not mapped, add it:
provider.Mappings[".glb"] = "model/gltf-binary";
// Only validate email settings if not in Development mode and settings are actually configured
if (!builder.Environment.IsDevelopment() && !string.IsNullOrEmpty(emailSettings.GetValue<string>("SMTPMail")))
{
if (string.IsNullOrEmpty(host))
throw new ArgumentNullException(nameof(host), "SMTP host cannot be null or empty.");
if (port <= 0)
throw new ArgumentOutOfRangeException(nameof(port), "SMTP port must be a positive number.");
if (string.IsNullOrEmpty(username))
throw new ArgumentNullException(nameof(username), "SMTP username cannot be null or empty.");
if (string.IsNullOrEmpty(password))
throw new ArgumentNullException(nameof(password), "SMTP password cannot be null or empty.");
}
#endregion
#region Data Protection - CRITICAL for Plesk
// IMPORTANT: Configure DataProtection to persist keys across app restarts
// Without this, authentication cookies become invalid when Plesk recycles the app pool
var keysFolder = Path.Combine(builder.Environment.ContentRootPath, "DataProtection-Keys");
// Ensure the keys directory exists and is writable
Directory.CreateDirectory(keysFolder);
builder.Services.AddDataProtection()
.SetApplicationName("SpeakingClub")
.PersistKeysToFileSystem(new DirectoryInfo(keysFolder))
.SetDefaultKeyLifetime(TimeSpan.FromDays(90)); // Keys last 90 days
Console.WriteLine($"Data Protection Keys Path: {keysFolder}");
#endregion
#region DbContext Registration
// Register SpeakingClubContext (your domain entities)
builder.Services.AddDbContext<SpeakingClubContext>(options =>
options.UseSqlServer(config.GetConnectionString("DefaultConnection"))
// options.UseSqlite(config.GetConnectionString("DefaultConnection")) // Use SQLite when needed.
);
// Register ApplicationDbContext (for Identity)
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(config.GetConnectionString("DefaultConnection"))
);
#endregion
#region Identity Registration
builder.Services.AddIdentity<User, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.SignIn.RequireConfirmedEmail = true;
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedPhoneNumber = false;
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = false;
options.Lockout.MaxFailedAccessAttempts = 4;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(4);
options.Lockout.AllowedForNewUsers = true;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
options.ClaimsIdentity.RoleClaimType = System.Security.Claims.ClaimTypes.Role;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
#endregion
#region Identity Cookie Configuration
builder.Services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Account/Login";
options.LogoutPath = "/Account/Logout";
options.AccessDeniedPath = "/Account/AccessDenied";
options.SlidingExpiration = true;
options.ExpireTimeSpan = TimeSpan.FromDays(7);
// Enhanced cookie configuration for Plesk stability
options.Cookie = new CookieBuilder
{
Name = "SpeakingClubAuth",
HttpOnly = true,
SameSite = SameSiteMode.Lax,
SecurePolicy = builder.Environment.IsDevelopment()
? CookieSecurePolicy.SameAsRequest
: CookieSecurePolicy.Always, // Always use Secure in production
IsEssential = true,
Path = "/",
MaxAge = TimeSpan.FromDays(7) // Explicit MaxAge for better browser compatibility
};
// Enhanced cookie regeneration to prevent 403 errors and auth issues
options.Events.OnValidatePrincipal = async context =>
{
// Check if the cookie is about to expire (within 30% of its lifetime)
var timeElapsed = DateTimeOffset.UtcNow - context.Properties.IssuedUtc;
var timeRemaining = context.Properties.ExpiresUtc - DateTimeOffset.UtcNow;
if (timeElapsed.HasValue && timeRemaining.HasValue)
{
var totalTime = timeElapsed.Value + timeRemaining.Value;
if (timeRemaining.Value < TimeSpan.FromTicks(totalTime.Ticks / 3))
{
// Refresh the cookie
context.ShouldRenew = true;
}
}
// Additional validation: Ensure user still exists in database
if (context.Principal != null)
{
var userManager = context.HttpContext.RequestServices.GetRequiredService<UserManager<User>>();
var user = await userManager.GetUserAsync(context.Principal);
if (user == null)
{
// User no longer exists, reject the principal
context.RejectPrincipal();
}
}
};
});
#endregion
#region Cookie Policy Configuration
// Add Cookie Policy for better cookie handling
builder.Services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false; // Set to true if you want GDPR consent
options.MinimumSameSitePolicy = SameSiteMode.Lax;
options.Secure = builder.Environment.IsDevelopment()
? CookieSecurePolicy.SameAsRequest
: CookieSecurePolicy.Always;
// Ensure all cookies have proper settings in production
options.OnAppendCookie = cookieContext =>
{
if (!builder.Environment.IsDevelopment())
{
cookieContext.CookieOptions.Secure = true;
}
};
});
#endregion
#region Security
builder.Services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
options.Cookie.Name = "SpeakingClubCSRF";
options.Cookie.SecurePolicy = builder.Environment.IsDevelopment()
? CookieSecurePolicy.SameAsRequest
: CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Lax;
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
options.Cookie.Path = "/";
});
#endregion
#region Additional Services
// Register UnitOfWork extension (repositories accessible via IUnitOfWork)
builder.Services.AddUnitOfWork();
// Configure Email Sender
builder.Services.AddScoped<IEmailSender, SmtpEmailSender>(sp =>
new SmtpEmailSender(host!, port, enablessl, username!, password!, fromEmail!, fromName!, replyToEmail!));
// Register resource services and file provider for localization/resources.
var resourcesPath = Path.Combine(Directory.GetCurrentDirectory(), "Resources");
builder.Services.AddSingleton<AliveResourceService>(p => new AliveResourceService(resourcesPath));
builder.Services.AddSingleton<IManageResourceService>(sp => new ManageResourceService(resourcesPath));
builder.Services.AddSingleton<LanguageService>();
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddHttpClient<IDictionaryService, DictionaryService>();
builder.Services.AddHttpClient<IDeeplService, DeeplService>()
.AddTransientHttpErrorPolicy(policyBuilder =>
policyBuilder.WaitAndRetryAsync(2, retryAttempt => TimeSpan.FromSeconds(10)));
builder.Services.AddSingleton<IFileProvider>(new PhysicalFileProvider(resourcesPath));
builder.Services.AddSignalR();
builder.Services.AddMemoryCache();
// Register background service for temp file cleanup
builder.Services.AddHostedService<TempFileCleanupService>();
#endregion
#region Localization and MVC Configuration
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
builder.Services.AddMvc()
.AddViewLocalization()
.AddDataAnnotationsLocalization(options =>
{
var assemblyInfo = typeof(SharedResource).GetTypeInfo().Assembly;
var assemblyName = new AssemblyName(assemblyInfo.FullName ?? throw new InvalidOperationException("Assembly full name cannot be null."));
options.DataAnnotationLocalizerProvider = (type, factory) =>
{
var location = assemblyName.Name ?? throw new ArgumentNullException(nameof(assemblyName.Name), "Assembly name cannot be null or empty.");
return factory.Create(nameof(SharedResource), location);
};
});
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("de-DE"),
new CultureInfo("tr-TR")
};
options.DefaultRequestCulture = new RequestCulture("tr-TR", "tr-TR");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders.Insert(0, new QueryStringRequestCultureProvider());
});
builder.Services.AddControllersWithViews()
.AddNewtonsoftJson()
.AddViewLocalization()
.AddDataAnnotationsLocalization()
.AddRazorRuntimeCompilation();
#endregion
var app = builder.Build();
#region Database Migration and Seeding
using (var scope = app.Services.CreateScope())
{
var speakingClubContext = scope.ServiceProvider.GetRequiredService<SpeakingClubContext>();
var applicationDbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
try
{
if (app.Environment.IsDevelopment())
{
// Automatically apply migrations in development mode
Console.WriteLine("Attempting database migration...");
speakingClubContext.Database.Migrate();
applicationDbContext.Database.Migrate();
Console.WriteLine("Database migration completed successfully.");
}
else
{
// Only run migration once in production
var hasAppliedMigrations = speakingClubContext.Database.GetAppliedMigrations().Any();
if (!hasAppliedMigrations)
{
speakingClubContext.Database.Migrate();
applicationDbContext.Database.Migrate();
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Warning: Database migration failed: {ex.Message}");
Console.WriteLine("Continuing startup without database...");
}
// Identity seeding and role/user checking (safe to run in production)
try
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
var usersConfig = config.GetSection("Data:Users").GetChildren().ToList();
if (!usersConfig.Any())
{
Console.WriteLine("No user configuration found. Skipping seeding.");
}
else
{
Console.WriteLine("Running identity seeding...");
await SeedIdentity.Seed(userManager, roleManager, config);
}
}
catch (Exception ex)
{
Console.WriteLine($"[SEED ERROR] User seeding failed: {ex}");
}
}
#endregion
#region HTTP Pipeline Configuration
// Configure ForwardedHeaders for Cloudflare proxy and Plesk
var forwardedHeadersOptions = new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost,
RequireHeaderSymmetry = false,
ForwardLimit = 2
};
// Add Cloudflare IPs - trust their headers
forwardedHeadersOptions.KnownIPNetworks.Clear();
forwardedHeadersOptions.KnownProxies.Clear();
// Trust all proxies for Cloudflare (adjust if needed)
forwardedHeadersOptions.AllowedHosts.Clear();
app.UseForwardedHeaders(forwardedHeadersOptions);
// Middleware: ACME challenge ve HTTPS yönlendirme
app.Use(async (context, next) =>
{
var path = context.Request.Path.Value;
// 1. ACME challenge → yönlendirme yok
if (path != null && path.StartsWith("/.well-known/acme-challenge"))
{
await next();
return;
}
// 2. Diğer tüm istekler → HTTPS'ye yönlendir
if (!context.Request.IsHttps)
{
var httpsUrl = $"https://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";
context.Response.Redirect(httpsUrl, permanent: true);
return;
}
await next();
});
// Content Security Policy middleware
app.Use(async (context, next) =>
{
// Force all resources to load over HTTPS
context.Response.Headers.Append("Content-Security-Policy", "upgrade-insecure-requests");
context.Response.Headers.Append("X-Content-Type-Options", "nosniff");
context.Response.Headers.Append("X-Frame-Options", "SAMEORIGIN");
context.Response.Headers.Append("X-XSS-Protection", "1; mode=block");
context.Response.Headers.Append("Referrer-Policy", "strict-origin-when-cross-origin");
await next();
});
if (!app.Environment.IsDevelopment())
{
// Hata sayfası ve HSTS
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
else
{
// Geliştirme modunda da HSTS kullan (daha kısa süre ile)
app.UseHsts();
}
// 4. Normal statik dosyalar
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = provider,
ServeUnknownFileTypes = true
});
// IMPORTANT: Cookie policy must come before authentication
app.UseCookiePolicy();
// Localization
app.UseRequestLocalization(app.Services.GetRequiredService<IOptions<RequestLocalizationOptions>>().Value);
// Routing ve auth
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseAntiforgery();
// MVC route'ları
// Localized Quiz Routes (Turkish)
app.MapControllerRoute(
name: "quizzes-tr",
pattern: "sinavlar",
defaults: new { controller = "Home", action = "Quizzes" });
app.MapControllerRoute(
name: "quizzes-tr-level",
pattern: "sinavlar/{level}",
defaults: new { controller = "Home", action = "Quizzes" });
// Localized Quiz Routes (German)
app.MapControllerRoute(
name: "quizzes-de",
pattern: "pruefungen",
defaults: new { controller = "Home", action = "Quizzes" });
app.MapControllerRoute(
name: "quizzes-de-level",
pattern: "pruefungen/{level}",
defaults: new { controller = "Home", action = "Quizzes" });
// Localized Blog Routes (Turkish)
app.MapControllerRoute(
name: "blog-tr",
pattern: "yazilar",
defaults: new { controller = "Home", action = "Blog" });
app.MapControllerRoute(
name: "blog-detail-tr",
pattern: "yazilar/{url}",
defaults: new { controller = "Home", action = "BlogDetail" });
// Localized Blog Routes (German)
app.MapControllerRoute(
name: "blog-de",
pattern: "beitraege",
defaults: new { controller = "Home", action = "Blog" });
app.MapControllerRoute(
name: "blog-detail-de",
pattern: "beitraege/{url}",
defaults: new { controller = "Home", action = "BlogDetail" });
// Localized About Routes
app.MapControllerRoute(
name: "about-tr",
pattern: "hakkimizda",
defaults: new { controller = "Home", action = "About" });
app.MapControllerRoute(
name: "about-de",
pattern: "ueber-uns",
defaults: new { controller = "Home", action = "About" });
// Localized Words/Dictionary Routes
app.MapControllerRoute(
name: "words-tr",
pattern: "sozluk",
defaults: new { controller = "Home", action = "Words" });
app.MapControllerRoute(
name: "words-de",
pattern: "woerterbuch",
defaults: new { controller = "Home", action = "Words" });
// Localized Privacy Routes
app.MapControllerRoute(
name: "privacy-tr",
pattern: "gizlilik",
defaults: new { controller = "Home", action = "Privacy" });
app.MapControllerRoute(
name: "privacy-de",
pattern: "datenschutz",
defaults: new { controller = "Home", action = "Privacy" });
// Localized Clinical German – Doctors Routes
app.MapControllerRoute(
name: "doctors-tr",
pattern: "hekim-almancasi",
defaults: new { controller = "Home", action = "DoctorsGerman" });
app.MapControllerRoute(
name: "doctors-de",
pattern: "aerztedeutsch",
defaults: new { controller = "Home", action = "DoctorsGerman" });
// Localized Clinical German – Nurses Routes
app.MapControllerRoute(
name: "nurses-tr",
pattern: "hemsirelik-almancasi",
defaults: new { controller = "Home", action = "NursesGerman" });
app.MapControllerRoute(
name: "nurses-de",
pattern: "pflegedeutsch",
defaults: new { controller = "Home", action = "NursesGerman" });
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
// app.MapControllerRoute(
// name: "blogdetail",
// pattern: "blog/{url}",
// defaults: new { controller = "Home", action = "BlogDetail" });
app.MapControllerRoute(
name: "about",
pattern: "about",
defaults: new { controller = "Home", action = "About" });
app.MapControllerRoute(
name: "privacy",
pattern: "privacy",
defaults: new { controller = "Home", action = "Privacy" });
app.MapControllerRoute(
name: "words",
pattern: "words",
defaults: new { controller = "Home", action = "Words" });
// Quiz canonical routes
app.MapControllerRoute(
name: "quizzes",
pattern: "quizzes",
defaults: new { controller = "Home", action = "Quizzes" });
app.MapControllerRoute(
name: "quizzes-level",
pattern: "quizzes/{level}",
defaults: new { controller = "Home", action = "Quizzes" });
// SEO Routes
app.MapControllerRoute(
name: "sitemap",
pattern: "sitemap.xml",
defaults: new { controller = "Sitemap", action = "Index" });
#endregion
#region SignalR Configuration
app.MapHub<SpeakingClub.Hubs.QuizMonitorHub>("/quizMonitorHub");
#endregion
Console.WriteLine("");
Console.WriteLine("🚀 Application starting up...");
Console.WriteLine("🌐 Application will be available at:");
Console.WriteLine(" 🔒 HTTPS: https://localhost:5001");
Console.WriteLine(" 🔒 HTTPS: https://localhost:5000");
Console.WriteLine("");
app.Run();