Mirrors the user's LDAP groups in the Django database and updates the
        user's membership.
548330
def _mirror_groups(self):
        
        target_group_names = frozenset(self._get_groups().get_group_names())
        current_group_names = frozenset(
            self._user.groups.values_list("name", flat=True).iterator()
        )

        # These were normalized to sets above.
        MIRROR_GROUPS_EXCEPT = self.settings.MIRROR_GROUPS_EXCEPT
        MIRROR_GROUPS = self.settings.MIRROR_GROUPS

        # If the settings are white- or black-listing groups, we'll update
        # target_group_names such that we won't modify the membership of groups
        # beyond our purview.
        if isinstance(MIRROR_GROUPS_EXCEPT, (set, frozenset)):
            target_group_names = (target_group_names - MIRROR_GROUPS_EXCEPT) | (
                current_group_names & MIRROR_GROUPS_EXCEPT
            )
        elif isinstance(MIRROR_GROUPS, (set, frozenset)):
            target_group_names = (target_group_names & MIRROR_GROUPS) | (
                current_group_names - MIRROR_GROUPS
            )

        if target_group_names != current_group_names:
            existing_groups = list(
                Group.objects.filter(name__in=target_group_names).iterator()
            )
            existing_group_names = frozenset(group.name for group in existing_groups)

            new_groups = [
                Group.objects.get_or_create(name=name)[0]
                for name in target_group_names
                if name not in existing_group_names
            ]

            self._user.groups.set(existing_groups + new_groups)
