Search and add RBAC rules
438307
public function actionAdd()
	{
		Question::confirm(null, 1);
		$collection = \App::$domain->rbac->rule->searchInAllApps();
		$rules = \App::$domain->rbac->rule->insertBatch($collection);
		if($rules) {
			Output::items($rules, "Added " . count($rules) . " rules");
		} else {
			Output::block("All rules exists!");
		}
	}
77811
def _load_permissions(self):
        """"""
        result = _P(needs=set(), excludes=set())
        if not self.allow_by_default:
            result.needs.update(self.explicit_needs)

        for explicit_need in self.explicit_needs:
            if explicit_need.method == 'action':
                action = current_access.get_action_cache(
                    self._cache_key(explicit_need)
                )
                if action is None:
                    action = _P(needs=set(), excludes=set())

                    actionsusers = ActionUsers.query_by_action(
                        explicit_need
                    ).all()

                    actionsroles = ActionRoles.query_by_action(
                        explicit_need
                    ).join(
                        ActionRoles.role
                    ).all()

                    actionssystem = ActionSystemRoles.query_by_action(
                        explicit_need
                    ).all()

                    for db_action in chain(
                            actionsusers, actionsroles, actionssystem):
                        if db_action.exclude:
                            action.excludes.add(db_action.need)
                        else:
                            action.needs.add(db_action.need)

                    current_access.set_action_cache(
                        self._cache_key(explicit_need),
                        action
                    )
                # in-place update of results
                result.update(action)
            elif self.allow_by_default:
                result.needs.add(explicit_need)
        self._permissions = result
485302
def basic_info(user, keys):
    """"""

    table = formatting.KeyValueTable(['Title', 'Basic Information'])
    table.align['Title'] = 'r'
    table.align['Basic Information'] = 'l'

    table.add_row(['Id', user.get('id', '-')])
    table.add_row(['Username', user.get('username', '-')])
    if keys:
        for key in user.get('apiAuthenticationKeys'):
            table.add_row(['APIKEY', key.get('authenticationKey')])
    table.add_row(['Name', "%s %s" % (user.get('firstName', '-'), user.get('lastName', '-'))])
    table.add_row(['Email', user.get('email')])
    table.add_row(['OpenID', user.get('openIdConnectUserName')])
    address = "%s %s %s %s %s %s" % (
        user.get('address1'), user.get('address2'), user.get('city'), user.get('state'),
        user.get('country'), user.get('postalCode'))
    table.add_row(['Address', address])
    table.add_row(['Company', user.get('companyName')])
    table.add_row(['Created', user.get('createDate')])
    table.add_row(['Phone Number', user.get('officePhone')])
    if user.get('parentId', False):
        table.add_row(['Parent User', utils.lookup(user, 'parent', 'username')])
    table.add_row(['Status', utils.lookup(user, 'userStatus', 'name')])
    table.add_row(['PPTP VPN', user.get('pptpVpnAllowedFlag', 'No')])
    table.add_row(['SSL VPN', user.get('sslVpnAllowedFlag', 'No')])
    for login in user.get('unsuccessfulLogins', {}):
        login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
        table.add_row(['Last Failed Login', login_string])
        break
    for login in user.get('successfulLogins', {}):
        login_string = "%s From: %s" % (login.get('createDate'), login.get('ipAddress'))
        table.add_row(['Last Login', login_string])
        break

    return table
132386
def add(user_id, resource_policy, admin, inactive,  rate_limit):
    '''
    
    '''
    try:
        user_id = int(user_id)
    except ValueError:
        pass  # string-based user ID for Backend.AI v1.4+
    with Session() as session:
        try:
            data = session.KeyPair.create(
                user_id,
                is_active=not inactive,
                is_admin=admin,
                resource_policy=resource_policy,
                rate_limit=rate_limit)
        except Exception as e:
            print_error(e)
            sys.exit(1)
        if not data['ok']:
            print_fail('KeyPair creation has failed: {0}'.format(data['msg']))
            sys.exit(1)
        item = data['keypair']
        print('Access Key: {0}'.format(item['access_key']))
        print('Secret Key: {0}'.format(item['secret_key']))
182802
def search(self, key_pattern: str, user_pattern: str) -> List[Entry]:
        """"""
        # normalize key
        key_pattern = _normalized_key(key_pattern)

        # search
        results = []
        for entry in self.entries:
            if key_pattern in entry.key and user_pattern in entry.user:
                results.append(entry)

        # sort results according to key (stability of sorted() ensures that the order of accounts for any given key remains untouched)
        return sorted(results, key=lambda e: e.key)
