| | | 1 | | using System.Security.Claims; |
| | | 2 | | using Elsa.AI.Host.Options; |
| | | 3 | | using Elsa.Common.Multitenancy; |
| | | 4 | | using Microsoft.AspNetCore.Http; |
| | | 5 | | using Microsoft.Extensions.DependencyInjection; |
| | | 6 | | |
| | | 7 | | namespace Elsa.AI.Host.Endpoints.AI; |
| | | 8 | | |
| | | 9 | | internal static class AIHttpContextIdentity |
| | | 10 | | { |
| | | 11 | | private const string TenantIdClaimType = "http://schemas.microsoft.com/identity/claims/tenantid"; |
| | | 12 | | |
| | | 13 | | public static string GetActorId(HttpContext? context) => |
| | 10 | 14 | | context?.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? |
| | 10 | 15 | | context?.User.FindFirstValue("sub") ?? |
| | 10 | 16 | | context?.User.Identity?.Name ?? |
| | 10 | 17 | | "anonymous"; |
| | | 18 | | |
| | | 19 | | public static string? GetTenantId(HttpContext? context) |
| | | 20 | | { |
| | 10 | 21 | | var tenantAccessor = context?.RequestServices?.GetService<ITenantAccessor>(); |
| | 10 | 22 | | if (tenantAccessor != null) |
| | 1 | 23 | | return tenantAccessor.TenantId; |
| | | 24 | | |
| | 9 | 25 | | return context?.User.FindFirstValue(TenantIdClaimType) ?? |
| | 9 | 26 | | context?.User.FindFirstValue("tenant_id") ?? |
| | 9 | 27 | | context?.User.FindFirstValue("tenantId"); |
| | | 28 | | } |
| | | 29 | | |
| | | 30 | | public static ICollection<string> GetPermissions(HttpContext? context) => |
| | 10 | 31 | | context?.User |
| | 10 | 32 | | .FindAll(PermissionNames.ClaimType) |
| | 1 | 33 | | .Select(x => x.Value) |
| | 1 | 34 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 10 | 35 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| | 10 | 36 | | .ToList() ?? []; |
| | | 37 | | |
| | | 38 | | public static string? GetAuthorizedAgent(string? requestedAgent, AIHostOptions options, ICollection<string> userPerm |
| | | 39 | | { |
| | 10 | 40 | | if (string.IsNullOrWhiteSpace(requestedAgent)) |
| | 7 | 41 | | return null; |
| | | 42 | | |
| | 6 | 43 | | var agent = options.Agents.FirstOrDefault(x => string.Equals(x.Name, requestedAgent, StringComparison.OrdinalIgn |
| | 3 | 44 | | if (agent == null || !HasRequiredPermissions(agent.Permissions, userPermissions)) |
| | 1 | 45 | | return null; |
| | | 46 | | |
| | 2 | 47 | | return agent.Name; |
| | | 48 | | } |
| | | 49 | | |
| | | 50 | | private static bool HasRequiredPermissions(ICollection<string> requiredPermissions, ICollection<string> userPermissi |
| | | 51 | | { |
| | 2 | 52 | | if (requiredPermissions.Count == 0) |
| | 2 | 53 | | return true; |
| | | 54 | | |
| | 0 | 55 | | var grantedPermissions = userPermissions |
| | 0 | 56 | | .Where(x => !string.IsNullOrWhiteSpace(x)) |
| | 0 | 57 | | .ToHashSet(StringComparer.OrdinalIgnoreCase); |
| | | 58 | | |
| | 0 | 59 | | return grantedPermissions.Contains(PermissionNames.All) || requiredPermissions.All(grantedPermissions.Contains); |
| | | 60 | | } |
| | | 61 | | } |