desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'This method is ignored, but provided for compatibility.'
| def simple_bind_s(self, dn, password):
| if server_fail:
raise ldap.SERVER_DOWN
LOG.debug(_('FakeLdap bind dn=%s'), dn)
if ((dn == 'cn=Admin') and (password == 'password')):
return
try:
attrs = self.db[('%s%s' % (self.__prefix, dn))]
except KeyError:
LOG.debug(_('FakeLdap bind fail: dn=%s n... |
'This method is ignored, but provided for compatibility.'
| def unbind_s(self):
| if server_fail:
raise ldap.SERVER_DOWN
|
'Add an object with the specified attributes at dn.'
| def add_s(self, dn, attrs):
| if server_fail:
raise ldap.SERVER_DOWN
key = ('%s%s' % (self.__prefix, dn))
LOG.debug(_('FakeLdap add item: dn=%s, attrs=%s'), dn, attrs)
if (key in self.db):
LOG.debug(_('FakeLdap add item failed: dn=%s is already in store.'), dn)
raise ldap.A... |
'Remove the ldap object at specified dn.'
| def delete_s(self, dn):
| if server_fail:
raise ldap.SERVER_DOWN
key = ('%s%s' % (self.__prefix, dn))
LOG.debug(_('FakeLdap delete item: dn=%s'), dn)
try:
del self.db[key]
except KeyError:
LOG.debug(_('FakeLdap delete item failed: dn=%s not found.'), dn)
raise ldap.N... |
'Remove the ldap object at specified dn.'
| def delete_ext_s(self, dn, serverctrls):
| if server_fail:
raise ldap.SERVER_DOWN
key = ('%s%s' % (self.__prefix, dn))
LOG.debug(_('FakeLdap delete item: dn=%s'), dn)
try:
del self.db[key]
except KeyError:
LOG.debug(_('FakeLdap delete item failed: dn=%s not found.'), dn)
raise ldap.N... |
'Modify the object at dn using the attribute list.
:param dn: an LDAP DN
:param attrs: a list of tuples in the following form:
([MOD_ADD | MOD_DELETE | MOD_REPACE], attribute, value)'
| def modify_s(self, dn, attrs):
| if server_fail:
raise ldap.SERVER_DOWN
key = ('%s%s' % (self.__prefix, dn))
LOG.debug(_('FakeLdap modify item: dn=%s attrs=%s'), dn, attrs)
try:
entry = self.db[key]
except KeyError:
LOG.debug(_('FakeLdap modify item failed: dn=%s not found.'), d... |
'Search for all matching objects under dn using the query.
Args:
dn -- dn to search under
scope -- only SCOPE_BASE and SCOPE_SUBTREE are supported
query -- query to filter objects by
fields -- fields to return. Returns all fields if not specified'
| def search_s(self, dn, scope, query=None, fields=None):
| if server_fail:
raise ldap.SERVER_DOWN
LOG.debug(_('FakeLdap search at dn=%s scope=%s query=%s'), dn, SCOPE_NAMES.get(scope, scope), query)
if (scope == ldap.SCOPE_BASE):
try:
item_dict = self.db[('%s%s' % (self.__prefix, dn))]
except KeyError:
... |
'Run a WSGI server with the given application.'
| def start(self, key=None, backlog=128):
| LOG.debug((_('Starting %(arg0)s on %(host)s:%(port)s') % {'arg0': sys.argv[0], 'host': self.host, 'port': self.port}))
info = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)[0]
_socket = eventlet.listen(info[(-1)], family=info[0], backlog=backlog)
if key:
... |
'Wait until all servers have completed running.'
| def wait(self):
| try:
self.pool.waitall()
except KeyboardInterrupt:
pass
|
'Start a WSGI server in a new green thread.'
| def _run(self, application, socket):
| log = logging.getLogger('eventlet.wsgi.server')
try:
eventlet.wsgi.server(socket, application, custom_pool=self.pool, log=WritableLogger(log))
except Exception:
LOG.exception(_('Server error'))
raise
|
'Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [app:APPNAME]
section of the paste config) will be passed into the `__init__` method
as kwargs.
A hypothetical configuration would look like:
[app:wadl]
latest_version = 1.3
paste.app_factory = nova.api.fancy_... | @classmethod
def factory(cls, global_config, **local_config):
| return cls()
|
'Subclasses will probably want to implement __call__ like this:
@webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
# Any of the following objects work as responses:
# Option 1: simple string
res = \'message\n\'
# Option 2: a nicely formatted HTTP exception page
res = exc.HTTPForbidden(detail=\'Nice try\')... | def __call__(self, environ, start_response):
| raise NotImplementedError('You must implement __call__')
|
'Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [filter:APPNAME]
section of the paste config) will be passed into the `__init__` method
as kwargs.
A hypothetical configuration would look like:
[filter:analytics]
redis_host = 127.0.0.1
paste.filter_factory =... | @classmethod
def factory(cls, global_config, **local_config):
| def _factory(app):
conf = global_config.copy()
conf.update(local_config)
return cls(app)
return _factory
|
'Called on each request.
If this returns None, the next application down the stack will be
executed. If it returns a response then that response will be returned
and execution will stop here.'
| def process_request(self, request):
| return None
|
'Do whatever you\'d like to the response, based on the request.'
| def process_response(self, request, response):
| return response
|
'Iterator that prints the contents of a wrapper string.'
| @staticmethod
def print_generator(app_iter):
| LOG.debug('%s %s %s', ('*' * 20), 'RESPONSE BODY', ('*' * 20))
for part in app_iter:
LOG.debug(part)
(yield part)
|
'Create a router for the given routes.Mapper.
Each route in `mapper` must specify a \'controller\', which is a
WSGI app to call. You\'ll probably want to specify an \'action\' as
well and have your controller be an object that can route
the request to the action-specific method.
Examples:
mapper = routes.Mapper()
sc =... | def __init__(self, mapper):
| if CONF.debug:
logging.getLogger('routes.middleware').setLevel(logging.INFO)
self.map = mapper
self._router = routes.middleware.RoutesMiddleware(self._dispatch, self.map)
|
'Route the incoming request to a controller based on self.map.
If no match, return a 404.'
| @webob.dec.wsgify(RequestClass=Request)
def __call__(self, req):
| return self._router
|
'Dispatch the request to the appropriate controller.
Called by self._router after matching the incoming request to a route
and putting the information into req.environ. Either returns 404
or the routed WSGI app\'s response.'
| @staticmethod
@webob.dec.wsgify(RequestClass=Request)
def _dispatch(req):
| match = req.environ['wsgiorg.routing_args'][1]
if (not match):
return render_exception(exception.NotFound(_('The resource could not be found.')))
app = match['controller']
return app
|
'Add routes to given mapper.'
| def add_routes(self, mapper):
| pass
|
'Used for paste app factories in paste.deploy config files.
Any local configuration (that is, values under the [filter:APPNAME]
section of the paste config) will be passed into the `__init__` method
as kwargs.
A hypothetical configuration would look like:
[filter:analytics]
redis_host = 127.0.0.1
paste.filter_factory =... | @classmethod
def factory(cls, global_config, **local_config):
| def _factory(app):
conf = global_config.copy()
conf.update(local_config)
return cls(app)
return _factory
|
'Returns the model\'s attributes as a dictionary.
If include_extra_dict is True, \'extra\' attributes are literally
included in the resulting dictionary twice, for backwards-compatibility
with a broken implementation.'
| def to_dict(self, include_extra_dict=False):
| d = self.extra.copy()
for attr in self.__class__.attributes:
d[attr] = getattr(self, attr)
if include_extra_dict:
d['extra'] = self.extra.copy()
return d
|
'Make the model object behave like a dict.'
| def update(self, values):
| for (k, v) in values.iteritems():
setattr(self, k, v)
|
'Make the model object behave like a dict.
Includes attributes from joins.'
| def iteritems(self):
| return dict([(k, getattr(self, k)) for k in self])
|
'Return a SQLAlchemy session.'
| def get_session(self, autocommit=True, expire_on_commit=False):
| self._engine = (self._engine or self.get_engine())
self._sessionmaker = (self._sessionmaker or self.get_sessionmaker(self._engine))
return self._sessionmaker()
|
'Return a SQLAlchemy engine.
If allow_global_engine is True and an in-memory sqlite connection
string is provided by CONF, all backends will share a global sqlalchemy
engine.'
| def get_engine(self, allow_global_engine=True):
| def new_engine():
connection_dict = sql.engine.url.make_url(CONF.sql.connection)
engine_config = {'convert_unicode': True, 'echo': (CONF.debug and CONF.verbose), 'pool_recycle': CONF.sql.idle_timeout}
if ('sqlite' in connection_dict.drivername):
engine_config['poolclass'] = sqlal... |
'Return a SQLAlchemy sessionmaker using the given engine.'
| def get_sessionmaker(self, engine, autocommit=True, expire_on_commit=False):
| return sqlalchemy.orm.sessionmaker(bind=engine, autocommit=autocommit, expire_on_commit=expire_on_commit)
|
'Generate the contents of a catalog templates file.'
| def dump_catalog(self):
| self._export_legacy_db()
services_by_id = dict(((x['id'], x) for x in self._data['services']))
template = 'catalog.%(region)s.%(service_type)s.%(key)s = %(value)s'
o = []
for row in self._data['endpoint_templates']:
service = services_by_id[row['service_id']]
d = {'service_type... |
'Ensures the reference contains the specified attribute.'
| def _require_attribute(self, ref, attr):
| if ((ref.get(attr) is None) or (ref.get(attr) == '')):
msg = ('%s field is required and cannot be empty' % attr)
raise exception.ValidationError(message=msg)
|
'Fill in domain_id since v2 calls are not domain-aware.
This will overwrite any domain_id that was inadvertently
specified in the v2 call.'
| def _normalize_domain_id(self, context, ref):
| ref['domain_id'] = DEFAULT_DOMAIN_ID
return ref
|
'Remove domain_id since v2 calls are not domain-aware.'
| def _filter_domain_id(self, ref):
| ref.pop('domain_id', None)
return ref
|
'Paginates a list of references by page & per_page query strings.'
| @classmethod
def paginate(cls, context, refs):
| return refs
page = context['query_string'].get('page', 1)
per_page = context['query_string'].get('per_page', 30)
return refs[(per_page * (page - 1)):(per_page * page)]
|
'Filters a list of references by query string value.'
| @classmethod
def filter_by_attribute(cls, context, refs, attr):
| def _attr_match(ref_attr, val_attr):
"Matches attributes allowing for booleans as strings.\n\n We test explicitly for a value that defines it as 'False',\n which a... |
'Ensures the value matches the reference\'s ID, if any.'
| def _require_matching_id(self, value, ref):
| if (('id' in ref) and (ref['id'] != value)):
raise exception.ValidationError('Cannot change ID')
|
'Generates and assigns a unique identifer to a reference.'
| def _assign_unique_id(self, ref):
| ref = ref.copy()
ref['id'] = uuid.uuid4().hex
return ref
|
'Fill in domain_id if not specified in a v3 call.'
| def _normalize_domain_id(self, context, ref):
| if ('domain_id' not in ref):
if context['is_admin']:
ref['domain_id'] = DEFAULT_DOMAIN_ID
else:
try:
token_ref = self.token_api.get_token(context=context, token_id=context['token_id'])
except exception.TokenNotFound:
LOG.warning(_('... |
'Override v2 filter to let domain_id out for v3 calls.'
| def _filter_domain_id(self, ref):
| return ref
|
'Verify that a user is authorized to perform action.
For more information on a full implementation of this see:
`keystone.common.policy.enforce`.'
| def enforce(self, context, credentials, action, target):
| raise exception.NotImplemented()
|
'Store a policy blob.
:raises: keystone.exception.Conflict'
| def create_policy(self, policy_id, policy):
| raise exception.NotImplemented()
|
'List all policies.'
| def list_policies(self):
| raise exception.NotImplemented()
|
'Retrieve a specific policy blob.
:raises: keystone.exception.PolicyNotFound'
| def get_policy(self, policy_id):
| raise exception.NotImplemented()
|
'Update a policy blob.
:raises: keystone.exception.PolicyNotFound'
| def update_policy(self, policy_id, policy):
| raise exception.NotImplemented()
|
'Remove a policy blob.
:raises: keystone.exception.PolicyNotFound'
| def delete_policy(self, policy_id):
| raise exception.NotImplemented()
|
'Private method to get a policy model object (NOT a dictionary).'
| def _get_policy(self, session, policy_id):
| try:
return session.query(PolicyModel).filter_by(id=policy_id).one()
except sql.NotFound:
raise exception.PolicyNotFound(policy_id=policy_id)
|
'Transform the request from XML to JSON.'
| def process_request(self, request):
| incoming_xml = ('application/xml' in str(request.content_type))
if (incoming_xml and request.body):
request.content_type = 'application/json'
try:
request.body = jsonutils.dumps(serializer.from_xml(request.body))
except Exception:
LOG.exception('Serializer fail... |
'Transform the response from JSON to XML.'
| def process_response(self, request, response):
| outgoing_xml = ('application/xml' in str(request.accept))
if (outgoing_xml and response.body):
response.content_type = 'application/xml'
try:
body_obj = jsonutils.loads(response.body)
response.body = serializer.to_xml(body_obj)
except Exception:
LOG.ex... |
'Normalizes URLs.'
| def process_request(self, request):
| if ((len(request.environ['PATH_INFO']) > 1) and (request.environ['PATH_INFO'][(-1)] == '/')):
request.environ['PATH_INFO'] = request.environ['PATH_INFO'][:(-1)]
elif (not request.environ['PATH_INFO']):
request.environ['PATH_INFO'] = '/'
|
'Common initialization code.'
| def __init__(self, app, conf):
| self.app = app
self.logger = swift_utils.get_logger(conf, log_route='s3token')
self.logger.debug(('Starting the %s component' % PROTOCOL_NAME))
self.reseller_prefix = conf.get('reseller_prefix', 'AUTH_')
self.auth_host = conf.get('auth_host')
self.auth_port = int(conf.get('auth_port', 3... |
'Handle incoming request. authenticate and send downstream.'
| def __call__(self, environ, start_response):
| req = webob.Request(environ)
self.logger.debug('Calling S3Token middleware.')
try:
parts = swift_utils.split_path(req.path, 1, 4, True)
(version, account, container, obj) = parts
except ValueError:
msg = 'Not a path query, skipping.'
self.logger.debug(ms... |
'Get a token by id.
:param token_id: identity of the token
:type token_id: string
:returns: token_ref
:raises: keystone.exception.TokenNotFound'
| def get_token(self, token_id):
| raise exception.NotImplemented()
|
'Create a token by id and data.
:param token_id: identity of the token
:type token_id: string
:param data: dictionary with additional reference information
expires=\'\'
id=token_id,
user=user_ref,
tenant=tenant_ref,
metadata=metadata_ref
:type data: dict
:returns: token_ref or None.'
| def create_token(self, token_id, data):
| raise exception.NotImplemented()
|
'Deletes a token by id.
:param token_id: identity of the token
:type token_id: string
:returns: None.
:raises: keystone.exception.TokenNotFound'
| def delete_token(self, token_id):
| raise exception.NotImplemented()
|
'Returns a list of current token_id\'s for a user
:param user_id: identity of the user
:type user_id: string
:param tenant_id: identity of the tenant
:type tenant_id: string
:param trust_id: identified of the trust
:type trust_id: string
:returns: list of token_id\'s'
| def list_tokens(self, user_id, tenant_id=None, trust_id=None):
| raise exception.NotImplemented()
|
'Returns a list of all revoked tokens
:returns: list of token_id\'s'
| def list_revoked_tokens(self):
| raise exception.NotImplemented()
|
'Authenticate credentials and return a token.
Accept auth as a dict that looks like::
"auth":{
"passwordCredentials":{
"username":"test_user",
"password":"mypass"
"tenantName":"customer-x"
In this case, tenant is optional, if not provided the token will be
considered "unscoped" and can later be used to get a scoped tok... | def authenticate(self, context, auth=None):
| if (auth is None):
raise exception.ValidationError(attribute='auth', target='request body')
auth_token_data = None
if ('token' in auth):
auth_info = self._authenticate_token(context, auth)
else:
try:
auth_info = self._authenticate_external(context, auth)
ex... |
'Try to authenticate using an already existing token.
Returns auth_token_data, (user_ref, tenant_ref, metadata_ref)'
| def _authenticate_token(self, context, auth):
| if ('token' not in auth):
raise exception.ValidationError(attribute='token', target='auth')
if ('id' not in auth['token']):
raise exception.ValidationError(attribute='id', target='token')
old_token = auth['token']['id']
if (len(old_token) > CONF.max_token_size):
raise exception.V... |
'Try to authenticate against the identity backend.
Returns auth_token_data, (user_ref, tenant_ref, metadata_ref)'
| def _authenticate_local(self, context, auth):
| if ('passwordCredentials' not in auth):
raise exception.ValidationError(attribute='passwordCredentials', target='auth')
if ('password' not in auth['passwordCredentials']):
raise exception.ValidationError(attribute='password', target='passwordCredentials')
password = auth['passwordCredentials... |
'Try to authenticate an external user via REMOTE_USER variable.
Returns auth_token_data, (user_ref, tenant_ref, metadata_ref)'
| def _authenticate_external(self, context, auth):
| if ('REMOTE_USER' not in context):
raise ExternalAuthNotApplicable()
username = context['REMOTE_USER']
try:
user_ref = self.identity_api.get_user_by_name(context=context, user_name=username, domain_id=DEFAULT_DOMAIN_ID)
user_id = user_ref['id']
except exception.UserNotFound as e:... |
'Extract tenant information from auth dict.
Returns a valid tenant_id if it exists, or None if not specified.'
| def _get_project_id_from_auth(self, context, auth):
| tenant_id = auth.get('tenantId', None)
if (tenant_id and (len(tenant_id) > CONF.max_param_size)):
raise exception.ValidationSizeError(attribute='tenantId', size=CONF.max_param_size)
tenant_name = auth.get('tenantName', None)
if (tenant_name and (len(tenant_name) > CONF.max_param_size)):
... |
'Extract domain information from v3 auth dict.
Returns a valid domain_id if it exists, or None if not specified.'
| def _get_domain_id_from_auth(self, context, auth):
| domain_id = auth.get('domainId', None)
domain_name = auth.get('domainName', None)
if domain_name:
try:
domain_ref = self.identity_api._get_domain_by_name(context=context, domain_name=domain_name)
domain_id = domain_ref['id']
except exception.DomainNotFound as e:
... |
'Returns the tenant_ref for the user\'s tenant'
| def _get_project_ref(self, context, user_id, tenant_id):
| tenant_ref = None
if tenant_id:
tenants = self.identity_api.get_projects_for_user(context, user_id)
if (tenant_id not in tenants):
msg = ('User %s is unauthorized for tenant %s' % (user_id, tenant_id))
LOG.warning(msg)
raise exception.Unautho... |
'Returns metadata_ref for a user or group in a tenant or domain'
| def _get_metadata_ref(self, context, user_id=None, tenant_id=None, domain_id=None, group_id=None):
| metadata_ref = {}
if ((user_id or group_id) and (tenant_id or domain_id)):
try:
metadata_ref = self.identity_api.get_metadata(context=context, user_id=user_id, tenant_id=tenant_id, domain_id=domain_id, group_id=group_id)
except exception.MetadataNotFound:
pass
return ... |
'Return any metadata for this project/domain due to group grants'
| def _get_group_metadata_ref(self, context, user_id, tenant_id=None, domain_id=None):
| group_refs = self.identity_api.list_groups_for_user(context=context, user_id=user_id)
metadata_ref = {}
for x in group_refs:
metadata_ref.update(self._get_metadata_ref(context, group_id=x['id'], tenant_id=tenant_id, domain_id=domain_id))
return metadata_ref
|
'Update the roles in metadata to be the union of the roles from
both of the passed metadatas'
| def _append_roles(self, metadata, additional_metadata):
| first = set(metadata.get('roles', []))
second = set(additional_metadata.get('roles', []))
metadata['roles'] = list(first.union(second))
|
'Returns a token if a valid one exists.
Optionally, limited to a token owned by a specific tenant.'
| def _get_token_ref(self, context, token_id, belongs_to=None):
| self.assert_admin(context)
data = self.token_api.get_token(context=context, token_id=token_id)
if belongs_to:
if (data.get('tenant') is None):
raise exception.Unauthorized(_('Token does not belong to specified tenant.'))
if (data['tenant'].get('id') != belongs_t... |
'Make sure we are operating on default domain only.'
| def _assert_default_domain(self, context, token_ref):
| if token_ref.get('token_data'):
msg = _('Non-default domain is not supported')
if (token_ref['token_data']['token']['user']['domain']['id'] != DEFAULT_DOMAIN_ID):
raise exception.Unauthorized(msg)
if token_ref['token_data']['token'].get('domain'):
raise ex... |
'Check that a token is valid.
Optionally, also ensure that it is owned by a specific tenant.
Identical to ``validate_token``, except does not return a response.'
| def validate_token_head(self, context, token_id):
| belongs_to = context['query_string'].get('belongsTo')
token_ref = self._get_token_ref(context, token_id, belongs_to)
assert token_ref
self._assert_default_domain(context, token_ref)
|
'Check that a token is valid.
Optionally, also ensure that it is owned by a specific tenant.
Returns metadata about the token along any associated roles.'
| def validate_token(self, context, token_id):
| belongs_to = context['query_string'].get('belongsTo')
token_ref = self._get_token_ref(context, token_id, belongs_to)
self._assert_default_domain(context, token_ref)
metadata_ref = token_ref['metadata']
roles_ref = []
for role_id in metadata_ref.get('roles', []):
roles_ref.append(self.ide... |
'Delete a token, effectively invalidating it for authz.'
| def delete_token(self, context, token_id):
| self.assert_admin(context)
self.token_api.delete_token(context=context, token_id=token_id)
|
'Return a list of endpoints available to the token.'
| def endpoints(self, context, token_id):
| self.assert_admin(context)
token_ref = self._get_token_ref(context, token_id)
catalog_ref = None
if token_ref.get('tenant'):
catalog_ref = self.catalog_api.get_catalog(context=context, user_id=token_ref['user']['id'], tenant_id=token_ref['tenant']['id'], metadata=token_ref['metadata'])
retur... |
'Munge catalogs from internal to output format
Internal catalogs look like:
{$REGION: {
{$SERVICE: {
$key1: $value1,
The legacy api wants them to look like
[{\'name\': $SERVICE[name],
\'type\': $SERVICE,
\'endpoints\': [{
\'tenantId\': $tenant_id,
\'region\': $REGION,
\'endpoints_links\': [],'
| @classmethod
def format_catalog(cls, catalog_ref):
| if (not catalog_ref):
return []
services = {}
for (region, region_ref) in catalog_ref.iteritems():
for (service, service_ref) in region_ref.iteritems():
new_service_ref = services.get(service, {})
new_service_ref['name'] = service_ref.pop('name')
new_servi... |
'Formats a list of endpoints according to Identity API v2.
The v2.0 API wants an endpoint list to look like::
\'endpoints\': [
\'id\': $endpoint_id,
\'name\': $SERVICE[name],
\'type\': $SERVICE,
\'tenantId\': $tenant_id,
\'region\': $REGION,
\'endpoints_links\': [],'
| @classmethod
def format_endpoint_list(cls, catalog_ref):
| if (not catalog_ref):
return {}
endpoints = []
for (region_name, region_ref) in catalog_ref.iteritems():
for (service_type, service_ref) in region_ref.iteritems():
endpoints.append({'id': service_ref.get('id'), 'name': service_ref.get('name'), 'type': service_type, 'region': regi... |
'Create a new trust.
:returns: a new trust'
| def create_trust(self, trust_id, trust, roles):
| raise exception.NotImplemented()
|
'The user creating the trust must be trustor'
| @controller.protected
def create_trust(self, context, trust=None):
| if (not trust):
raise exception.ValidationError(attribute='trust', target='request')
try:
user_id = self._get_user_id(context)
_trustor_only(context, trust, user_id)
trustee_ref = self.identity_api.get_user(context, trust['trustee_user_id'])
if (not trustee_ref):
... |
'Checks if a role has been assigned to a trust.'
| @controller.protected
def check_role_for_trust(self, context, trust_id, role_id):
| trust = self.trust_api.get_trust(context, trust_id)
if (not trust):
raise exception.TrustNotFound(trust_id)
user_id = self._get_user_id(context)
_admin_trustor_trustee_only(context, trust, user_id)
matching_roles = [x for x in trust['roles'] if (x['id'] == role_id)]
if (not matching_role... |
'Checks if a role has been assigned to a trust.'
| @controller.protected
def get_role_for_trust(self, context, trust_id, role_id):
| trust = self.trust_api.get_trust(context, trust_id)
if (not trust):
raise exception.TrustNotFound(trust_id)
user_id = self._get_user_id(context)
_admin_trustor_trustee_only(context, trust, user_id)
matching_roles = [x for x in trust['roles'] if (x['id'] == role_id)]
if (not matching_role... |
'Returns a URL to keystone\'s own endpoint.'
| def _get_identity_url(self, version='v2.0'):
| url = (CONF[('%s_endpoint' % self.endpoint_url_type)] % CONF)
if (url[(-1)] != '/'):
url += '/'
return ('%s%s/' % (url, version))
|
'The list of versions is dependent on the context.'
| def _get_versions_list(self, context):
| versions = {}
versions['v2.0'] = {'id': 'v2.0', 'status': 'stable', 'updated': '2013-03-06T00:00:00Z', 'links': [{'rel': 'self', 'href': self._get_identity_url(version='v2.0')}, {'rel': 'describedby', 'type': 'text/html', 'href': 'http://docs.openstack.org/api/openstack-identity-service/2.0/content/'}, {'rel': ... |
'Allow loading of JSON rule data.'
| @classmethod
def load_json(cls, data, default_rule=None):
| rules = dict(((k, parse_rule(v)) for (k, v) in jsonutils.loads(data).items()))
return cls(rules, default_rule)
|
'Initialize the Rules store.'
| def __init__(self, rules=None, default_rule=None):
| super(Rules, self).__init__((rules or {}))
self.default_rule = default_rule
|
'Implements the default rule handling.'
| def __missing__(self, key):
| if ((not self.default_rule) or (self.default_rule not in self)):
raise KeyError(key)
return self[self.default_rule]
|
'Dumps a string representation of the rules.'
| def __str__(self):
| out_rules = {}
for (key, value) in self.items():
if isinstance(value, TrueCheck):
out_rules[key] = ''
else:
out_rules[key] = str(value)
return jsonutils.dumps(out_rules, indent=4)
|
'Retrieve a string representation of the Check tree rooted at
this node.'
| @abc.abstractmethod
def __str__(self):
| pass
|
'Perform the check. Returns False to reject the access or a
true value (not necessary True) to accept the access.'
| @abc.abstractmethod
def __call__(self, target, cred):
| pass
|
'Return a string representation of this check.'
| def __str__(self):
| return '!'
|
'Check the policy.'
| def __call__(self, target, cred):
| return False
|
'Return a string representation of this check.'
| def __str__(self):
| return '@'
|
'Check the policy.'
| def __call__(self, target, cred):
| return True
|
':param kind: The kind of the check, i.e., the field before the
:param match: The match of the check, i.e., the field after
the \':\'.'
| def __init__(self, kind, match):
| self.kind = kind
self.match = match
|
'Return a string representation of this check.'
| def __str__(self):
| return ('%s:%s' % (self.kind, self.match))
|
'Initialize the \'not\' check.
:param rule: The rule to negate. Must be a Check.'
| def __init__(self, rule):
| self.rule = rule
|
'Return a string representation of this check.'
| def __str__(self):
| return ('not %s' % self.rule)
|
'Check the policy. Returns the logical inverse of the wrapped
check.'
| def __call__(self, target, cred):
| return (not self.rule(target, cred))
|
'Initialize the \'and\' check.
:param rules: A list of rules that will be tested.'
| def __init__(self, rules):
| self.rules = rules
|
'Return a string representation of this check.'
| def __str__(self):
| return ('(%s)' % ' and '.join((str(r) for r in self.rules)))
|
'Check the policy. Requires that all rules accept in order to
return True.'
| def __call__(self, target, cred):
| for rule in self.rules:
if (not rule(target, cred)):
return False
return True
|
'Allows addition of another rule to the list of rules that will
be tested. Returns the AndCheck object for convenience.'
| def add_check(self, rule):
| self.rules.append(rule)
return self
|
'Initialize the \'or\' check.
:param rules: A list of rules that will be tested.'
| def __init__(self, rules):
| self.rules = rules
|
'Return a string representation of this check.'
| def __str__(self):
| return ('(%s)' % ' or '.join((str(r) for r in self.rules)))
|
'Check the policy. Requires that at least one rule accept in
order to return True.'
| def __call__(self, target, cred):
| for rule in self.rules:
if rule(target, cred):
return True
return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.