-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
153 lines (128 loc) · 4.36 KB
/
Program.cs
File metadata and controls
153 lines (128 loc) · 4.36 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
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Npgsql;
using play929_server.Data;
using play929_server.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using play929_server.Hubs;
using play929_server.Middlewares;
using System.Text;
using AspNetCoreRateLimit;
var builder = WebApplication.CreateBuilder(args);
// Add essential services to the DI container
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register HttpClient
builder.Services.AddHttpClient();
builder.Services.AddMemoryCache();
// Add rate limiting services
builder.Services.AddInMemoryRateLimiting();
builder.Services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
// Configure PostgreSQL DbContext with dynamic connection string handling
string connectionString = GetConnectionString(builder.Environment);
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
ConfigureJwtBearerOptions(options);
});
// Register DbContext with the resolved connection string
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseNpgsql(connectionString));
// Register application services and controllers
builder.Services.AddControllers();
builder.Services.AddScoped<PostgreSQLHelper>();
builder.Services.AddScoped<IUserService, UserService>();
// Add SignalR for real-time communication
builder.Services.AddSignalR();
// Configure CORS policy for authorized domains
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowPlay929AndAuth", builder =>
{
builder.WithOrigins("https://play929.com" , "https://dashboard.play929.com", "https://portal.play929.com", "http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
var app = builder.Build();
// Enable rate limiting globally
app.UseIpRateLimiting();
// Configure static file serving and apply migrations
app.UseStaticFiles();
ApplyDatabaseMigrations(app);
// Enable Swagger UI in development environment
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors("AllowPlay929AndAuth");
app.UseRouting();
app.UseMiddleware<TokenMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
// Map SignalR hubs
app.MapHub<ChatHub>("/chatHub");
app.MapHub<GameHub>("/gameHub");
app.MapHub<GameHub>("/adminHub");
// Map controllers
app.MapControllers();
app.Run();
/// <summary>
/// Retrieves the appropriate database connection string based on the environment.
/// </summary>
string GetConnectionString(IHostEnvironment environment)
{
// Use the default connection string for local development
return builder.Configuration.GetConnectionString("DefaultConnection");
}
/// <summary>
/// Constructs a PostgreSQL connection string from a given URI.
/// </summary>
string BuildNpgsqlConnectionString(Uri databaseUri)
{
var userInfo = databaseUri.UserInfo.Split(':');
return new NpgsqlConnectionStringBuilder
{
Host = databaseUri.Host,
Port = databaseUri.Port,
Username = userInfo[0],
Password = userInfo[1],
Database = databaseUri.AbsolutePath.TrimStart('/'),
SslMode = SslMode.Require,
TrustServerCertificate = true
}.ToString();
}
/// <summary>
/// Configures JWT Bearer Authentication options.
/// </summary>
void ConfigureJwtBearerOptions(JwtBearerOptions options)
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "https://play929.com",
ValidAudience = "https://auth.play929.com",
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySuperSecretJWTKeyThatIs32CharsLongOrMore!"))
};
}
/// <summary>
/// Applies pending database migrations.
/// </summary>
void ApplyDatabaseMigrations(WebApplication app)
{
using var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.Database.Migrate();
}