From a930e972917575c46ff9f59ab69d62be657ecac8 Mon Sep 17 00:00:00 2001 From: Tim Date: Mon, 21 Apr 2025 15:36:15 +0200 Subject: Move api handler out of Program.cs --- VPNAuth.Server/Api/Oidc.cs | 63 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 VPNAuth.Server/Api/Oidc.cs (limited to 'VPNAuth.Server/Api/Oidc.cs') diff --git a/VPNAuth.Server/Api/Oidc.cs b/VPNAuth.Server/Api/Oidc.cs new file mode 100644 index 0000000..8b984c7 --- /dev/null +++ b/VPNAuth.Server/Api/Oidc.cs @@ -0,0 +1,63 @@ +using VPNAuth.Server.Responses; + +namespace VPNAuth.Server.Api; + +public static class Oidc +{ + public static async Task UserInfoHandler(HttpContext context) + { + if (context.Request.Method != "GET" && context.Request.Method != "POST") + { + context.Response.StatusCode = StatusCodes.Status405MethodNotAllowed; + return; + } + + var tokenHeader = context.Request.Headers["Authorization"].First()?.Split(" "); + + if (tokenHeader?.Length == 1 || tokenHeader?[0] != "Bearer") + { + context.Response.StatusCode = StatusCodes.Status400BadRequest; + return; + } + + if (tokenHeader.Length < 2) + { + context.Response.StatusCode = StatusCodes.Status401Unauthorized; + return; + } + + using var db = new Database.Database(); + var tokenDbEntry = db.AccessTokens + .Where(tokenEntry => tokenEntry.Token == tokenHeader[1]) + .ToList() + .FirstOrDefault(); + + if (tokenDbEntry == null) + { + context.Response.StatusCode = StatusCodes.Status403Forbidden; + return; + } + + var userInformation = db.UserInformation + .Where(entry => entry.Sub == tokenDbEntry.Username) + .ToList() + .FirstOrDefault(); + + if (userInformation == null) + { + context.Response.StatusCode = StatusCodes.Status204NoContent; + return; + } + + context.Response.WriteAsJsonAsync(new UserInfo + { + Email = userInformation.Email, + GivenName = userInformation.GivenName, + FamilyName = userInformation.FamilyName, + Name = userInformation.Name, + Picture = userInformation.Picture, + PreferredUsername = userInformation.PreferredUsername, + Sub = userInformation.Sub + }); + } +} -- cgit v1.2.3