377571
def sync_ldap_users(self, ldap_users):
        """"""
        model = get_user_model()

        #Load total User starts
        self.stats_user_total = len(ldap_users)

        list_profiles = []
        #Load extra profiles. This way we don't even need a callback. The same code is used to populate both auth_user and user_profile
        for list_profile in self.conf_LDAP_SYNC_USER_EXTRA_PROFILES:
            list_profiles.append((list_profile, apps.get_model(list_profile)))

        if not model._meta.get_field(self.conf_LDAP_SYNC_USERNAME_FIELD).unique:
            raise ImproperlyConfigured("Field '%s' must be unique" % self.conf_LDAP_SYNC_USERNAME_FIELD)

        actualProgress = 0

        for cname, attributes in ldap_users:
            defaults = {}
            actualProgress += 1
            if (self.conf_LDAP_SYNC_USER_SHOW_PROGRESS and ((100 * actualProgress // self.stats_user_total) > (100 * (actualProgress - 1) // self.stats_user_total))):
                logger.info("AD User Sync: Processed %d/%d users (%d" % (actualProgress, self.stats_user_total, (100 * actualProgress) // self.stats_user_total) + "%)")
            try:
                for name, attribute in attributes.items():
                    try:
                        if ((name.lower() == 'thumbnailphoto') or (name.lower() == 'jpegphoto') or (name.lower() == 'thumbnaillogo')):
                            defaults[self.conf_LDAP_SYNC_USER_ATTRIBUTES[name]] = attribute[0]
                        else:
                            defaults[self.conf_LDAP_SYNC_USER_ATTRIBUTES[name]] = attribute[0].decode('utf-8')
                    except KeyError:
                        pass
                    except UnicodeDecodeError:
                        raise ImproperlyConfigured('Error in attribute ' + name + ' ' + str(attribute))
            except AttributeError:
                # In some cases attributes is a list instead of a dict; skip these invalid users
                continue

            try:
                username = defaults[self.conf_LDAP_SYNC_USERNAME_FIELD].lower()
            except KeyError:
                logger.warning("User is missing a required attribute '%s'" % self.conf_LDAP_SYNC_USERNAME_FIELD)
                continue

            #Don't import users if they are in LDAP_SYNC_USER_EXEMPT_FROM_SYNC settings
            if (username in self.conf_LDAP_SYNC_USER_EXEMPT_FROM_SYNC):
                logger.debug("Skip importing user %s, it appears in LDAP_SYNC_USER_EXEMPT_FROM_SYNC list" % username)
                continue

            kwargs = {
                self.conf_LDAP_SYNC_USERNAME_FIELD + '__iexact': username,
                'defaults': defaults,
            }

            ### Users Disable
            #Check disable bit 
            user_account_control = int(attributes[self.ATTRIBUTE_DISABLED][0].decode('utf-8'))
            user_is_disabled = (user_account_control and ((user_account_control & self.FLAG_UF_ACCOUNT_DISABLE) == self.FLAG_UF_ACCOUNT_DISABLE))
            if user_is_disabled:
                try:
                    #If disabled, we need to check if the user already exists on Django
                    user = model.objects.get(**{self.conf_LDAP_SYNC_USERNAME_FIELD + '__iexact': username,})
                    if (not user):
                        #Ignore disabled users, we won't import it, only update it
                        continue
                except Exception as e:
                    #Ignore disabled users, we won't import it, only update it
                    continue
                else:
                    #If the user already exists on Django we'll run the callbacks
                    if (self.conf_LDAP_SYNC_REMOVED_USER_CALLBACKS):
                        self.stats_user_deleted += 1
                    for path in self.conf_LDAP_SYNC_REMOVED_USER_CALLBACKS:
                        logger.debug("Calling %s for user %s" % (path, username))
                        callback = import_string(path)
                        callback(user)
            ### User creation and sinchronization
            updated = False
            try:
                if user_is_disabled:
                    created = False
                    #reload it because it may be deleted
                    user = model.objects.get(**{self.conf_LDAP_SYNC_USERNAME_FIELD + '__iexact': username,})
                else:
                    user, created = model.objects.get_or_create(**kwargs)
            except (ObjectDoesNotExist) as e:
                if (user_is_disabled):
                    continue
                else:
                    raise e
            except (IntegrityError, DataError) as e:
                logger.error("Error creating user %s: %s" % (username, e))
                self.stats_user_errors += 1
            else:
                user_updated = False
                if created:
                    logger.debug("Created user %s" % username)
                    self.stats_user_added += 1
                    user.set_unusable_password()
                else:
                    for name, attr in defaults.items():
                        current_attr = getattr(user, name, None)
                        if current_attr != attr:
                            setattr(user, name, attr)
                            if (not user_updated):
                                user_updated = True
                    if user_updated:
                        logger.debug("Updated user %s" % username)
                        updated = True

                for path in self.conf_LDAP_SYNC_USER_CALLBACKS:
                    callback = import_string(path)
                    callback(user, attributes, created, user_updated)

                try:
                    if (created or user_updated):
                        user.save()
                except Exception as e:
                    logger.error("Error saving user %s: %s" % (username, e))
                    self.stats_user_errors += 1
                ### LDAP Sync Membership
                if (self.conf_LDAP_SYNC_GROUP_MEMBERSHIP):
                    membership_uri, ldap_membership = self.get_ldap_user_membership(attributes[self.conf_LDAP_SYNC_GROUP_MEMBERSHIP_DN_FIELD][0].decode('utf-8'))
                    if ldap_membership:
                        self.sync_ldap_user_membership(user, ldap_membership)
            #Profile creation and update.
            for name_profile, profile_model in list_profiles:
                try:
                    profile, created = profile_model.objects.get_or_create(user=user)  # ,  **kwargs )
                except (IntegrityError, DataError) as e:
                    logger.error("Error creating profile %s for user %s: %s" % (name_profile, username, e))
                    self.stats_user_errors += 1
                else:
                    profile_updated = False
                    if (created):
                        logger.debug("Created profile '%s' for user '%s'" % (name_profile, username))
                        #profile.save()
                    for unchanged_name, attr in attributes.items():
                        name = unchanged_name
                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "lower"):
                            name = unchanged_name.lower()
                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "upper"):
                            name = unchanged_name.upper()

                        try:
                            if ((name.lower() != 'thumbnailphoto') and (name.lower() != 'jpegphoto') and (name.lower() != 'thumbnaillogo') ):
                                current_attr = getattr(profile, name)
                                new_value = ''
                                if (isinstance(attr, list)):
                                    for val in attr:
                                        new_value += val.decode("utf8") + self.conf_LDAP_SYNC_MULTIVALUE_SEPARATOR
                                    if (new_value != ""):
                                        new_value = new_value[:-len(self.conf_LDAP_SYNC_MULTIVALUE_SEPARATOR)]
                                else:
                                    new_value = attr
                                if current_attr != new_value:
                                    setattr(profile, name, new_value)
                                    #logger.debug("Updated profile %s: Attribute %s from '%s' to '%s' - '%s'" % (username,name, current_attr, new_value, attr))
                                    profile_updated = True
                            else:
                                if (isinstance(attr, list)):
                                    newthumbPhoto = attr[0]
                                else:
                                    newthumbPhoto = attr
                                actualPhoto = None
                                try:
                                    if (name.lower() == 'thumbnailphoto'):
                                        if (not self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE):
                                            actualPhoto = profile.thumbnailPhoto.read()
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "lower"):
                                            actualPhoto = profile.thumbnailphoto.read()
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "upper"):
                                            actualPhoto = profile.THUMBNAILPHOTO.read()
                                    elif (name.lower() == 'thumbnaillogo'):
                                        if (not self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE):
                                            actualPhoto = profile.thumbnailLogo.read()
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "lower"):
                                            actualPhoto = profile.thumbnaillogo.read()
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "upper"):
                                            actualPhoto = profile.THUMBNAILLOGO.read()                                            
                                    else:
                                        if (not self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE):
                                            actualPhoto = profile.jpegPhoto.read()
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "lower"):
                                            actualPhoto = profile.jpegphoto.read()
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "upper"):
                                            actualPhoto = profile.JPEGPHOTO.read()
                                except Exception as e:
                                    pass
                                if (actualPhoto != newthumbPhoto):
                                    #Saving thumbnailphoto
                                    #logger.debug("Photo in "+username+" are different... ")
                                    photo_name = self.conf_LDAP_SYNC_USER_THUMBNAILPHOTO_NAME
                                    #we don't format because I don't know if username it's being used at all
                                    photo_name = photo_name.replace('{username}', username)
                                    photo_name = photo_name.replace('{uuid4}', str(uuid.uuid4()))
                                    photo_name = datetime.now().strftime(photo_name)
                                    if (name.lower() == 'thumbnailphoto'):
                                        if (not self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE):
                                            if (actualPhoto):
                                                profile.thumbnailPhoto.delete()
                                            profile.thumbnailPhoto.save(name=photo_name, content=ContentFile(newthumbPhoto))
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "lower"):
                                            if (actualPhoto):
                                                profile.thumbnailphoto.delete()
                                            profile.thumbnailphoto.save(name=photo_name, content=ContentFile(newthumbPhoto))
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "upper"):
                                            if (actualPhoto):
                                                profile.THUMBNAILPHOTO.delete()
                                            profile.THUMBNAILPHOTO.save(name=photo_name, content=ContentFile(newthumbPhoto))
                                    elif (name.lower() == 'thumbnaillogo'):
                                        if (not self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE):
                                            if (actualPhoto):
                                                profile.thumbnailLogo.delete()
                                            profile.thumbnailLogo.save(name=photo_name, content=ContentFile(newthumbPhoto))
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "lower"):
                                            if (actualPhoto):
                                                profile.thumbnaillogo.delete()
                                            profile.thumbnaillogo.save(name=photo_name, content=ContentFile(newthumbPhoto))
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "upper"):
                                            if (actualPhoto):
                                                profile.THUMBNAILLOGO.delete()
                                            profile.THUMBNAILLOGO.save(name=photo_name, content=ContentFile(newthumbPhoto))                                            
                                    else:
                                        if (not self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE):
                                            if (actualPhoto):
                                                profile.jpegPhoto.delete()
                                            profile.jpegPhoto.save(name=photo_name, content=ContentFile(newthumbPhoto))
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "lower"):
                                            if (actualPhoto):
                                                profile.jpegphoto.delete()
                                            profile.jpegphoto.save(name=photo_name, content=ContentFile(newthumbPhoto))
                                        if (self.conf_LDAP_SYNC_USER_CHANGE_FIELDCASE == "upper"):
                                            if (actualPhoto):
                                                profile.JPEGPHOTO.delete()
                                            profile.JPEGPHOTO.save(name=photo_name, content=ContentFile(newthumbPhoto))
                                    profile_updated = True
                                else:
                                    pass
                                    #logger.debug("Photo "+username+" are equal")
                        except AttributeError:
                            pass
                            #logger.debug("Ignore Attribute %s on profile '%s'" % (name, name_profile))
                    if profile_updated:
                        logger.debug("Updated profile %s on user %s" % (name_profile, username))
                        updated = True
                    if (created or profile_updated):
                        try:
                            profile.save()
                        except Exception as e:
                            logger.error("Error saving profile %s for user %s: %s" % (name_profile, username, e))
                            self.stats_user_errors += 1
                    #profile.save()
                    #If either user record or any profile record is changed, we'll mark it as updated.
            if (updated):
                self.stats_user_updated += 1

        logger.info("Users are synchronized")
