Generating enums for RBAC roles, permissions and rules
16507
public function actionGenerate()
	{
		Question::confirm(null, 1);
		$count = \App::$domain->rbac->const->generateAll();
		if($count) {
			Output::block("Generated {$count} constants");
		} else {
			Output::block("All rules exists!");
		}
	}
944968
def object_permission_set(self):
        ''''''
        return Or(
            AllowOnlySafeHttpMethod,
            AllowAdmin,
            And(
                AllowPermission('org:admin'),
                ObjAttrTrue(lambda _, u: not u.is_superuser),
                ObjAttrTrue(
                    lambda r, _: r.data.get('admin') is not True)
            ),
            And(
                AllowModify,
                ObjAttrTrue(
                    lambda req, user: user == req.user),
                ObjAttrTrue(
                    lambda r, _: r.data.get('admin') is not True)
            ),
        )
297252
function can(rbac, action, resource, cb) {
  // check existance of permission
  rbac.getPermission(action, resource, (err, permission) => {
    if (err) {
      return cb(err);
    }

    if (!permission) {
      return cb(null, false);
    }

    // check user additional permissions
    if (indexOf(this.permissions, permission.name) !== -1) {
      return cb(null, true);
    }

    if (!this.role) {
      return cb(null, false);
    }

    // check permission inside user role
    return rbac.can(this.role, action, resource, cb);
  });

  return this;
}
960096
def _get_all_permissions(opts, tools):
    """"""
    perms = []
    for tool in tools:
        perms.append((_get_permission_codename(tool, opts), 'Can %s %s' % \
                (tool.name, opts.verbose_name_plural)))
    return perms
1021017
def _lookup_enum_in_ns(namespace, value):
    """"""
    for attribute in dir(namespace):
        if getattr(namespace, attribute) == value:
            return attribute
244761
function enum_ (options) {
  options.hash.kind = 'member'
  options.hash.isEnum = true
  var result = _identifier(options)
  return result ? options.fn(result) : 'ERROR, Cannot find enum.'
}
822458
def permissions(self):
        """"""
        perms = set()
        for r in self.roles:
            perms = perms | set(r.permissions)
        return perms
188313
def cli(obj, role, scopes, delete):
    """"""
    client = obj['client']
    if delete:
        client.delete_perm(delete)
    else:
        if not role:
            raise click.UsageError('Missing option "--role".')
        if not scopes:
            raise click.UsageError('Missing option "--scope".')
        try:
            perm = client.create_perm(role, scopes)
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
            sys.exit(1)
        click.echo(perm.id)
299558
def cli_default_perms(self, *args):
        """"""

        for key, item in schemastore.items():
            # self.log(item, pretty=True)
            if item['schema'].get('no_perms', False):
                self.log('Schema without permissions:', key)
                continue
            try:
                perms = item['schema']['properties']['perms']['properties']
                if perms == {}:
                    self.log('Schema:', item, pretty=True)

                self.log(
                    'Schema:', key,
                    'read', perms['read']['default'],
                    'write', perms['write']['default'],
                    'list', perms['list']['default'],
                    'create', item['schema']['roles_create']
                )
            except KeyError as e:
                self.log('Fishy schema found:', key, e, lvl=error)
                self.log(item, pretty=True)
835987
def enum(name = nil, localized_name = name)

      if block_given?

        yield.each do |key, value|
          options = value.map { |k, v| [ k.to_sym, v ] }.to_h
          #options[:optional] = true if options[:optional].nil?
          code    = options.delete :code
          safe_add_item ProgneTapera::EnumItem.new(code, key.to_s, options)
        end

      else

        name         = enum_name(name).to_s
        enumerations = Rails.configuration.enum[name]
        raise ArgumentError.new("The enum.#{name} was not configured in the config/enum.yml file.") if enumerations.blank?

        enumerations.each do |key, value|
          options = value.map { |k, v| [ k.to_sym, v ] }.to_h
          #options[:optional] = false
          code    = options.delete :code
          options[:localized_name] = I18n.t "enum.#{localized_name||name}.#{key}"
          item = ProgneTapera::EnumItem.new code, key, options

          item_method_module = "#{self.name}::ItemMethods".safe_constantize
          item.class_eval do
            include item_method_module if item_method_module.present?
          end
          #class << item
          #  include item_method_module if item_method_module.present?
          #end

          safe_add_item item
        end

      end

    end
1134282
def _enum_generator(descriptor):
    ''
    vals = descriptor.enum_type.values_by_number.keys()
    return gen.IterValueGenerator(descriptor.name, vals)
