-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
283 lines (253 loc) · 9.08 KB
/
Copy pathProgram.cs
File metadata and controls
283 lines (253 loc) · 9.08 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
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using TraWell.Data;
using TraWell.Models;
using TraWell.Services;
using TraWell.Middleware;
using System.Diagnostics;
using System.Runtime.InteropServices;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Response Compression
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<Microsoft.AspNetCore.ResponseCompression.BrotliCompressionProvider>();
options.Providers.Add<Microsoft.AspNetCore.ResponseCompression.GzipCompressionProvider>();
options.MimeTypes = new[]
{
"text/plain",
"text/html",
"text/css",
"text/javascript",
"application/javascript",
"application/json",
"application/xml",
"text/xml",
"image/svg+xml"
};
});
// Output Caching
builder.Services.AddOutputCache(options =>
{
options.AddBasePolicy(policy => policy.Expire(TimeSpan.FromMinutes(10)));
options.AddPolicy("StaticFiles", policy => policy.Expire(TimeSpan.FromHours(24)));
options.AddPolicy("ApiData", policy => policy.Expire(TimeSpan.FromMinutes(5)));
});
// Database Configuration
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ??
"Data Source=TraWell.db";
// Configure database provider based on environment
if (builder.Environment.IsEnvironment("Testing"))
{
// Use in-memory database for testing (will be overridden in test factory)
builder.Services.AddDbContext<TraWellDbContext>(options =>
options.UseInMemoryDatabase("TestDatabase"));
}
else if (builder.Environment.IsProduction())
{
// Use PostgreSQL for production
builder.Services.AddDbContext<TraWellDbContext>(options =>
options.UseNpgsql(connectionString));
}
else
{
// Use SQLite for development
builder.Services.AddDbContext<TraWellDbContext>(options =>
options.UseSqlite(connectionString));
}
// Identity Configuration
builder.Services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = true;
options.Password.RequireLowercase = true;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = true;
options.Password.RequiredLength = 6;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<TraWellDbContext>()
.AddDefaultTokenProviders();
// JWT Authentication
var jwtSettings = builder.Configuration.GetSection("JwtSettings");
var key = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"] ?? "TraWell2024SecretKeyForJWTTokenGeneration");
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
ClockSkew = TimeSpan.Zero
};
});
// Authorization
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Admin", policy => policy.RequireRole("Admin"));
options.AddPolicy("User", policy => policy.RequireRole("User"));
});
// Add HttpClient service
builder.Services.AddHttpClient();
// Register Custom Services
builder.Services.AddScoped<PlaceService>();
builder.Services.AddScoped<VideoService>();
builder.Services.AddScoped<RecommendationService>();
builder.Services.AddScoped<IEmailService, EmailService>();
builder.Services.AddScoped<IOtpService, OtpService>();
builder.Services.AddScoped<IPaymentService, RazorpayService>();
builder.Services.AddScoped<DataSeeder>();
builder.Services.AddMemoryCache(); // Required for OTP service
builder.Services.AddHostedService<BackgroundVideoScraper>();
// Configure CORS
builder.Services.AddCors(options =>
{
options.AddPolicy("TraWellCorsPolicy", policy =>
{
if (builder.Environment.IsDevelopment())
{
// Development: Allow localhost origins
policy.WithOrigins("http://localhost:3000", "http://localhost:5088", "https://localhost:5089")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}
else
{
// Production: Add your specific domains
policy.WithOrigins("https://yourdomain.com", "https://www.yourdomain.com")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
}
});
});
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
// Only use HTTPS redirection in production
if (app.Environment.IsProduction())
{
app.UseHttpsRedirection();
}
app.UseResponseCompression(); // Add compression early in pipeline
app.UseMiddleware<SecurityHeadersMiddleware>();
app.UseStaticFiles();
app.UseOutputCache(); // Add output caching
// Temporarily disable rate limiting for development
// app.UseMiddleware<RateLimitingMiddleware>();
app.UseCors("TraWellCorsPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapFallbackToFile("index.html");
// Ensure default roles exist
using (var scope = app.Services.CreateScope())
{
var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "User", "Provider" };
foreach (var roleName in roleNames)
{
var roleExists = await roleManager.RoleExistsAsync(roleName);
if (!roleExists)
{
await roleManager.CreateAsync(new IdentityRole(roleName));
}
}
// Create default admin user
var adminEmail = "admin@trawell.com";
var adminUser = await userManager.FindByEmailAsync(adminEmail);
if (adminUser == null)
{
adminUser = new ApplicationUser
{
UserName = adminEmail,
Email = adminEmail,
FirstName = "Admin",
LastName = "TraWell",
DateOfBirth = new DateTime(1990, 1, 1),
EmailConfirmed = true,
CreatedAt = DateTime.UtcNow,
LastActive = DateTime.UtcNow,
Bio = "System Administrator",
ProfileImageUrl = ""
};
var result = await userManager.CreateAsync(adminUser, "Admin@123");
if (result.Succeeded)
{
await userManager.AddToRoleAsync(adminUser, "Admin");
Console.WriteLine("✅ Default admin user created:");
Console.WriteLine($" Email: {adminEmail}");
Console.WriteLine($" Password: Admin@123");
}
}
}
// Create database if it doesn't exist and seed sample data
using (var scope = app.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<TraWellDbContext>();
var dataSeeder = scope.ServiceProvider.GetRequiredService<DataSeeder>();
try
{
context.Database.EnsureCreated();
await dataSeeder.SeedSampleDataAsync();
Console.WriteLine("✅ Database and sample data initialized successfully");
}
catch (Exception ex)
{
Console.WriteLine($"⚠️ Database initialization failed: {ex.Message}");
// Continue with application startup
}
}
// Auto-open browser in development
if (app.Environment.IsDevelopment())
{
var lifetime = app.Services.GetRequiredService<IHostApplicationLifetime>();
lifetime.ApplicationStarted.Register(() =>
{
try
{
var address = app.Urls.FirstOrDefault() ?? "http://localhost:5088";
Console.WriteLine($"\n🌐 Opening browser at: {address}");
// Open browser cross-platform
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo("cmd", $"/c start {address}") { CreateNoWindow = true });
}
else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.OSX))
{
Process.Start("open", address);
}
else if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Linux))
{
Process.Start("xdg-open", address);
}
}
catch (Exception ex)
{
Console.WriteLine($"Could not auto-open browser: {ex.Message}");
}
});
}
app.Run();
// Make Program class accessible for testing
public partial class Program { }