/// <summary> /// Returns true if the user is in the specified group /// </summary> /// <param name="adUser">The user</param> /// <param name="groupName">The ID of the group to check for membership</param> /// <returns></returns> public bool IsInGroup(UserPrincipal adUser, string groupName) { GroupPrincipal g = GroupPrincipal.FindByIdentity(Context, groupName); return adUser.IsMemberOf(g); }
private static string GetMbrPath(UserPrincipal usr) { Stack<string> output = new Stack<string>(); StringBuilder retVal = new StringBuilder(); GroupObj fg = null, tg = null; output.Push(usr.Name); foreach (GroupObj go in _groups) { if (usr.IsMemberOf(go.Group)) { output.Push(go.Group.Name); fg = go; while (fg.Parent != null) { output.Push(fg.Parent.Name); tg = (from g in _groups where g.Group == fg.Parent select g).FirstOrDefault(); fg = tg; } break; } } while (output.Count > 1) retVal.AppendFormat("{0} ->", output.Pop()); retVal.Append(output.Pop()); return retVal.ToString(); }
/// <summary> /// Returns a list of groups of which the user is a member. It does so in a fashion that /// may seem strange since one can call UserPrincipal.GetGroups, but seems to be much faster /// in my tests. /// </summary> /// <param name="user"></param> /// <returns></returns> private static List<GroupPrincipal> GetGroups(UserPrincipal user) { List<GroupPrincipal> result = new List<GroupPrincipal>(); // Get all groups using a PrincipalSearcher and GroupPrincipal filter = new GroupPrincipal(m_machinePrincipal); using (PrincipalSearcher searcher = new PrincipalSearcher(filter)) { PrincipalSearchResult<Principal> sResult = searcher.FindAll(); foreach (Principal p in sResult) { if (p is GroupPrincipal) { GroupPrincipal gp = (GroupPrincipal)p; if (user.IsMemberOf(gp)) result.Add(gp); else gp.Dispose(); } else { p.Dispose(); } } } return result; }