1
0
mirror of https://github.com/chylex/Discord-History-Tracker.git synced 2025-01-06 22:42:49 +01:00
Discord-History-Tracker/app/Server/Endpoints/BaseEndpoint.cs
2023-07-21 18:47:21 +02:00

76 lines
2.0 KiB
C#

using System;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using DHT.Server.Database;
using DHT.Server.Service;
using DHT.Utils.Http;
using DHT.Utils.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Primitives;
namespace DHT.Server.Endpoints;
abstract class BaseEndpoint {
private static readonly Log Log = Log.ForType<BaseEndpoint>();
protected IDatabaseFile Db { get; }
private readonly ServerAccessToken accessToken;
protected BaseEndpoint(IDatabaseFile db, ServerAccessToken accessToken) {
this.Db = db;
this.accessToken = accessToken;
}
private async Task Handle(HttpContext ctx, StringValues token) {
var request = ctx.Request;
var response = ctx.Response;
Log.Info("Request: " + request.GetDisplayUrl() + " (" + request.ContentLength + " B)");
if (!CheckToken(token)) {
Log.Error("Invalid token.");
response.StatusCode = (int) HttpStatusCode.Forbidden;
return;
}
try {
response.StatusCode = (int) HttpStatusCode.OK;
var output = await Respond(ctx);
await output.WriteTo(response);
} catch (HttpException e) {
Log.Error(e);
response.StatusCode = (int) e.StatusCode;
await response.WriteAsync(e.Message);
} catch (Exception e) {
Log.Error(e);
response.StatusCode = (int) HttpStatusCode.InternalServerError;
}
}
private bool CheckToken(StringValues token) {
if (token.Count != 1) {
return false;
}
string? tokenString = token[0];
return tokenString != null && accessToken.IsValid(tokenString);
}
public async Task HandleGet(HttpContext ctx) {
await Handle(ctx, ctx.Request.Query["token"]);
}
public async Task HandlePost(HttpContext ctx) {
await Handle(ctx, ctx.Request.Headers["X-DHT-Token"]);
}
protected abstract Task<IHttpOutput> Respond(HttpContext ctx);
protected static async Task<JsonElement> ReadJson(HttpContext ctx) {
return await ctx.Request.ReadFromJsonAsync<JsonElement?>() ?? throw new HttpException(HttpStatusCode.UnsupportedMediaType, "This endpoint only accepts JSON.");
}
}