195175
function buildRole(options, roleName='LambdaCfnRole') {
  let role = {
    Resources: {}
  };

  role.Resources[roleName] = {
    Type: 'AWS::IAM::Role',
    Properties: {
      AssumeRolePolicyDocument: {
        Statement: [
          {
            Sid: '',
            Effect: 'Allow',
            Principal: {
              Service: 'lambda.amazonaws.com'
            },
            Action: 'sts:AssumeRole'
          },
          {
            Sid: '',
            Effect: 'Allow',
            Principal: {
              Service: 'events.amazonaws.com'
            },
            Action: 'sts:AssumeRole'
          }
        ]
      },
      Path: '/',
      Policies: [
        {
          PolicyName: 'basic',
          PolicyDocument: {
            Statement: [
              {
                Effect: 'Allow',
                Action: [
                  'logs:*'
                ],
                Resource: cf.join(['arn:aws:logs:*:', cf.accountId, ':*'])
              },
              {
                Effect: 'Allow',
                Action: [
                  'sns:Publish'
                ],
                Resource: cf.ref('ServiceAlarmSNSTopic')
              },
              {
                Effect: 'Allow',
                Action: [
                  'iam:SimulateCustomPolicy'
                ],
                Resource: '*'
              }
            ]
          }
        },
      ]
    }
  };

  if (options.eventSources && options.eventSources.webhook) {
    role.Resources[roleName].Properties.AssumeRolePolicyDocument.Statement.push({
      Sid: '',
      Effect: 'Allow',
      Principal: {
        Service: 'apigateway.amazonaws.com'
      },
      Action: 'sts:AssumeRole'
    });
  }

  if (options.statements) {
    statementValidation(options);

    role.Resources[roleName].Properties.Policies.push({
      PolicyName: options.name,
      PolicyDocument: {
        Statement: options.statements
      }
    });
  }

  return role;
}
525202
function createEasyAccess() {
  var userConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var conf = Object.assign({}, defaultConfig, userConfig);
  return function (store) {
    generateSetterModules(store, conf);

    store[conf.setter] = function (path, payload) {
      return defaultSetter(path, payload, store, conf);
    };

    store[conf.getter] = function (path) {
      return defaultGetter(path, store);
    };

    store[conf.deletor] = function (path, payload) {
      return defaultDeletor(path, payload, store, conf);
    };
  };
}
814220
def model_enums(vk, model):
    
    model['enums'] = {}

    # init enums dict
    enums_type = [x['@name'] for x in vk['registry']['types']['type']
                  if x.get('@category') == 'enum']

    for name in enums_type:
        model['enums'][name] = {}

    # create enums
    enums = [x for x in vk['registry']['enums']
             if x.get('@type') in ('enum', 'bitmask')]

    for enum in enums:
        name = enum['@name']
        t = enum.get('@type')

        # enum may have no enums (because of extension)
        if not enum.get('enum'):
            continue

        if t in ('enum', 'bitmask'):
            # add attr to enum
            for attr in enum['enum']:
                if '@bitpos' in attr:
                    num_val = int(attr['@bitpos'], 0)
                    num_val = 1 << num_val
                    val = '0x%08x' % num_val
                elif '@value' in attr:
                    val = attr['@value']

                model['enums'][name][attr['@name']] = val

        # Add computed value
        def ext_name(name, extension):
            if extension:
                return name + '_' + extension
            return name

        extension = next(iter([x for x in VENDOR_EXTENSIONS
                               if name.lower().endswith(x)]), '').upper()

        standard_name = inflection.underscore(name).upper()
        if extension:
            standard_name = standard_name.split(extension)[0][:-1]

        if t == 'bitmask':
            en = ext_name(standard_name, '_MAX_ENUM')
            model['enums'][name][en] = 0x7FFFFFFF
        else:
            values = [int(x, 0) for x in model['enums'][name].values()]

            begin_attr = ext_name(standard_name, '_BEGIN_RANGE')
            end_attr = ext_name(standard_name, '_END_RANGE')
            size_attr = ext_name(standard_name, '_RANGE_SIZE')
            max_attr = ext_name(standard_name, '_MAX_ENUM')

            model['enums'][name][begin_attr] = min(values)
            model['enums'][name][end_attr] = max(values)
            model['enums'][name][size_attr] = max(values) - min(values) + 1
            model['enums'][name][max_attr] = 0x7FFFFFFF

    # Enum in features
    ext_base = 1000000000
    ext_blocksize = 1000
    # base + (ext - 1) * blocksize + offset
    for feature in vk['registry']['feature']:
        for require in feature['require']:
            if not 'enum' in require:
                continue
            for enum in require['enum']:
                if not '@extnumber' in enum:
                    continue
                n1 = int(enum['@extnumber'])
                n2 = int(enum['@offset'])
                extend = enum['@extends']
                val = ext_base + (n1 - 1) * ext_blocksize + n2
                model['enums'][extend][enum['@name']] = val
49396
public void permissionDenied(final ProtectionDomain pd, final Permission perm) {
        final StringBuilder sb = new StringBuilder(">> Denied permission ");
        sb.append(perm.getClass().getName()).append(" \"") //
                .append(createPrintablePermissionName(perm.getName())).append("\""); //
        if (perm.getActions()!=null && !perm.getActions().equals("")) {
                sb.append(", \"").append(perm.getActions()).append("\"");
        }
        sb.append(";");
        if (includeCodeSource) {
            sb.append("\n>>> CodeSource: " + pd.getCodeSource());
        }
        printStream.println(sb);
    }
1120382
def del_action_role(ctx):
    """"""

    objects = ctx.obj['objects']
    action = ctx.obj['action']
    role = ctx.obj['role']

    if action is None or role is None:
        log('You need to specify an action or role to the RBAC command group for this to work.', lvl=warn)
        return

    for item in objects:
        if role in item.perms[action]:
            item.perms[action].remove(role)
            item.save()

    log("Done")
1241483
function enum_ (options) {
  options.hash.kind = 'enum'
  var result = ddata._identifier(options)
  return result ? options.fn(result) : 'ERROR, Cannot find enum.'
}