pages/Program.cs

61 lines
1.8 KiB
C#
Raw Normal View History

2024-10-06 19:50:15 +00:00
using System.IO.Compression;
if (!Directory.Exists("wwwroot"))
Directory.CreateDirectory("wwwroot");
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
WebApplication app = builder.Build();
if (Environment.GetEnvironmentVariable("API_TOKEN") is null)
throw new InvalidOperationException("API_TOKEN is not set");
app.UseStatusCodePages();
app.UseStaticFiles(new StaticFileOptions {
ServeUnknownFileTypes = true,
DefaultContentType = "text/plain"
});
app.MapPost("/pages/{projectName}", async (string projectName, HttpRequest request) => {
2024-10-07 06:59:46 +00:00
if (!request.HasFormContentType || request.Form.Files["zipfile"] is null)
2024-10-06 19:50:15 +00:00
return Results.BadRequest();
2024-10-07 06:59:46 +00:00
IFormFile zipFile = request.Form.Files["zipfile"]!;
2024-10-06 19:50:15 +00:00
if (zipFile.Length == 0)
return Results.BadRequest();
var extractPath = Path.Combine(app.Environment.WebRootPath, projectName);
if (Directory.Exists(extractPath))
Directory.Delete(extractPath, true);
Directory.CreateDirectory(extractPath);
try {
await using Stream stream = zipFile.OpenReadStream();
using var zipArchive = new ZipArchive(stream);
zipArchive.ExtractToDirectory(extractPath, true);
} catch {
return Results.BadRequest();
}
return Results.Ok();
}).DisableAntiforgery().AddEndpointFilter(async (context, next) => {
var token = GetBearerToken(context.HttpContext);
if (token is not null && token == Environment.GetEnvironmentVariable("API_TOKEN"))
return await next(context);
return Results.Unauthorized();
});
app.Run();
return;
string? GetBearerToken(HttpContext httpContext) {
var authHeader = httpContext.Request.Headers.Authorization.ToString();
return authHeader.StartsWith("Bearer ",
StringComparison.OrdinalIgnoreCase)
? authHeader["Bearer ".Length..].Trim()
: null;
2024-10-07 06:59:46 +00:00
}