Files
inventory/MaxInventory.Authentication/Core/AdminRoleClaimsTransformation.cs
T
2026-03-19 09:06:14 -04:00

98 lines
3.2 KiB
C#

using MaxInventory.Authentication.Abstractions;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
namespace MaxInventory.Authentication.Core
{
public sealed class AdminRoleClaimsTransformation : IClaimsTransformation
{
private static readonly string[] GroupClaimTypes =
{
"groups",
"group",
"role",
"roles",
ClaimTypes.GroupSid,
ClaimTypes.Role,
"http://schemas.microsoft.com/ws/2008/06/identity/claims/role",
"http://schemas.xmlsoap.org/claims/Group"
};
private readonly IAdminGroupSource _adminGroupSource;
public AdminRoleClaimsTransformation(IAdminGroupSource adminGroupSource)
{
_adminGroupSource = adminGroupSource;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity is not ClaimsIdentity identity || !identity.IsAuthenticated)
{
return principal;
}
if (HasRole(identity, AuthRoles.Admin) &&
HasRole(identity, AuthRoles.EditAdd) &&
HasRole(identity, AuthRoles.View))
{
return principal;
}
var principalGroups = identity.Claims
.Where(c => GroupClaimTypes.Contains(c.Type, StringComparer.OrdinalIgnoreCase))
.Select(c => c.Value);
var groupSet = new HashSet<string>(principalGroups, StringComparer.OrdinalIgnoreCase);
var isViewer = IsInConfiguredGroup(groupSet, await _adminGroupSource.GetViewGroupsAsync());
var isEditor = IsInConfiguredGroup(groupSet, await _adminGroupSource.GetEditGroupsAsync());
var isAdmin = IsInConfiguredGroup(groupSet, await _adminGroupSource.GetAdminGroupsAsync());
if (isAdmin)
{
AddRole(identity, AuthRoles.Admin);
AddRole(identity, AuthRoles.EditAdd);
AddRole(identity, AuthRoles.View);
return principal;
}
if (isEditor)
{
AddRole(identity, AuthRoles.EditAdd);
AddRole(identity, AuthRoles.View);
return principal;
}
if (isViewer)
{
AddRole(identity, AuthRoles.View);
}
return principal;
}
private static bool IsInConfiguredGroup(HashSet<string> principalGroups, IReadOnlyCollection<string> configuredGroups)
{
if (configuredGroups.Count == 0)
return false;
return configuredGroups.Any(principalGroups.Contains);
}
private static bool HasRole(ClaimsIdentity identity, string role)
{
return identity.Claims.Any(c => c.Type == ClaimTypes.Role &&
string.Equals(c.Value, role, StringComparison.OrdinalIgnoreCase));
}
private static void AddRole(ClaimsIdentity identity, string role)
{
if (!HasRole(identity, role))
identity.AddClaim(new Claim(ClaimTypes.Role, role));
}
}
}