-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
219 lines (185 loc) · 7.14 KB
/
Program.cs
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
using System.Text;
using AutoMapper;
using FoosballApi;
using FoosballApi.Hub;
using FoosballApi.Services;
using Hangfire;
using Hangfire.PostgreSql;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.SignalR;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
var builder = WebApplication.CreateBuilder(args);
// Load environment variables
DotNetEnv.Env.Load();
// Configure Kestrel for non-development environments
var portVar = Environment.GetEnvironmentVariable("PORT");
if (!builder.Environment.IsDevelopment())
{
if (portVar is { Length: > 0 } && int.TryParse(portVar, out int port))
{
builder.WebHost.ConfigureKestrel(options =>
{
options.ListenAnyIP(5297);
options.ListenAnyIP(7145);
options.ListenAnyIP(52729);
options.ListenAnyIP(port);
});
}
}
// Add services to the container
var jwtSecret = Environment.GetEnvironmentVariable("JwtSecret");
if (string.IsNullOrEmpty(jwtSecret))
{
throw new ArgumentNullException("JWTSecret", "JwtSecret is not configured.");
}
var key = Encoding.ASCII.GetBytes(jwtSecret);
builder.Services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false,
};
// Handle SignalR token retrieval from query string
x.Events = new JwtBearerEvents
{
OnMessageReceived = context =>
{
var accessToken = context.Request.Query["access_token"];
var path = context.HttpContext.Request.Path;
// Check if the request is for SignalR Hubs and has a token in the query string
if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/messageHub"))
{
context.Token = accessToken;
}
return Task.CompletedTask;
},
// Validate token upon receipt
OnTokenValidated = context =>
{
var userService = context.HttpContext.RequestServices.GetRequiredService<IUserService>();
var name = context.Principal.FindFirst("name")?.Value;
if (name == null || !int.TryParse(name, out int userId))
{
context.Fail("Unauthorized");
return Task.CompletedTask;
}
var user = userService.GetUserByIdSync(userId);
if (user == null)
{
context.Fail("Unauthorized");
}
return Task.CompletedTask;
}
};
});
builder.Services.AddControllers().AddNewtonsoftJson(s =>
{
s.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
});
string connectionString = builder.Environment.IsDevelopment()
? Environment.GetEnvironmentVariable("FoosballDbDev")
: Environment.GetEnvironmentVariable("FoosballDbProd");
if (string.IsNullOrEmpty(connectionString))
{
throw new ArgumentNullException("ConnectionString", "Connection string is not configured.");
}
builder.Services.AddHangfire(config =>
config.UsePostgreSqlStorage(connectionString));
builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddScoped<IAuthService, AuthService>();
builder.Services.AddScoped<IEmailService, EmailService>();
builder.Services.AddScoped<ICmsService, CmsService>();
builder.Services.AddScoped<IDoubleLeagueGoalService, DoubleLeagueGoalService>();
builder.Services.AddScoped<IDoubleLeaugeMatchService, DoubleLeaugeMatchService>();
builder.Services.AddScoped<IDoubleLeaguePlayerService, DoubleLeaguePlayerService>();
builder.Services.AddScoped<IDoubleLeagueTeamService, DoubleLeagueTeamService>();
builder.Services.AddScoped<IFreehandDoubleGoalService, FreehandDoubleGoalService>();
builder.Services.AddScoped<IFreehandDoubleMatchService, FreehandDoubleMatchService>();
builder.Services.AddScoped<IFreehandMatchService, FreehandMatchService>();
builder.Services.AddScoped<IFreehandGoalService, FreehandGoalService>();
builder.Services.AddScoped<ILeagueService, LeagueService>();
builder.Services.AddScoped<ISingleLeagueMatchService, SingleLeagueMatchService>();
builder.Services.AddScoped<IOrganisationService, OrganisationService>();
builder.Services.AddScoped<ISingleLeagueGoalService, SingleLeagueGoalService>();
builder.Services.AddScoped<ISingleLeaguePlayersService, SingleLeaguePlayersService>();
builder.Services.AddScoped<IPremiumService, PremiumService>();
builder.Services.AddScoped<IMicrosoftTeamsService, MicrosoftTeamsService>();
builder.Services.AddScoped<IMatchService, MatchService>();
// Register IHttpContextAccessor
builder.Services.AddHttpContextAccessor();
// Register MatchesRealtimeService as Singleton
builder.Services.AddSingleton<IMatchesRealtimeService>(provider =>
{
var hubContext = provider.GetRequiredService<IHubContext<MessageHub>>();
var httpContextAccessor = provider.GetRequiredService<IHttpContextAccessor>();
var mapper = provider.GetRequiredService<IMapper>();
return new MatchesRealtimeService(hubContext, connectionString, httpContextAccessor, mapper);
});
// Register the Background Service
builder.Services.AddHostedService<ScoreNotificationBackgroundService>();
// Configure Swagger/OpenAPI
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Foosball Api", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Name = "Authorization",
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer",
BearerFormat = "JWT",
In = ParameterLocation.Header,
Description = "JWT Authorization header using the Bearer scheme."
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddScoped<ISlackService, SlackService>();
builder.Services.AddScoped<IDiscordService, DiscordService>();
// Add SignalR support
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.UseHangfireServer();
app.UseHangfireDashboard();
app.MapControllers();
app.MapHub<MessageHub>("/messageHub").RequireAuthorization();
app.UseCors(builder => builder
.WithOrigins("http://localhost:5173", "http://localhost:8000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.Run();