79 lines
3.0 KiB
C#
79 lines
3.0 KiB
C#
using System;
|
|
using Microsoft.Extensions.Hosting;
|
|
namespace perubahan;
|
|
|
|
public class Middlewares
|
|
{
|
|
public class AuthCheck(RequestDelegate next)
|
|
{
|
|
public async Task Invoke(HttpContext runner)
|
|
{
|
|
if(runner.Request.Cookies.ContainsKey("session"))
|
|
{
|
|
string Token = runner.Request.Cookies["session"] ?? ".";
|
|
string LoggedInBase64 = Token.Split(".")[0];
|
|
string Signature = Token.Split(".")[1];
|
|
if (Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(LoggedInBase64+SecretKey))).Equals(Signature,StringComparison.InvariantCultureIgnoreCase))
|
|
{
|
|
string Username = (string?)JsonNode.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(LoggedInBase64)))?["username"] ?? "";
|
|
SafeUser LoggedIn = SafeUser.FromUser(UserAccounts[Username]);
|
|
if (LoggedIn.Active)
|
|
{
|
|
runner.Items.Add("AuthorizedUser",LoggedIn);
|
|
}
|
|
else
|
|
{
|
|
runner.Response.Cookies.Append("session", "", Delete);
|
|
}
|
|
}
|
|
else
|
|
{
|
|
runner.Response.Cookies.Append("session", "", Delete);
|
|
}
|
|
}
|
|
await next(runner);
|
|
}
|
|
}
|
|
public class DomainNormalize(RequestDelegate next)
|
|
{
|
|
|
|
public async Task Invoke(HttpContext runner)
|
|
{
|
|
HttpOnly.Domain = runner.Request.Host.ToString();
|
|
Delete.Domain = runner.Request.Host.ToString();
|
|
await next(runner);
|
|
}
|
|
}
|
|
public class ErrorHandling(RequestDelegate next)
|
|
{
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await next(context);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await HandleExceptionAsync(context, ex);
|
|
throw;
|
|
}
|
|
}
|
|
|
|
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
|
|
{
|
|
WriteLog(ex, $"at {Path.Combine(context.Request.PathBase, context.Request.Path)}");
|
|
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
|
return context.Response.WriteAsJsonAsync(new SimpleApiResponse(context.Response.StatusCode, "Internal Server Error."), SGContext.Default.SimpleApiResponse);
|
|
}
|
|
}
|
|
public class CancellationTokenSourceLinker(RequestDelegate next, IHostApplicationLifetime Lifetime)
|
|
{
|
|
public async Task Invoke(HttpContext context)
|
|
{
|
|
CancellationTokenSource LinkedToken = CancellationTokenSource.CreateLinkedTokenSource(Lifetime.ApplicationStopping,context.RequestAborted,CTS.Token);
|
|
context.RequestAborted = LinkedToken.Token;
|
|
await next(context);
|
|
}
|
|
}
|
|
}
|