575552
def filter(self, table, security_groups, filter_string):
        """"""
        query = filter_string.lower()
        return [security_group for security_group in security_groups
                if query in security_group.name.lower()]
558087
def SecurityCheck(self, func, request, *args, **kwargs):
    """"""
    request.user = u""

    authorized = False
    try:
      auth_type, authorization = request.headers.get("Authorization",
                                                     " ").split(" ", 1)

      if auth_type == "Basic":
        authorization_string = authorization.decode("base64").decode("utf-8")
        user, password = authorization_string.split(":", 1)

        if data_store.AFF4Enabled():

          token = access_control.ACLToken(username=user)

          fd = aff4.FACTORY.Open(
              "aff4:/users/%s" % user,
              aff4_type=aff4_users.GRRUser,
              token=token)
          crypted_password = fd.Get(fd.Schema.PASSWORD)
          if crypted_password and crypted_password.CheckPassword(password):
            authorized = True

            # The password is ok - update the user
            request.user = user

        else:

          try:
            user_obj = data_store.REL_DB.ReadGRRUser(user)
            if user_obj.password.CheckPassword(password):
              authorized = True

              # The password is ok - update the user
              request.user = user

          except db.UnknownGRRUserError:
            pass

    except access_control.UnauthorizedAccess as e:
      logging.warning("UnauthorizedAccess: %s for %s", e, request)
    except (IndexError, KeyError, IOError):
      pass

    if not authorized:
      result = werkzeug_wrappers.Response("Unauthorized", status=401)
      result.headers["WWW-Authenticate"] = "Basic realm='Secure Area'"
      return result

    # Modify this to implement additional checking (e.g. enforce SSL).
    return func(request, *args, **kwargs)
629288
def ldap_search(self, filter, attributes, incremental, incremental_filter):
        
        for uri in self.conf_LDAP_SYNC_BIND_URI:
            #Read record of this uri
            if (self.working_uri == uri):
                adldap_sync = self.working_adldap_sync
                created = False
            else:
                adldap_sync, created = ADldap_Sync.objects.get_or_create(ldap_sync_uri=uri)

            if ((adldap_sync.syncs_to_full > 0) and incremental):
                filter_to_use = incremental_filter.replace('?', self.whenchanged.strftime(self.conf_LDAP_SYNC_INCREMENTAL_TIMESTAMPFORMAT))
                logger.debug("Using an incremental search. Filter is:'%s'" % filter_to_use)
            else:
                filter_to_use = filter

            ldap.set_option(ldap.OPT_REFERRALS, 0)
            #ldap.set_option(ldap.OPT_NETWORK_TIMEOUT, 10)
            l = PagedLDAPObject(uri)
            l.protocol_version = 3

            if (uri.startswith('ldaps:')):
                l.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_DEMAND)
                l.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_DEMAND)
                l.set_option(ldap.OPT_X_TLS_DEMAND, True)
            else:
                l.set_option(ldap.OPT_X_TLS, ldap.OPT_X_TLS_NEVER)
                l.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER)
                l.set_option(ldap.OPT_X_TLS_DEMAND, False)
            try:
                l.simple_bind_s(self.conf_LDAP_SYNC_BIND_DN, self.conf_LDAP_SYNC_BIND_PASS)
            except ldap.LDAPError as e:
                logger.error("Error connecting to LDAP server %s : %s" % (uri, e))
                continue

            results = l.paged_search_ext_s(self.conf_LDAP_SYNC_BIND_SEARCH, ldap.SCOPE_SUBTREE, filter_to_use, attrlist=attributes, serverctrls=None)
            l.unbind_s()
            if (self.working_uri is None):
                self.working_uri = uri
                self.conf_LDAP_SYNC_BIND_URI.insert(0, uri)
                self.working_adldap_sync = adldap_sync

            return (uri, results)  # Return both the LDAP server URI used and the request. This is for incremental sync purposes
        #if not connected correctly, raise error
        raise
1260662
def get_items_by_search(self, item_query, item_search):
        """"""
        # Implemented from azosid template for -
        # osid.resource.ResourceSearchSession.get_resources_by_search_template
        if not self._can('search'):
            raise PermissionDenied()
        return self._provider_session.get_items_by_search(item_query, item_search)
