| 1 | using AgentForge.Data.Entities; |
| 2 | using AgentForge.Services; |
| 3 | |
| 4 | namespace AgentForge.Plugin.Sdk; |
| 5 | |
| 6 | public static class ForgePluginHttpAuth |
| 7 | { |
| 8 | public const string ApiTokenItemKey = "ForgeApiToken"; |
| 9 | public const string ViewSessionCookieName = "forge_view_token"; |
| 10 | |
| 11 | public static string? GetBearerToken(HttpContext context) |
| 12 | { |
| 13 | var authorization = context.Request.Headers.Authorization.ToString(); |
| 14 | if (string.IsNullOrWhiteSpace(authorization)) |
| 15 | return null; |
| 16 | |
| 17 | const string prefix = "Bearer "; |
| 18 | return authorization.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) |
| 19 | ? authorization[prefix.Length..].Trim() |
| 20 | : null; |
| 21 | } |
| 22 | |
| 23 | public static ForgeApiTokenEntity? GetApiToken(HttpContext context) => |
| 24 | context.Items.TryGetValue(ApiTokenItemKey, out var value) |
| 25 | ? value as ForgeApiTokenEntity |
| 26 | : null; |
| 27 | |
| 28 | public static ForgeApiTokenEntity? ResolveApiToken(HttpContext context, ForgeAuthService auth) |
| 29 | { |
| 30 | var fromBearer = auth.ValidateApiToken(GetBearerToken(context)); |
| 31 | if (fromBearer is not null) |
| 32 | return fromBearer; |
| 33 | |
| 34 | if (context.Request.Cookies.TryGetValue(ViewSessionCookieName, out var cookieToken)) |
| 35 | return auth.ValidateApiToken(cookieToken); |
| 36 | |
| 37 | return null; |
| 38 | } |
| 39 | } |
| 40 | |