1354597
private static void updateLibertyServer() throws Exception {
        ServerConfiguration server = emptyConfiguration.clone();

        LdapRegistry ldap = new LdapRegistry();
        ldap.setId("ldap1");
        ldap.setRealm("LDAPRealm");
        ldap.setHost("localhost");
        ldap.setPort(String.valueOf(ds.getListenPort()));
        ldap.setBaseDN(SUB_DN);
        ldap.setBindDN(InMemoryLDAPServer.getBindDN());
        ldap.setBindPassword(InMemoryLDAPServer.getBindPassword());
        ldap.setLdapType("Custom");
        LdapEntityType type1 = new LdapEntityType("Group", null, new String[] { "groupOfNames" }, new String[] { GROUP_BASE_DN });
        LdapEntityType type2 = new LdapEntityType("PersonAccount", null, new String[] { "inetOrgPerson" }, new String[] { USER_BASE_DN });
        ldap.getLdapEntityTypes().add(type1);
        ldap.getLdapEntityTypes().add(type2);

        LDAPFatUtils.createFederatedRepository(server, "LDAPRealmFed", new String[] { SUB_DN });

        server.getLdapRegistries().add(ldap);

        updateConfigDynamically(libertyServer, server);
    }
565016
private User updateUserStandard(LdapName originalId, User existingUser) {
        User savedUser = userRepo.save(existingUser);

        if(!originalId.equals(savedUser.getId())) {
            // The user has moved - we need to update group references.
            LdapName oldMemberDn = toAbsoluteDn(originalId);
            LdapName newMemberDn = toAbsoluteDn(savedUser.getId());

            Collection<Group> groups = groupRepo.findByMember(oldMemberDn);
            updateGroupReferences(groups, oldMemberDn, newMemberDn);
        }
        return savedUser;
    }
