- sets an acl user group to hold all intranet users
    - setup the dynamic groups plugin
    - sets the addable types for the ploneintranet policy
505523
def post_install(context):
    
    marker = 'ploneintranet-workspace.marker'
    if context.readDataFile(marker) is None:
        return

    portal = api.portal.get()

    # Set up a group to hold all intranet users
    if api.group.get(groupname=INTRANET_USERS_GROUP_ID) is None:
        api.group.create(groupname=INTRANET_USERS_GROUP_ID)
        # All users have Reader role on portal root
        api.group.grant_roles(groupname=INTRANET_USERS_GROUP_ID,
                              roles=['Reader', ],
                              obj=portal)

    # Set up dynamic groups plugin to put all users into the above group
    pas = api.portal.get_tool('acl_users')
    if DYNAMIC_GROUPS_PLUGIN_ID not in pas.objectIds():
        addDynamicGroupsPlugin(
            pas,
            DYNAMIC_GROUPS_PLUGIN_ID,
            "ploneintranet.workspace Dynamic Groups"
        )
        plugin = pas[DYNAMIC_GROUPS_PLUGIN_ID]
        plugin.addGroup(
            group_id=INTRANET_USERS_GROUP_ID,
            predicate='python: True',
            title='All Intranet Users',
            description='',
            active=True,
        )
        # activate the plugin (all interfaces)
        activatePluginInterfaces(portal, DYNAMIC_GROUPS_PLUGIN_ID)

    # deactivate the enumerate groups interface for collective.workspace
    activatePluginInterfaces(portal, 'workspace_groups',
                             disable=['IGroupEnumerationPlugin'])

    # Set up the ploneintranet policy for all addable types
    default_types = []
    types = api.portal.get_tool('portal_types')
    for type_info in types.listTypeInfo():
        if type_info.global_allow:
            default_types.append(type_info.getId())

    if default_types:
        pwftool = api.portal.get_tool('portal_placeful_workflow')
        policy = pwftool['ploneintranet_policy']
        policy.setChainForPortalTypes(default_types, ('(Default)',))
1360169
public void setUserGroupRoleLocalService(
		com.liferay.portal.kernel.service.UserGroupRoleLocalService userGroupRoleLocalService) {
		this.userGroupRoleLocalService = userGroupRoleLocalService;
	}
495267
protected function setUserFromDb()
	{
		$this->intId = $this->id;

		foreach ($this->arrData as $key => $value) {
			if (! is_numeric($value)) {
				$this->$key = \StringUtil::deserialize($value);
			}
		}

		$always = array('alexf');
		$depends = array();

		if (is_array($GLOBALS['TL_PERMISSIONS']) && ! empty($GLOBALS['TL_PERMISSIONS'])) {
			$depends = array_merge($depends, $GLOBALS['TL_PERMISSIONS']);
		}

		if ($this->inherit == 'group') {
			foreach ($depends as $field) {
				$this->$field = array();
			}
		}

		$inherit = in_array($this->inherit, array('group', 'extend')) ? array_merge($always, $depends) : $always;
		$time = time();

		foreach ((array) $this->groups as $id) {

			$objGroup = $this->Database
				->prepare("SELECT * FROM tl_user_group WHERE id=? AND disable!=1 AND (start='' OR start<$time) AND (stop='' OR stop>$time)")
				->limit(1)
				->execute($id);

			if ($objGroup->numRows > 0) {
				foreach ($inherit as $field) {
					$value = \StringUtil::deserialize($objGroup->$field, true);
					if (!empty($value)) {
						$this->$field = array_merge((is_array($this->$field) ? $this->$field : (($this->$field != '') ? array($this->$field) : array())), $value);
						$this->$field = array_unique($this->$field);
					}
				}
			}

		}
	}
1031467
def set_acl(self, role, users):
        
        acl_updates = [{"user": user, "role": role} for user in users]
        r = fapi.update_repository_method_acl(
            self.namespace, self.name, self.snapshot_id,
            acl_updates, self.api_url
        )
        fapi._check_response_code(r, 200)