811744
def search(self, regex=None, spec=None, **kwargs):
        """"""
        cmd_list = ['search', '--json']

        if regex and spec:
            raise TypeError('conda search: only one of regex or spec allowed')

        if regex:
            cmd_list.append(regex)

        if spec:
            cmd_list.extend(['--spec', spec])

        if 'platform' in kwargs:
            cmd_list.extend(['--platform', kwargs.pop('platform')])

        cmd_list.extend(
            self._setup_install_commands_from_kwargs(
                kwargs,
                ('canonical', 'unknown', 'use_index_cache', 'outdated',
                 'override_channels')))

        return self._call_and_parse(cmd_list,
                                    abspath=kwargs.get('abspath', True))
479462
def user_filter(query)
      filter  = "(&"
      filter += "(|(sn=#{query}*)(givenName=#{query}*)(mail=#{query}*))"
      filter += "(!(sAMAccountname=admin*))"
      filter += "(!(sAMAccountname=*test*))"
      filter += "(!(sn=*test*))"
      filter += "(!(sn=*admin*))"
      filter += "(!(givenName=*admin*))"
      filter += "(UserAccountControl:1.2.840.113556.1.4.803:=512)"
      filter += "(!(UserAccountControl:1.2.840.113556.1.4.803:=2))"
      filter += "(!(primaryGroupID=512))"
      filter += "(!(msExchHideFromAddressLists=TRUE))"
      filter += ")"
      filter = Net::LDAP::Filter.construct(filter)
    end
1089307
async function makeRbacAdmin (rbacService, options) {
  const rbacAdmin = new RbacAdmin()
  await rbacAdmin.init(rbacService, options)
  return rbacAdmin
}
347455
def search(self, *args, **kwargs):
        """"""
        ret = []
        for record in Handler.ALL_VERS_DATA.values():
            matchArgs = list(kwargs.keys())
            for k,v in iteritems(kwargs): # restrict records based on key-value match requirement
                try:
                    if record[k] != v: break # a non-matching requirement means this record doesn't match
                except: break # record doesn't have required key 'k'
                matchArgs.remove(k)
            if matchArgs: continue # didn't match all required kwargs
            matchArgs = list(args)
            for k,v in iteritems(record): # find any record with a <value> in it
                if k in matchArgs: matchArgs.remove(k)
                if v in matchArgs: matchArgs.remove(v)
            if matchArgs: continue # didn't match all required args
            ret.append(record)
        return ret
805398
def query(self, base, filterstr, attrlist=None):
		
		return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)
969223
def alter(data, system):
    """"""
    device = data[0]
    action = data[1]
    if data[2] == '*':
        data[2] = '.*'
    regex = re.compile(data[2])
    prop = data[3]
    value = float(data[4])
    if action == 'MUL':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] *= value
    elif action == 'REP':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] = value
    elif action == 'DIV':
        if not value:
            return
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] /= value
    elif action == 'SUM':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] += value
    elif action == 'SUB':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] -= value
    elif action == 'POW':
        for item in range(system.__dict__[device].n):
            if regex.search(system.__dict__[device].name[item]):
                system.__dict__[device].__dict__[prop][item] **= value
    else:
        print('ALTER action <%s> is not defined', action)
1296885
public function search($params)
    {
        /* @var \yii\rbac\Manager $authManager */
        $authManager = Configs::authManager();
        if ($this->type == Item::TYPE_ROLE) {
            $items = $authManager->getRoles();
        } else {
            $items = array_filter($authManager->getPermissions(), function($item) {
                return $this->type == Item::TYPE_PERMISSION xor strncmp($item->name, '/', 1) === 0;
            });
        }
        $this->load($params);
        if ($this->validate()) {

            $search = mb_strtolower(trim($this->name));
            $desc = mb_strtolower(trim($this->description));
            $ruleName = $this->ruleName;
            foreach ($items as $name => $item) {
                $f = (empty($search) || mb_strpos(mb_strtolower($item->name), $search) !== false) &&
                    (empty($desc) || mb_strpos(mb_strtolower($item->description), $desc) !== false) &&
                    (empty($ruleName) || $item->ruleName == $ruleName);
                if (!$f) {
                    unset($items[$name]);
                }
            }
        }

        return new ArrayDataProvider([
            'allModels' => $items,
        ]);
    }
1278999
function hasRole(rbac, role, cb) {
  if (!this.role) {
    cb(null, false);
    return this;
  }

  // check existance of permission
  rbac.hasRole(this.role, role, cb);
  return this;
}