using System; using System.Linq; using System.Threading; using xCommons.Extensions; using System.Threading.Tasks; using System.Collections.Generic; using xIdentityService.Interfaces; namespace xIdentityService.Providers { public class XRoleHierarchyResolver : IXRoleHierarchyResolver { private readonly IXRoleProvider provider; public XRoleHierarchyResolver( IXRoleProvider provider ) { this.provider = provider; } public async Task> GetRolesByMinWeightAsync( int minWeight, CancellationToken cancellationToken = default ) { // var roles = await provider.FindManyAsync( predicate: r => r.IsEnabled && r.Weight >= minWeight, orderBuilder: q => q.OrderBy(r => r.Weight), cancellationToken: cancellationToken ); // var result = roles .Select(r => r.Name.ToNormalString()) .Distinct() .ToList(); return result; } public async Task> ResolveEffectiveRolesAsync( IEnumerable explicitRoles, int? minRoleWeight, CancellationToken cancellationToken = default ) { // var result = new HashSet(StringComparer.InvariantCultureIgnoreCase); // // Explicit Roles ... if (explicitRoles.HasChild()) { // foreach (var role in explicitRoles) { result.Add(role.ToNormalString()); } } // // Roles by Weight ... if (minRoleWeight.HasValue) { // var byWeight = await GetRolesByMinWeightAsync( minRoleWeight.Value, cancellationToken ); foreach (var role in byWeight) { result.Add(role); } } // // Parent Chain: any Role whose ParentRoleName is in result inherits it ... var all = await provider.GetAllAsync(cancellationToken: cancellationToken); bool changed; do { // changed = false; foreach (var role in all.Where(r => r.IsEnabled && !r.ParentRoleName.IsNullOrEmpty())) { // if (result.Contains(role.ParentRoleName) && result.Add(role.Name.ToNormalString())) { changed = true; } } } while (changed); // return [.. result]; } } }