Exemplo n.º 1
0
        public static bool IsUserMemberOfGroups(PrincipalContext context, string samaccountname, List <string> groups)
        {
            using (UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, samaccountname))
            {
                if (user != null)
                {
                    GroupPrincipal prigroup = GetPrimaryGroup(context, user);
                    PrincipalSearchResult <Principal> usergroups = user.GetAuthorizationGroups();

                    if (groups == null)
                    {
                        return(true);
                    }

                    foreach (string groupname in groups)
                    {
                        using (GroupPrincipal group = GroupPrincipal.FindByIdentity(context, groupname))
                        {
                            if (group == null)
                            {
                                LoggerFacade.Warn("Group not found: " + groupname);
                            }
                            else
                            {
                                //work around issue where IsMemherOf always returns false on users primary group
                                if (group.Equals(prigroup))
                                {
                                    return(true);
                                }

                                //now do normal processing
                                bool ismember = user.IsMemberOf(group);
                                if (ismember == false)
                                {
                                    return(false);
                                }
                            }
                        }
                    }
                    return(true);
                }

                else
                {
                    throw new NoMatchingPrincipalException("User not found: " + samaccountname);
                }
            }
        }