1372749
def sync_groups(self):
        """"""
        if self.settings.GROUP_FILTER:
            ldap_groups = self.ldap.search(self.settings.GROUP_FILTER, self.settings.GROUP_ATTRIBUTES.keys())
            self._sync_ldap_groups(ldap_groups)
            logger.info("Groups are synchronized")
154687
def MergeMembers(self):
    
    for group_name, members in iteritems(self.gshadow_members):
      group = self.entry.get(group_name)
      if group and group.pw_entry.store == self.shadow_store:
        group.members = members.union(group.members)
559577
def update_user(self):
        
        # First create a copy of the current user
        user_dict = self.serialize()
        # Then delete the entities in the description field
        del user_dict['description']['entities']
        # Then upload user_dict
        user, meta = self._api.update_user('me', data=user_dict)
1857
def update_groups_for_user(self, user: User, state: State = None):
        
        if state is None:
            state = user.profile.state
        for config in self.filter(states=state):
            # grant user new groups for their state
            config.update_group_membership_for_user(user)
        for config in self.exclude(states=state):
            # ensure user does not have groups from previous state
            config.remove_user_from_alliance_groups(user)
            config.remove_user_from_corp_groups(user)
1242689
def update_user_groups(self, user, claims):
        
        if settings.GROUPS_CLAIM is not None:
            # Update the user's group memberships
            django_groups = [group.name for group in user.groups.all()]

            if settings.GROUPS_CLAIM in claims:
                claim_groups = claims[settings.GROUPS_CLAIM]
                if not isinstance(claim_groups, list):
                    claim_groups = [claim_groups, ]
            else:
                logger.debug(
                    "The configured groups claim '{}' was not found in the access token".format(settings.GROUPS_CLAIM))
                claim_groups = []

            # Make a diff of the user's groups.
            # Removing a user from all groups and then re-add them would cause
            # the autoincrement value for the database table storing the
            # user-to-group mappings to increment for no reason.
            groups_to_remove = set(django_groups) - set(claim_groups)
            groups_to_add = set(claim_groups) - set(django_groups)

            # Loop through the groups in the group claim and
            # add the user to these groups as needed.
            for group_name in groups_to_remove:
                group = Group.objects.get(name=group_name)
                user.groups.remove(group)
                logger.debug("User removed from group '{}'".format(group_name))

            for group_name in groups_to_add:
                try:
                    if settings.MIRROR_GROUPS:
                        group, _ = Group.objects.get_or_create(name=group_name)
                        logger.debug("Created group '{}'".format(group_name))
                    else:
                        group = Group.objects.get(name=group_name)
                    user.groups.add(group)
                    logger.debug("User added to group '{}'".format(group_name))
                except ObjectDoesNotExist:
                    # Silently fail for non-existing groups.
                    pass
