summary refs log tree commit diff
path: root/extra/admin-api/Spacebar.AdminAPI/Services/AuthenticationService.cs
diff options
context:
space:
mode:
authorEmma [it/its]@Rory& <root@rory.gay>2025-04-08 18:55:55 +0200
committerEmma [it/its]@Rory& <root@rory.gay>2025-10-05 21:34:40 +0200
commitabb1b570a4343d5e4fde34f55c1a2bf403f62981 (patch)
tree1986363f5bf369a03ee1f18ed3170da73d859c38 /extra/admin-api/Spacebar.AdminAPI/Services/AuthenticationService.cs
parentRewrite access tokens, initial admin api (diff)
downloadserver-ts-abb1b570a4343d5e4fde34f55c1a2bf403f62981.tar.xz
Local changes
Diffstat (limited to 'extra/admin-api/Spacebar.AdminAPI/Services/AuthenticationService.cs')
-rw-r--r--extra/admin-api/Spacebar.AdminAPI/Services/AuthenticationService.cs42
1 files changed, 42 insertions, 0 deletions
diff --git a/extra/admin-api/Spacebar.AdminAPI/Services/AuthenticationService.cs b/extra/admin-api/Spacebar.AdminAPI/Services/AuthenticationService.cs
new file mode 100644

index 000000000..2ec7fab15 --- /dev/null +++ b/extra/admin-api/Spacebar.AdminAPI/Services/AuthenticationService.cs
@@ -0,0 +1,42 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Security.Cryptography; +using ArcaneLibs.Extensions; +using Microsoft.IdentityModel.Tokens; +using Spacebar.Db.Contexts; +using Spacebar.Db.Models; + +namespace Spacebar.AdminAPI.Services; + +public class AuthenticationService(SpacebarDbContext db) { + private static Dictionary<string, User> _userCache = new(); + private static Dictionary<string, DateTime> _userCacheExpiry = new(); + + public async Task<User> GetCurrentUser(HttpRequest request) { + if (!request.Headers.ContainsKey("Authorization")) { + throw new UnauthorizedAccessException(); + } + + var token = request.Headers["Authorization"].ToString().Split(' ').Last(); + + var handler = new JwtSecurityTokenHandler(); + var secretFile = File.ReadAllText("../../../jwt.key.pub"); + var key = ECDsa.Create(ECCurve.NamedCurves.nistP256); + key.ImportFromPem(secretFile); + + var res = await handler.ValidateTokenAsync(token, new TokenValidationParameters { + IssuerSigningKey = new ECDsaSecurityKey(key), + ValidAlgorithms = new[] { "ES512" }, + LogValidationExceptions = true, + // These are required to be false for the token to be valid as they aren't provided by the token + ValidateIssuer = false, + ValidateLifetime = false, + ValidateAudience = false, + }); + + if (!res.IsValid) { + throw new UnauthorizedAccessException(); + } + + return await db.Users.FindAsync(res.ClaimsIdentity.Claims.First(x => x.Type == "id").Value) ?? throw new InvalidOperationException(); + } +} \ No newline at end of file