This repository was archived by the owner on Sep 25, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
217 lines (184 loc) · 7.5 KB
/
Copy pathProgram.cs
File metadata and controls
217 lines (184 loc) · 7.5 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
using Azure.Core;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.Azure;
using Azure.Identity;
using Azure.Storage;
using Jamly.Auth.Handlers;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Jamly.Data;
using Jamly.Models;
using Jamly.Services;
using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authorization;
using Jamly.Auth.Requirements;
using Microsoft.AspNetCore.ResponseCompression;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IAuthorizationHandler, PolicyRequirementHandler>();
// Retrieve settings for Azure Storage
var blobServiceUrl = builder.Configuration["AzureStorage:BlobServiceUrl"];
var accountName = builder.Configuration["AzureStorage:AccountName"];
var accountKey = builder.Configuration["AzureStorage:AccountKey"];
if (string.IsNullOrEmpty(blobServiceUrl) || string.IsNullOrEmpty(accountName) || string.IsNullOrEmpty(accountKey))
{
throw new InvalidOperationException("Azure Storage configuration is incomplete.");
}
builder.Services.AddAuthorization(options => {
options.AddPolicy("IsGameJamAdmin", policy => {
policy.Requirements.Add(new GameJamAdminRequirementsModel());
});
});
// Create StorageSharedKeyCredential and BlobServiceClient
var credential = new StorageSharedKeyCredential(accountName, accountKey);
var blobServiceClient = new BlobServiceClient(new Uri(blobServiceUrl), credential);
builder.Services.AddSingleton(blobServiceClient); // Register BlobServiceClient as singleton
builder.Services.AddScoped<IBlobService, BlobService>();
builder.Services.AddTransient<IEmailSender, EmailSender>();
builder.Services.Configure<AuthMessageSenderOptions>(builder.Configuration);
// Add CORS policy
// Retrieve URLs from launchSettings.json
var allowedOriginsSection = builder.Configuration.GetSection("profiles:https:applicationUrl");
var allowedOrigins = allowedOriginsSection?.Value?.Split(';') ?? Array.Empty<string>();
// actually adding the CORS policy
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
policyBuilder => policyBuilder.WithOrigins(allowedOrigins)
.AllowAnyHeader()
.AllowAnyMethod());
});
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
builder.Services.AddHttpClient();
builder.Services.AddControllers();
// Read the file size limit from the configuration and set it
var fileSizeLimit = builder.Configuration.GetValue<long>("FileUpload:MaxFileSize");
builder.Services.Configure<FormOptions>(options =>
{
// Setting a file size limit
options.MultipartBodyLengthLimit = fileSizeLimit;
options.ValueLengthLimit = (int)fileSizeLimit;
options.MultipartHeadersLengthLimit = (int)fileSizeLimit;
});
// Configure form request size limit
// this is so you can upload large game files to the server
builder.Services.Configure<FormOptions>(options =>
{
options.ValueLengthLimit = int.MaxValue;
options.MultipartBodyLengthLimit = int.MaxValue;
options.MultipartHeadersLengthLimit = int.MaxValue;
});
// adding the BlobService to the service collection
builder.Services.AddScoped<BlobService>();
// Load configurations
builder.Services.Configure<AuthMessageSenderOptions>(
builder.Configuration.GetSection("AuthMessageSenderOptions"));
// Check critical configuration values
ValidateSecrets(builder.Configuration);
// define response compression
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.MimeTypes = new[]
{
"text/html", "text/css", "application/javascript",
"application/json", "application/octet-stream", "application/wasm", "text/plain"
};
options.Providers.Add<GzipCompressionProvider>();
});
// build the app
var app = builder.Build();
using (var service = app.Services.CreateScope()) {
var db = service.ServiceProvider.GetRequiredService<ApplicationDbContext>();
var um = service.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var rm = service.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
ApplicationDbInitializer.Initialize(db,um,rm);
}
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
// enable static files like ".pck" and "gzip" for WebGL builds
app.UseHttpsRedirection();
app.UseResponseCompression(); // Must come before UseStaticFiles
app.UseStaticFiles(new StaticFileOptions
{
ContentTypeProvider = new FileExtensionContentTypeProvider
{
Mappings =
{
[".pck"] = "application/octet-stream",
[".wasm"] = "application/wasm",
[".js"] = "application/javascript",
[".js.gz"] = "application/javascript",
[".data"] = "application/octet-stream",
[".data.gz"] = "application/octet-stream",
[".wasm.gz"] = "application/wasm"
}
},
OnPrepareResponse = ctx =>
{
var headers = ctx.Context.Response.Headers;
// Set headers for .gz files
if (ctx.File.Name.EndsWith(".gz"))
{
Console.WriteLine("Setting gzip headers..."); // Debug logging
headers["Content-Encoding"] = "gzip";
if (ctx.File.Name.EndsWith(".js.gz"))
{
Console.WriteLine("Setting Content-Type: application/javascript"); // Debug logging
headers["Content-Type"] = "application/javascript";
}
else if (ctx.File.Name.EndsWith(".data.gz"))
{
headers["Content-Type"] = "application/octet-stream";
}
else if (ctx.File.Name.EndsWith(".wasm.gz"))
{
headers["Content-Type"] = "application/wasm";
}
}
headers["Accept-Ranges"] = "bytes";
headers["Cache-Control"] = "public, max-age=3600";
headers["Vary"] = "Accept-Encoding";
}
});
// Enable CORS
app.UseCors("AllowSpecificOrigin");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapRazorPages();
app.Run();
void ValidateSecrets(IConfiguration configuration)
{
var sendGridKey = configuration["AuthMessageSenderOptions:SendGridKey"];
var senderEmail = configuration["AuthMessageSenderOptions:SenderEmail"];
if (string.IsNullOrEmpty(sendGridKey) || string.IsNullOrEmpty(senderEmail))
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("WARNING: SendGridKey or senderEmail is not set. Emails cannot be sent.");
Console.ResetColor();
}
}