14752
public function updateMemberGroups($data, Member $member)
    {
        if (isset($data['memberof'])) {
            $ldapGroups = is_array($data['memberof']) ? $data['memberof'] : [$data['memberof']];
            foreach ($ldapGroups as $groupDN) {
                foreach (LDAPGroupMapping::get() as $mapping) {
                    if (!$mapping->DN) {
                        $this->getLogger()->debug(
                            sprintf(
                                'LDAPGroupMapping ID %s is missing DN field. Skipping',
                                $mapping->ID
                            )
                        );
                        continue;
                    }

                    // the user is a direct member of group with a mapping, add them to the SS group.
                    if ($mapping->DN == $groupDN) {
                        $group = $mapping->Group();
                        if ($group && $group->exists()) {
                            $group->Members()->add($member, [
                                'IsImportedFromLDAP' => '1'
                            ]);
                            $mappedGroupIDs[] = $mapping->GroupID;
                        }
                    }

                    // the user *might* be a member of a nested group provided the scope of the mapping
                    // is to include the entire subtree. Check all those mappings and find the LDAP child groups
                    // to see if they are a member of one of those. If they are, add them to the SS group
                    if ($mapping->Scope == 'Subtree') {
                        $childGroups = $this->getNestedGroups($mapping->DN, ['dn']);
                        if (!$childGroups) {
                            continue;
                        }

                        foreach ($childGroups as $childGroupDN => $childGroupRecord) {
                            if ($childGroupDN == $groupDN) {
                                $group = $mapping->Group();
                                if ($group && $group->exists()) {
                                    $group->Members()->add($member, [
                                        'IsImportedFromLDAP' => '1'
                                    ]);
                                    $mappedGroupIDs[] = $mapping->GroupID;
                                }
                            }
                        }
                    }
                }
            }
        }

        // Lookup the previous mappings and see if there is any mappings no longer present.
        $unmappedGroups = $member->Groups()->alterDataQuery(function (DataQuery $query) {
            // join with the Group_Members table because we only want those group members assigned by this module.
            $query->leftJoin("Group_Members", '"Group_Members"."GroupID" = "Group"."ID"');
            $query->where('"Group_Members"."IsImportedFromLDAP" = 1');
        });

        // Don't remove associations which have just been added and we know are already correct!
        if (!empty($mappedGroupIDs)) {
            $unmappedGroups = $unmappedGroups->filter("GroupID:NOT", $mappedGroupIDs);
        }

        // Remove the member from any previously mapped groups, where the mapping
        // has since been removed in the LDAP data source
        if ($unmappedGroups->count()) {
            foreach ($unmappedGroups as $group) {
                $group->Members()->remove($member);
            }
        }
    }
