aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2022-05-05 20:17:45 -0500
committerJP Dillingham <jp@dillingham.me>2022-05-05 20:17:45 -0500
commite3267df36b4a62d49658385c9d08b2d62df56ae0 (patch)
tree7dab5d605b994d874dfba721eca589be9720e33e /src
parent25b770b9fee1e2c429cf378d624f750963b146d8 (diff)
downloadslskd-e3267df36b4a62d49658385c9d08b2d62df56ae0.tar.gz
add HTMLInjectionMiddleware
Diffstat (limited to 'src')
-rw-r--r--src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs60
1 files changed, 60 insertions, 0 deletions
diff --git a/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
new file mode 100644
index 00000000..ab41806c
--- /dev/null
+++ b/src/slskd/Common/Middleware/HTMLInjectionMiddleware.cs
@@ -0,0 +1,60 @@
+namespace slskd
+{
+ using System;
+ using System.Linq;
+ using System.Text;
+ using System.Threading.Tasks;
+ using Microsoft.AspNetCore.Builder;
+ using Microsoft.AspNetCore.Http;
+
+ public static class HTMLInjectionMiddlewareExtensions
+ {
+ public static IApplicationBuilder UseHTMLInjection(this IApplicationBuilder builder, string html)
+ {
+ return builder.UseMiddleware<HTMLInjectionMiddleware>(html);
+ }
+ }
+
+ public class HTMLInjectionMiddleware
+ {
+ public HTMLInjectionMiddleware(RequestDelegate next, string html)
+ {
+ Next = next;
+ HTML = html;
+ }
+
+ private string HTML { get; }
+ private RequestDelegate Next { get; }
+
+ public async Task InvokeAsync(HttpContext context)
+ {
+ context.Request.Headers.TryGetValue("accept", out var accept);
+ var requestedTypes = accept.ToString().Split(',');
+
+ var injectableTypes = new[] { "text/html", "application/xhtml + xml", "application/xml" };
+
+ var isApiRoute = context.Request.Path.ToString().StartsWith("/api");
+ var isGET = context.Request.Method == "GET";
+
+ var isInjectableType = requestedTypes
+ .Intersect(injectableTypes, StringComparer.InvariantCultureIgnoreCase)
+ .Any();
+
+ if (!isApiRoute && isGET && isInjectableType)
+ {
+ context.Request.EnableBuffering();
+
+ await Next.Invoke(context);
+
+ if (context.Response.StatusCode == 200)
+ {
+ await context.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(HTML));
+ }
+ }
+ else
+ {
+ await Next.Invoke(context);
+ }
+ }
+ }
+}