-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
216 lines (186 loc) · 9.85 KB
/
Program.cs
File metadata and controls
216 lines (186 loc) · 9.85 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
using Backend.Data;
using Backend.Infrastructure;
using Backend.Services;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
if (builder.Environment.IsEnvironment("Testing"))
{
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
}
const string FrontendCorsPolicy = "AllowFrontend";
const string DefaultFrontendUrl = "http://localhost:4200";
var frontendUrl = builder.Configuration["FrontendUrl"] ?? DefaultFrontendUrl;
var googleClientId = builder.Configuration["Authentication:Google:ClientId"];
var googleClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
// ── Database ──────────────────────────────────────────────────────────────────
// In the Testing environment (WebApplicationFactory) the InMemory provider is used
// so integration tests run without a real database connection. The factory passes
// a unique database name via configuration to keep test classes isolated.
// All other environments use SQL Server.
builder.Services.AddDbContext<AppDbContext>(options =>
{
if (builder.Environment.IsEnvironment("Testing"))
options.UseInMemoryDatabase(
builder.Configuration["TestDatabaseName"] ?? "TestDb");
else
options.UseSqlServer(
builder.Configuration.GetConnectionString("DefaultConnection"));
});
// ── Identity ──────────────────────────────────────────────────────────────────
// AddIdentityApiEndpoints maps /register, /login, /refresh, etc. under any prefix
// you choose (see app.MapGroup below). It is designed for SPA / API clients.
builder.Services.AddIdentityApiEndpoints<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders()
.AddClaimsPrincipalFactory<DonorDefaultClaimsPrincipalFactory>();
// Password policy — must match what was taught in IS 414 (NOT Microsoft doc defaults).
builder.Services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 14;
options.Password.RequiredUniqueChars = 1;
});
// Cookie configuration for browser clients.
// Dev: SameSite=None is required because the frontend (http://localhost:4200) and backend
// (https://localhost:5200) use different schemes. Chrome's schemeful same-site treats
// these as cross-site, blocking Lax cookies on fetch requests. None+Secure allows them.
// Production: Lax is correct — frontend and backend share the same scheme and domain.
builder.Services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = builder.Environment.IsDevelopment()
? SameSiteMode.None
: SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.ExpireTimeSpan = TimeSpan.FromDays(7);
options.SlidingExpiration = true;
});
// The two-factor partial sign-in cookie (Identity.TwoFactorUserId) is a separate scheme
// and must also be set to SameSite=None in dev, otherwise Chrome blocks it cross-origin
// and TwoFactorAuthenticatorSignInAsync can't find the pending sign-in state.
builder.Services.Configure<CookieAuthenticationOptions>(
IdentityConstants.TwoFactorUserIdScheme,
options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SameSite = builder.Environment.IsDevelopment()
? SameSiteMode.None
: SameSiteMode.Lax;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
});
// ── Google OAuth ──────────────────────────────────────────────────────────────
// Secrets stored in appsettings.Development.json (dev) and Azure App Settings (prod).
// The block is skipped entirely if the keys are absent so local dev without Google
// credentials still starts successfully.
if (!string.IsNullOrEmpty(googleClientId) && !string.IsNullOrEmpty(googleClientSecret))
{
builder.Services.AddAuthentication()
.AddGoogle(options =>
{
options.ClientId = googleClientId;
options.ClientSecret = googleClientSecret;
options.SignInScheme = IdentityConstants.ExternalScheme;
options.CallbackPath = "/signin-google";
});
}
// ── Authorization policies ────────────────────────────────────────────────────
builder.Services.AddAuthorization(options =>
{
options.AddPolicy(AuthPolicies.AdminOnly, policy =>
policy.RequireRole(AuthRoles.Admin));
options.AddPolicy(AuthPolicies.StaffOrAdmin, policy =>
policy.RequireRole(AuthRoles.Admin, AuthRoles.Staff));
});
// ── HSTS ──────────────────────────────────────────────────────────────────────
builder.Services.AddHsts(options =>
{
options.MaxAge = TimeSpan.FromDays(365);
options.IncludeSubDomains = true;
});
// ── CORS ──────────────────────────────────────────────────────────────────────
// AllowCredentials() is required for cookie-based auth to work across origins.
builder.Services.AddCors(options =>
{
options.AddPolicy(FrontendCorsPolicy, policy =>
policy.WithOrigins(
frontendUrl,
"http://localhost:4200",
"https://lunas-project.site",
"https://www.lunas-project.site",
"https://intex-ii.vercel.app"
)
.AllowCredentials()
.AllowAnyHeader()
.AllowAnyMethod());
});
builder.Services.AddControllers();
// ── Gemini Audio Autofill ─────────────────────────────────────────────────────
builder.Services.AddHttpClient<IAudioAutofillService, AudioAutofillService>();
// ── Email Automation ─────────────────────────────────────────────────────────
builder.Services.AddHttpClient<IEmailService, ResendEmailService>();
builder.Services.AddScoped<IDonorScoringService, DonorScoringService>();
builder.Services.AddHostedService<WeeklyEmailHostedService>();
// ── AI Chat ──────────────────────────────────────────────────────────────────
builder.Services.AddHttpClient<GeminiChatService>();
builder.Services.AddScoped<ChatQueryService>();
builder.Services.AddScoped<ChatValidationService>();
// ── Expansion Recommendation (Gemini API) ─────────────────────────────────────
// Reuses the existing Gemini:ApiKey already configured for AudioAutofillService.
// No additional API key or registration needed — the service calls Gemini directly
// via IHttpClientFactory with no named client.
builder.Services.AddScoped<IExpansionRecommendationService, ExpansionRecommendationService>();
builder.Services.AddOpenApi();
var app = builder.Build();
var databaseStartupPolicy = DatabaseStartupPolicy.Resolve(app.Environment, app.Configuration);
// ── Seed roles and default admin user ─────────────────────────────────────────
using (var scope = app.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
if (app.Environment.IsEnvironment("Testing"))
{
db.Database.EnsureCreated();
}
else if (databaseStartupPolicy.ApplyMigrations)
{
db.Database.Migrate();
}
// Skip CSV seeding in the Testing environment: tests don't need production
// data, and the InMemory provider rejects duplicate PKs that SQL Server
// would catch at the constraint level.
if (!app.Environment.IsEnvironment("Testing") && databaseStartupPolicy.RunSeedData)
{
var seedPath = Path.Combine(AppContext.BaseDirectory, "Data", "SeedData");
await DataSeeder.SeedAsync(db, seedPath);
}
await AuthIdentityGenerator.GenerateDefaultIdentityAsync(
scope.ServiceProvider, app.Configuration);
}
// ── Middleware pipeline ────────────────────────────────────────────────────────
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
// Security headers (CSP, X-Content-Type-Options, X-Frame-Options, Referrer-Policy)
// must come before UseCors so headers are set on every response.
app.UseSecurityHeaders();
app.UseCors(FrontendCorsPolicy);
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Maps Identity API minimal endpoints: /register, /login, /refresh, /confirmEmail, etc.
app.MapGroup("/api/auth").MapIdentityApi<ApplicationUser>();
app.Run();
// Exposes the generated Program class to the test assembly via WebApplicationFactory<Program>.
public partial class Program { }