using HRD.LDAPService.JWT; using System; using System.Collections.Generic; using System.DirectoryServices.AccountManagement; using System.Linq; namespace HRD.LDAPService { public static class LdapExtensions { public static LdapUser CheckAndAddGroupMembers(this PrincipalContext context, UserPrincipal userPrincipal, LdapUser ldapUser) { if (context == null || userPrincipal == null || ldapUser == null) { throw new Exception($"UserPrincipal failed"); } if (ldapUser.RoleList?.Count == 0) { ldapUser.RoleList = new List(); return ldapUser; } try { List userGroupList = userPrincipal.GetGroups().ToList(); // all groups of which the user is a direct member List jwtRoleList = ldapUser.RoleList; //keep all possible Roles of the user List fullRoleList = new List(); fullRoleList = fullRoleList.Union(jwtRoleList).ToList(); //add Roles from backend fullRoleList = fullRoleList.Union(JwtTokenConfig.JwtRoleList).ToList(); //add Roles from JwtTokenConfig.JwtRoleList ldapUser.RoleList = new List(); if (fullRoleList.Count > 0) { foreach (JwtRole jwtRole in jwtRoleList) { if (userGroupList.Exists(userGroup => userGroup.Name == jwtRole.Group)) { ldapUser.AddRole(jwtRole.Role); } } } } catch (Exception ex) { throw ex; } return ldapUser; } } }