1211328
def autogroups_states_changed(sender, instance, action, reverse, model, pk_set, *args, **kwargs):
    
    if action.startswith('post_'):
        for pk in pk_set:
            try:
                state = State.objects.get(pk=pk)
                instance.update_group_membership_for_state(state)
            except State.DoesNotExist:
                # Deleted States handled by the profile state change
                pass
229092
def synchronize(self, user, info):
        '''
        
        '''

        self.debug("Synchronize!")

        # Remove all groups from this user
        user.groups.clear()

        # For all domains found for this user
        for domain in info['groups']:
            # For all groups he is
            for groupname in info['groups'][domain]:
                # Lookup for that group
                group = Group.objects.filter(name=groupname).first()
                if group:
                    # If found, add the user to that group
                    user.groups.add(group)
270108
def memberships(refresh = false)
      @memberships = nil if refresh
      @memberships ||= AccessGroupGroupMember.where(member_id: id).includes(:group).map{|v| v.group}.to_a.freeze
    end
646593
def add_user_to_group(self, user, group_name):
        
        group, _ = Group.objects.get_or_create(name = group_name)
        group.user_set.add(user)
663927
def organization_memberships(self, user):
        
        return self._query_zendesk(self.endpoint.organization_memberships, 'organization_membership', id=user)
1356935
def cli(ctx, group_id, users=None):
    
    return ctx.gi.groups.update_membership(group_id, users=users)
1163624
public void synchronizeUserOrganizationMembership(DbSession dbSession, UserDto user, ALM alm, Set<String> organizationAlmIds) {
    Set<String> userOrganizationUuids = dbClient.organizationMemberDao().selectOrganizationUuidsByUser(dbSession, user.getId());
    Set<String> userOrganizationUuidsWithMembersSyncEnabled = dbClient.organizationAlmBindingDao().selectByOrganizationUuids(dbSession, userOrganizationUuids).stream()
      .filter(OrganizationAlmBindingDto::isMembersSyncEnable)
      .map(OrganizationAlmBindingDto::getOrganizationUuid)
      .collect(toSet());
    Set<String> almOrganizationUuidsWithMembersSyncEnabled = dbClient.organizationAlmBindingDao().selectByOrganizationAlmIds(dbSession, alm, organizationAlmIds).stream()
      .filter(OrganizationAlmBindingDto::isMembersSyncEnable)
      .map(OrganizationAlmBindingDto::getOrganizationUuid)
      .collect(toSet());

    Set<String> organizationUuidsToBeAdded = difference(almOrganizationUuidsWithMembersSyncEnabled, userOrganizationUuidsWithMembersSyncEnabled);
    Set<String> organizationUuidsToBeRemoved = difference(userOrganizationUuidsWithMembersSyncEnabled, almOrganizationUuidsWithMembersSyncEnabled);
    Map<String, OrganizationDto> allOrganizationsByUuid = dbClient.organizationDao().selectByUuids(dbSession, union(organizationUuidsToBeAdded, organizationUuidsToBeRemoved))
      .stream()
      .collect(uniqueIndex(OrganizationDto::getUuid));

    allOrganizationsByUuid.entrySet().stream()
      .filter(entry -> organizationUuidsToBeAdded.contains(entry.getKey()))
      .forEach(entry -> addMemberInDb(dbSession, entry.getValue(), user));
    allOrganizationsByUuid.entrySet().stream()
      .filter(entry -> organizationUuidsToBeRemoved.contains(entry.getKey()))
      .forEach(entry -> removeMemberInDb(dbSession, entry.getValue(), user));
  }