943624
def user_in_any_group(user, groups):
    """"""
    return user_is_superuser(user) or any(user_in_group(user, group) for group in groups)
1297994
private function loadAcl()
    {
        $this->acl = new Acl();

        foreach ($this->serviceLocator->get('BjyAuthorize\RoleProviders') as $provider) {
            $this->addRoleProvider($provider);
        }

        foreach ($this->serviceLocator->get('BjyAuthorize\ResourceProviders') as $provider) {
            $this->addResourceProvider($provider);
        }

        foreach ($this->serviceLocator->get('BjyAuthorize\RuleProviders') as $provider) {
            $this->addRuleProvider($provider);
        }

        foreach ($this->serviceLocator->get('BjyAuthorize\Guards') as $guard) {
            $this->addGuard($guard);
        }

        foreach ($this->roleProviders as $provider) {
            $this->addRoles($provider->getRoles());
        }

        foreach ($this->resourceProviders as $provider) {
            $this->loadResource($provider->getResources(), null);
        }

        foreach ($this->ruleProviders as $provider) {
            $rules = $provider->getRules();
            if (isset($rules['allow'])) {
                foreach ($rules['allow'] as $rule) {
                    $this->loadRule($rule, static::TYPE_ALLOW);
                }
            }

            if (isset($rules['deny'])) {
                foreach ($rules['deny'] as $rule) {
                    $this->loadRule($rule, static::TYPE_DENY);
                }
            }
        }
    }
872888
def update_user_flags(self, user, claims):
        
        if settings.GROUPS_CLAIM is not None:
            if settings.GROUPS_CLAIM in claims:
                access_token_groups = claims[settings.GROUPS_CLAIM]
                if not isinstance(access_token_groups, list):
                    access_token_groups = [access_token_groups, ]
            else:
                logger.debug("The configured group claim was not found in the access token")
                access_token_groups = []

            for flag, group in settings.GROUP_TO_FLAG_MAPPING.items():
                if hasattr(user, flag):
                    if group in access_token_groups:
                        value = True
                    else:
                        value = False
                    setattr(user, flag, value)
                    logger.debug("Attribute '{}' for user '{}' was set to '{}'.".format(user, flag, value))
                else:
                    msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
                    raise ImproperlyConfigured(msg.format(flag))

        for field, claim in settings.BOOLEAN_CLAIM_MAPPING.items():
            if hasattr(user, field):
                bool_val = False
                if claim in claims and str(claims[claim]).lower() in ['y', 'yes', 't', 'true', 'on', '1']:
                    bool_val = True
                setattr(user, field, bool_val)
                logger.debug('Attribute "{}" for user "{}" was set to "{}".'.format(user, field, bool_val))
            else:
                msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
                raise ImproperlyConfigured(msg.format(field))
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)
19278
def _parse_acl(acl, user, group):
    '''
    
    '''
    comps = acl.split(':')
    vals = {}

    # What type of rule is this?
    vals['type'] = 'acl'
    if comps[0] == 'default':
        vals['type'] = 'default'
        comps.pop(0)

    # If a user is not specified, use the owner of the file
    if comps[0] == 'user' and not comps[1]:
        comps[1] = user
    elif comps[0] == 'group' and not comps[1]:
        comps[1] = group
    vals[comps[0]] = comps[1]

    # Set the permissions fields
    octal = 0
    vals['permissions'] = {}
    if 'r' in comps[-1]:
        octal += 4
        vals['permissions']['read'] = True
    else:
        vals['permissions']['read'] = False
    if 'w' in comps[-1]:
        octal += 2
        vals['permissions']['write'] = True
    else:
        vals['permissions']['write'] = False
    if 'x' in comps[-1]:
        octal += 1
        vals['permissions']['execute'] = True
    else:
        vals['permissions']['execute'] = False
    vals['octal'] = octal

    return vals
23526
public void add(Group group, AccessLevel accessLevel) {
        getAccessList().add(new Access(group, accessLevel));
    }
