-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
233 lines (192 loc) · 8.66 KB
/
Program.cs
File metadata and controls
233 lines (192 loc) · 8.66 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
using InventoryManager.Data;
using InventoryManager.Models;
using InventoryManager.Models.Domain;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// ==========================================
// 1. DATABASE CONFIGURATION (Enhanced Parser)
// ==========================================
// We check for "DefaultConnection" (Local) or "DATABASE_URL" (Render)
// 1. Prioritize Render/Production environment variable
var connectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
?? builder.Configuration.GetConnectionString("DefaultConnection");
if (string.IsNullOrEmpty(connectionString))
{
throw new InvalidOperationException("Connection string not found.");
}
// Convert postgres:// URI to the Key=Value format Npgsql requires
if (connectionString.StartsWith("postgres://") || connectionString.StartsWith("postgresql://"))
{
var uri = new Uri(connectionString);
var userInfo = uri.UserInfo.Split(':');
// Fix for the 'Port -1' error: If port is missing in URI, use default 5432
var port = uri.Port <= 0 ? 5432 : uri.Port;
connectionString = $"Host={uri.Host};" +
$"Port={port};" +
$"Database={uri.AbsolutePath.TrimStart('/')};" +
$"Username={userInfo[0]};" +
$"Password={userInfo[1]};" +
$"SslMode=Require;" +
$"Trust Server Certificate=true;";
}
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(connectionString));
// ==========================================
// 2. IDENTITY SETUP
// ==========================================
builder.Services.AddDefaultIdentity<ApplicationUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
options.Password.RequiredLength = 6;
options.Password.RequireDigit = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
// ==========================================
// 2b. EXTERNAL AUTHENTICATION PROVIDERS
// ==========================================
// Providers are only registered when credentials are present so the app
// starts cleanly with empty appsettings values (e.g. a fresh clone).
// Set real values with:
// dotnet user-secrets set "Authentication:Google:ClientId" "<value>"
// dotnet user-secrets set "Authentication:Google:ClientSecret" "<value>"
// dotnet user-secrets set "Authentication:Facebook:AppId" "<value>"
// dotnet user-secrets set "Authentication:Facebook:AppSecret" "<value>"
var authBuilder = builder.Services.AddAuthentication();
var googleClientId = builder.Configuration["Authentication:Google:ClientId"];
var googleClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
if (!string.IsNullOrEmpty(googleClientId) && !string.IsNullOrEmpty(googleClientSecret))
{
authBuilder.AddGoogle(options =>
{
options.ClientId = googleClientId;
options.ClientSecret = googleClientSecret;
});
}
var facebookAppId = builder.Configuration["Authentication:Facebook:AppId"];
var facebookAppSecret = builder.Configuration["Authentication:Facebook:AppSecret"];
if (!string.IsNullOrEmpty(facebookAppId) && !string.IsNullOrEmpty(facebookAppSecret))
{
authBuilder.AddFacebook(options =>
{
options.AppId = facebookAppId;
options.AppSecret = facebookAppSecret;
});
}
builder.Services.AddControllersWithViews()
.AddViewLocalization()
.AddDataAnnotationsLocalization();
builder.Services.AddAntiforgery(options =>
{
// The AJAX script (like.js) sends the token in this header
options.HeaderName = "RequestVerificationToken";
});
builder.Services.AddRazorPages();
// Configure Localization
var supportedCultures = new[] { "en", "es", "pl" };
builder.Services.Configure<Microsoft.AspNetCore.Builder.RequestLocalizationOptions>(options =>
{
options.SetDefaultCulture("en");
options.AddSupportedCultures(supportedCultures);
options.AddSupportedUICultures(supportedCultures);
});
// Register AccessService so it can be injected into controllers.
// Scoped lifetime means one instance per HTTP request — appropriate for EF Core usage.
builder.Services.AddScoped<InventoryManager.Services.Interfaces.IAccessService,
InventoryManager.Services.AccessService>();
// Register DiscussionService for discussion persistence
builder.Services.AddScoped<InventoryManager.Services.Interfaces.IDiscussionService,
InventoryManager.Services.DiscussionService>();
// Register SignalR — built into ASP.NET Core, no extra NuGet package required
builder.Services.AddSignalR();
// Register SearchService for full-text search via PostgreSQL FTS
builder.Services.AddScoped<InventoryManager.Services.Interfaces.ISearchService,
InventoryManager.Services.SearchService>();
// Register StatisticsService for inventory analytics
builder.Services.AddScoped<InventoryManager.Services.Interfaces.IStatisticsService,
InventoryManager.Services.StatisticsService>();
// Register remaining core domain services
builder.Services.AddScoped<InventoryManager.Services.Interfaces.IInventoryService,
InventoryManager.Services.InventoryService>();
builder.Services.AddScoped<InventoryManager.Services.Interfaces.IItemService,
InventoryManager.Services.ItemService>();
builder.Services.AddScoped<InventoryManager.Services.Interfaces.ICustomIdService,
InventoryManager.Services.CustomIdService>();
builder.Services.AddScoped<InventoryManager.Services.Interfaces.ITagService,
InventoryManager.Services.TagService>();
// Register DropboxService with HttpClient for support tickets
builder.Services.AddHttpClient<InventoryManager.Services.DropboxService>();
var app = builder.Build();
// ==========================================
// 3. MIDDLEWARE PIPELINE
// ==========================================
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
// Apply Localization before Routing with extracted options
var locOptions = app.Services.GetRequiredService<Microsoft.Extensions.Options.IOptions<Microsoft.AspNetCore.Builder.RequestLocalizationOptions>>().Value;
app.UseRequestLocalization(locOptions);
app.UseRouting();
app.UseAuthentication();
// Order is critical: Custom middleware must be after Auth and before AuthZ
app.UseMiddleware<InventoryManager.Middleware.BlockedUserMiddleware>();
app.UseMiddleware<InventoryManager.Middleware.RequestCultureMiddleware>();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
// Map the SignalR hub endpoint — clients connect to /discussionHub
app.MapHub<InventoryManager.Hubs.DiscussionHub>("/discussionHub");
// ==========================================
// 4. AUTO-MIGRATE & SEED DATA
// ==========================================
using (var scope = app.Services.CreateScope())
{
var services = scope.ServiceProvider;
try
{
var context = services.GetRequiredService<ApplicationDbContext>();
// This line creates the tables in your Render database automatically
await context.Database.MigrateAsync();
var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
// Seed Admin Role
if (!await roleManager.RoleExistsAsync("Admin"))
{
await roleManager.CreateAsync(new IdentityRole("Admin"));
}
// Seed Default Admin User
var adminEmail = "admin@admin.com";
var adminUser = await userManager.FindByEmailAsync(adminEmail);
if (adminUser == null)
{
var user = new ApplicationUser
{
UserName = adminEmail,
Email = adminEmail,
EmailConfirmed = true,
IsBlocked = false
};
var result = await userManager.CreateAsync(user, "admin123");
if (result.Succeeded)
{
await userManager.AddToRoleAsync(user, "Admin");
}
}
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred during migration or seeding.");
}
}
app.Run();