ProjectLighthouse/ProjectLighthouse.Servers.GameServer/Startup/TokenAuthHandler.cs
Josh 64b95e807d
Refactor Database class (#616)
Refactor Database into DatabaseContext
Moved into separate folder so it actually has a namespace instead sitting in the root
2023-02-15 23:54:30 -06:00

50 lines
No EOL
1.8 KiB
C#

using System.Security.Claims;
using System.Text.Encodings.Web;
using LBPUnion.ProjectLighthouse.Database;
using LBPUnion.ProjectLighthouse.Types.Entities.Token;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
namespace LBPUnion.ProjectLighthouse.Servers.GameServer.Startup;
public class TokenAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly DatabaseContext database;
private const string cookie = "MM_AUTH";
public TokenAuthHandler
(
IOptionsMonitor<AuthenticationSchemeOptions> options,
UrlEncoder encoder,
ISystemClock clock,
DatabaseContext database
// I said I don't want any damn vegetables (logs)
) : base(options, new NullLoggerFactory(), encoder, clock)
{
this.database = database;
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
this.Context.Response.StatusCode = 403;
return Task.CompletedTask;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!this.Context.Request.Cookies.ContainsKey(cookie)) return AuthenticateResult.Fail("No auth cookie");
GameToken? gameToken = await this.database.GameTokenFromRequest(this.Request);
if (gameToken == null) return AuthenticateResult.Fail("No game token");
this.Context.Items["Token"] = gameToken;
Claim[] claims = {
new("userId", gameToken.UserId.ToString()),
};
ClaimsIdentity identity = new(claims, this.Scheme.Name);
ClaimsPrincipal principal = new(identity);
AuthenticationTicket ticket = new(principal, this.Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}