97473
public void setMembership() {

        if ((m_orgUnit == null) || (m_membership == null)) {
            return;
        }

        // get the membership data to set
        Map<String, Map<String, String>> membership = m_membership.get(m_orgUnit.getName());
        if (membership == null) {
            return;
        }

        // set group membership
        Map<String, String> groups = membership.get(I_CmsPrincipal.PRINCIPAL_GROUP);
        if (groups != null) {
            Iterator<Entry<String, String>> it = groups.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, String> entry = it.next();
                String userName = entry.getKey();
                String groupName = entry.getValue();

                // set the users group
                try {
                    getCms().addUserToGroup(userName, groupName);
                } catch (Throwable e) {
                    getReport().println(
                        Messages.get().container(Messages.RPT_USER_COULDNT_BE_ADDED_TO_GROUP_2, userName, groupName),
                        I_CmsReport.FORMAT_WARNING);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }

        // set role membership
        Map<String, String> roles = membership.get(I_CmsPrincipal.PRINCIPAL_USER);
        if (roles != null) {
            Iterator<Entry<String, String>> it = roles.entrySet().iterator();
            while (it.hasNext()) {
                Entry<String, String> entry = it.next();
                String userName = entry.getKey();
                String roleName = entry.getValue();

                // set the users roles
                CmsRole role = CmsRole.valueOfRoleName(roleName);
                try {
                    // set the user role
                    OpenCms.getRoleManager().addUserToRole(getCms(), role, userName);
                    return;
                } catch (Throwable e) {
                    getReport().println(
                        Messages.get().container(Messages.RPT_USER_COULDNT_BE_ADDED_TO_ROLE_2, userName, roleName),
                        I_CmsReport.FORMAT_WARNING);
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(e.getLocalizedMessage(), e);
                    }
                }
            }
        }
    }
621976
def add_user(self, user, group):
        
        if self.is_user_in(user, group):
            raise UserAlreadyInAGroup
        self.new_groups.add(group, user)
89441
public GitlabGroup updateGroup(GitlabGroup group, GitlabUser sudoUser) throws IOException {

        Query query = new Query()
                .appendIf("name", group.getName())
                .appendIf("path", group.getPath())
                .appendIf("description", group.getDescription())
                .appendIf("membership_lock", group.getMembershipLock())
                .appendIf("share_with_group_lock", group.getShareWithGroupLock())
                .appendIf("visibility", group.getVisibility().toString())
                .appendIf("lfs_enabled", group.isLfsEnabled())
                .appendIf("request_access_enabled", group.isRequestAccessEnabled())
                .appendIf("shared_runners_minutes_limit", group.getSharedRunnersMinutesLimit())
                .appendIf("ldap_cn", group.getLdapCn())
                .appendIf("ldap_access", group.getLdapAccess())
                .appendIf(PARAM_SUDO, sudoUser != null ? sudoUser.getId() : null);

        String tailUrl = GitlabGroup.URL + "/" + group.getId() + query.toString();

        return retrieve().method(PUT).to(tailUrl, GitlabGroup.class);
    }
290656
public void setUsers(Set<PrincipalUser> users) {
        SystemAssert.requireArgument(users != null && !users.isEmpty(), "Users associated with a namespace cannot be null or empty.");
        this.users.clear();
        if (users != null && !users.isEmpty()) {
            this.users.addAll(users);
        }
    }
637797
public void setOwner(Path f, String user, String group) throws IOException {
    try (Closeable context = new TimerContextWithLog(this.setOwnerTimer.time(), "setOwner", f, user, group)) {
      super.setOwner(f, user, group);
    }
  }
210362
def assign_user_policies(user, *policies_roles):
    
    clear_user_policies(user)
    pset = PermissionSet.objects.by_policies_and_roles(policies_roles)
    pset.refresh()
    if user is None:
        pset.anonymous_user = True
    else:
        pset.users.add(user)
    pset.save()
    cache.set(user_cache_key(user), None)
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