id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
237,000
|
IdentityPython/SATOSA
|
src/satosa/frontends/saml2.py
|
SAMLVirtualCoFrontend._overlay_for_saml_metadata
|
def _overlay_for_saml_metadata(self, config, co_name):
"""
Overlay configuration details like organization and contact person
from the front end configuration onto the IdP configuration to
support SAML metadata generation.
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated details for SAML metadata
"""
for co in self.config[self.KEY_CO]:
if co[self.KEY_ENCODEABLE_NAME] == co_name:
break
key = self.KEY_ORGANIZATION
if key in co:
if key not in config:
config[key] = {}
for org_key in self.KEY_ORGANIZATION_KEYS:
if org_key in co[key]:
config[key][org_key] = co[key][org_key]
key = self.KEY_CONTACT_PERSON
if key in co:
config[key] = co[key]
return config
|
python
|
def _overlay_for_saml_metadata(self, config, co_name):
"""
Overlay configuration details like organization and contact person
from the front end configuration onto the IdP configuration to
support SAML metadata generation.
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated details for SAML metadata
"""
for co in self.config[self.KEY_CO]:
if co[self.KEY_ENCODEABLE_NAME] == co_name:
break
key = self.KEY_ORGANIZATION
if key in co:
if key not in config:
config[key] = {}
for org_key in self.KEY_ORGANIZATION_KEYS:
if org_key in co[key]:
config[key][org_key] = co[key][org_key]
key = self.KEY_CONTACT_PERSON
if key in co:
config[key] = co[key]
return config
|
[
"def",
"_overlay_for_saml_metadata",
"(",
"self",
",",
"config",
",",
"co_name",
")",
":",
"for",
"co",
"in",
"self",
".",
"config",
"[",
"self",
".",
"KEY_CO",
"]",
":",
"if",
"co",
"[",
"self",
".",
"KEY_ENCODEABLE_NAME",
"]",
"==",
"co_name",
":",
"break",
"key",
"=",
"self",
".",
"KEY_ORGANIZATION",
"if",
"key",
"in",
"co",
":",
"if",
"key",
"not",
"in",
"config",
":",
"config",
"[",
"key",
"]",
"=",
"{",
"}",
"for",
"org_key",
"in",
"self",
".",
"KEY_ORGANIZATION_KEYS",
":",
"if",
"org_key",
"in",
"co",
"[",
"key",
"]",
":",
"config",
"[",
"key",
"]",
"[",
"org_key",
"]",
"=",
"co",
"[",
"key",
"]",
"[",
"org_key",
"]",
"key",
"=",
"self",
".",
"KEY_CONTACT_PERSON",
"if",
"key",
"in",
"co",
":",
"config",
"[",
"key",
"]",
"=",
"co",
"[",
"key",
"]",
"return",
"config"
] |
Overlay configuration details like organization and contact person
from the front end configuration onto the IdP configuration to
support SAML metadata generation.
:type config: satosa.satosa_config.SATOSAConfig
:type co_name: str
:rtype: satosa.satosa_config.SATOSAConfig
:param config: satosa proxy config
:param co_name: CO name
:return: config with updated details for SAML metadata
|
[
"Overlay",
"configuration",
"details",
"like",
"organization",
"and",
"contact",
"person",
"from",
"the",
"front",
"end",
"configuration",
"onto",
"the",
"IdP",
"configuration",
"to",
"support",
"SAML",
"metadata",
"generation",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L854-L885
|
237,001
|
IdentityPython/SATOSA
|
src/satosa/frontends/saml2.py
|
SAMLVirtualCoFrontend._co_names_from_config
|
def _co_names_from_config(self):
"""
Parse the configuration for the names of the COs for which to
construct virtual IdPs.
:rtype: [str]
:return: list of CO names
"""
co_names = [co[self.KEY_ENCODEABLE_NAME] for
co in self.config[self.KEY_CO]]
return co_names
|
python
|
def _co_names_from_config(self):
"""
Parse the configuration for the names of the COs for which to
construct virtual IdPs.
:rtype: [str]
:return: list of CO names
"""
co_names = [co[self.KEY_ENCODEABLE_NAME] for
co in self.config[self.KEY_CO]]
return co_names
|
[
"def",
"_co_names_from_config",
"(",
"self",
")",
":",
"co_names",
"=",
"[",
"co",
"[",
"self",
".",
"KEY_ENCODEABLE_NAME",
"]",
"for",
"co",
"in",
"self",
".",
"config",
"[",
"self",
".",
"KEY_CO",
"]",
"]",
"return",
"co_names"
] |
Parse the configuration for the names of the COs for which to
construct virtual IdPs.
:rtype: [str]
:return: list of CO names
|
[
"Parse",
"the",
"configuration",
"for",
"the",
"names",
"of",
"the",
"COs",
"for",
"which",
"to",
"construct",
"virtual",
"IdPs",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L887-L899
|
237,002
|
IdentityPython/SATOSA
|
src/satosa/frontends/saml2.py
|
SAMLVirtualCoFrontend._create_co_virtual_idp
|
def _create_co_virtual_idp(self, context):
"""
Create a virtual IdP to represent the CO.
:type context: The current context
:rtype: saml.server.Server
:param context:
:return: An idp server
"""
co_name = self._get_co_name(context)
context.decorate(self.KEY_CO_NAME, co_name)
# Verify that we are configured for this CO. If the CO was not
# configured most likely the endpoint used was not registered and
# SATOSA core code threw an exception before getting here, but we
# include this check in case later the regex used to register the
# endpoints is relaxed.
co_names = self._co_names_from_config()
if co_name not in co_names:
msg = "CO {} not in configured list of COs {}".format(co_name,
co_names)
satosa_logging(logger, logging.WARN, msg, context.state)
raise SATOSAError(msg)
# Make a copy of the general IdP config that we will then overwrite
# with mappings between SAML bindings and CO specific URL endpoints,
# and the entityID for the CO virtual IdP.
backend_name = context.target_backend
idp_config = copy.deepcopy(self.idp_config)
idp_config = self._add_endpoints_to_config(idp_config,
co_name,
backend_name)
idp_config = self._add_entity_id(idp_config, co_name)
# Use the overwritten IdP config to generate a pysaml2 config object
# and from it a server object.
pysaml2_idp_config = IdPConfig().load(idp_config,
metadata_construction=False)
server = Server(config=pysaml2_idp_config)
return server
|
python
|
def _create_co_virtual_idp(self, context):
"""
Create a virtual IdP to represent the CO.
:type context: The current context
:rtype: saml.server.Server
:param context:
:return: An idp server
"""
co_name = self._get_co_name(context)
context.decorate(self.KEY_CO_NAME, co_name)
# Verify that we are configured for this CO. If the CO was not
# configured most likely the endpoint used was not registered and
# SATOSA core code threw an exception before getting here, but we
# include this check in case later the regex used to register the
# endpoints is relaxed.
co_names = self._co_names_from_config()
if co_name not in co_names:
msg = "CO {} not in configured list of COs {}".format(co_name,
co_names)
satosa_logging(logger, logging.WARN, msg, context.state)
raise SATOSAError(msg)
# Make a copy of the general IdP config that we will then overwrite
# with mappings between SAML bindings and CO specific URL endpoints,
# and the entityID for the CO virtual IdP.
backend_name = context.target_backend
idp_config = copy.deepcopy(self.idp_config)
idp_config = self._add_endpoints_to_config(idp_config,
co_name,
backend_name)
idp_config = self._add_entity_id(idp_config, co_name)
# Use the overwritten IdP config to generate a pysaml2 config object
# and from it a server object.
pysaml2_idp_config = IdPConfig().load(idp_config,
metadata_construction=False)
server = Server(config=pysaml2_idp_config)
return server
|
[
"def",
"_create_co_virtual_idp",
"(",
"self",
",",
"context",
")",
":",
"co_name",
"=",
"self",
".",
"_get_co_name",
"(",
"context",
")",
"context",
".",
"decorate",
"(",
"self",
".",
"KEY_CO_NAME",
",",
"co_name",
")",
"# Verify that we are configured for this CO. If the CO was not",
"# configured most likely the endpoint used was not registered and",
"# SATOSA core code threw an exception before getting here, but we",
"# include this check in case later the regex used to register the",
"# endpoints is relaxed.",
"co_names",
"=",
"self",
".",
"_co_names_from_config",
"(",
")",
"if",
"co_name",
"not",
"in",
"co_names",
":",
"msg",
"=",
"\"CO {} not in configured list of COs {}\"",
".",
"format",
"(",
"co_name",
",",
"co_names",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARN",
",",
"msg",
",",
"context",
".",
"state",
")",
"raise",
"SATOSAError",
"(",
"msg",
")",
"# Make a copy of the general IdP config that we will then overwrite",
"# with mappings between SAML bindings and CO specific URL endpoints,",
"# and the entityID for the CO virtual IdP.",
"backend_name",
"=",
"context",
".",
"target_backend",
"idp_config",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"idp_config",
")",
"idp_config",
"=",
"self",
".",
"_add_endpoints_to_config",
"(",
"idp_config",
",",
"co_name",
",",
"backend_name",
")",
"idp_config",
"=",
"self",
".",
"_add_entity_id",
"(",
"idp_config",
",",
"co_name",
")",
"# Use the overwritten IdP config to generate a pysaml2 config object",
"# and from it a server object.",
"pysaml2_idp_config",
"=",
"IdPConfig",
"(",
")",
".",
"load",
"(",
"idp_config",
",",
"metadata_construction",
"=",
"False",
")",
"server",
"=",
"Server",
"(",
"config",
"=",
"pysaml2_idp_config",
")",
"return",
"server"
] |
Create a virtual IdP to represent the CO.
:type context: The current context
:rtype: saml.server.Server
:param context:
:return: An idp server
|
[
"Create",
"a",
"virtual",
"IdP",
"to",
"represent",
"the",
"CO",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/frontends/saml2.py#L901-L943
|
237,003
|
IdentityPython/SATOSA
|
src/satosa/backends/oauth.py
|
_OAuthBackend._authn_response
|
def _authn_response(self, context):
"""
Handles the authentication response from the AS.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The context in SATOSA
:return: A SATOSA response. This method is only responsible to call the callback function
which generates the Response object.
"""
state_data = context.state[self.name]
aresp = self.consumer.parse_response(AuthorizationResponse, info=json.dumps(context.request))
self._verify_state(aresp, state_data, context.state)
rargs = {"code": aresp["code"], "redirect_uri": self.redirect_url,
"state": state_data["state"]}
atresp = self.consumer.do_access_token_request(request_args=rargs, state=aresp["state"])
if "verify_accesstoken_state" not in self.config or self.config["verify_accesstoken_state"]:
self._verify_state(atresp, state_data, context.state)
user_info = self.user_information(atresp["access_token"])
internal_response = InternalData(auth_info=self.auth_info(context.request))
internal_response.attributes = self.converter.to_internal(self.external_type, user_info)
internal_response.subject_id = user_info[self.user_id_attr]
del context.state[self.name]
return self.auth_callback_func(context, internal_response)
|
python
|
def _authn_response(self, context):
"""
Handles the authentication response from the AS.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The context in SATOSA
:return: A SATOSA response. This method is only responsible to call the callback function
which generates the Response object.
"""
state_data = context.state[self.name]
aresp = self.consumer.parse_response(AuthorizationResponse, info=json.dumps(context.request))
self._verify_state(aresp, state_data, context.state)
rargs = {"code": aresp["code"], "redirect_uri": self.redirect_url,
"state": state_data["state"]}
atresp = self.consumer.do_access_token_request(request_args=rargs, state=aresp["state"])
if "verify_accesstoken_state" not in self.config or self.config["verify_accesstoken_state"]:
self._verify_state(atresp, state_data, context.state)
user_info = self.user_information(atresp["access_token"])
internal_response = InternalData(auth_info=self.auth_info(context.request))
internal_response.attributes = self.converter.to_internal(self.external_type, user_info)
internal_response.subject_id = user_info[self.user_id_attr]
del context.state[self.name]
return self.auth_callback_func(context, internal_response)
|
[
"def",
"_authn_response",
"(",
"self",
",",
"context",
")",
":",
"state_data",
"=",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"aresp",
"=",
"self",
".",
"consumer",
".",
"parse_response",
"(",
"AuthorizationResponse",
",",
"info",
"=",
"json",
".",
"dumps",
"(",
"context",
".",
"request",
")",
")",
"self",
".",
"_verify_state",
"(",
"aresp",
",",
"state_data",
",",
"context",
".",
"state",
")",
"rargs",
"=",
"{",
"\"code\"",
":",
"aresp",
"[",
"\"code\"",
"]",
",",
"\"redirect_uri\"",
":",
"self",
".",
"redirect_url",
",",
"\"state\"",
":",
"state_data",
"[",
"\"state\"",
"]",
"}",
"atresp",
"=",
"self",
".",
"consumer",
".",
"do_access_token_request",
"(",
"request_args",
"=",
"rargs",
",",
"state",
"=",
"aresp",
"[",
"\"state\"",
"]",
")",
"if",
"\"verify_accesstoken_state\"",
"not",
"in",
"self",
".",
"config",
"or",
"self",
".",
"config",
"[",
"\"verify_accesstoken_state\"",
"]",
":",
"self",
".",
"_verify_state",
"(",
"atresp",
",",
"state_data",
",",
"context",
".",
"state",
")",
"user_info",
"=",
"self",
".",
"user_information",
"(",
"atresp",
"[",
"\"access_token\"",
"]",
")",
"internal_response",
"=",
"InternalData",
"(",
"auth_info",
"=",
"self",
".",
"auth_info",
"(",
"context",
".",
"request",
")",
")",
"internal_response",
".",
"attributes",
"=",
"self",
".",
"converter",
".",
"to_internal",
"(",
"self",
".",
"external_type",
",",
"user_info",
")",
"internal_response",
".",
"subject_id",
"=",
"user_info",
"[",
"self",
".",
"user_id_attr",
"]",
"del",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"return",
"self",
".",
"auth_callback_func",
"(",
"context",
",",
"internal_response",
")"
] |
Handles the authentication response from the AS.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The context in SATOSA
:return: A SATOSA response. This method is only responsible to call the callback function
which generates the Response object.
|
[
"Handles",
"the",
"authentication",
"response",
"from",
"the",
"AS",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/oauth.py#L117-L143
|
237,004
|
IdentityPython/SATOSA
|
src/satosa/util.py
|
hash_data
|
def hash_data(salt, value, hash_alg=None):
"""
Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to hash together with the salt
:return: hashed value
"""
hash_alg = hash_alg or 'sha512'
hasher = hashlib.new(hash_alg)
hasher.update(value.encode('utf-8'))
hasher.update(salt.encode('utf-8'))
value_hashed = hasher.hexdigest()
return value_hashed
|
python
|
def hash_data(salt, value, hash_alg=None):
"""
Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to hash together with the salt
:return: hashed value
"""
hash_alg = hash_alg or 'sha512'
hasher = hashlib.new(hash_alg)
hasher.update(value.encode('utf-8'))
hasher.update(salt.encode('utf-8'))
value_hashed = hasher.hexdigest()
return value_hashed
|
[
"def",
"hash_data",
"(",
"salt",
",",
"value",
",",
"hash_alg",
"=",
"None",
")",
":",
"hash_alg",
"=",
"hash_alg",
"or",
"'sha512'",
"hasher",
"=",
"hashlib",
".",
"new",
"(",
"hash_alg",
")",
"hasher",
".",
"update",
"(",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"hasher",
".",
"update",
"(",
"salt",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"value_hashed",
"=",
"hasher",
".",
"hexdigest",
"(",
")",
"return",
"value_hashed"
] |
Hashes a value together with a salt with the given hash algorithm.
:type salt: str
:type hash_alg: str
:type value: str
:param salt: hash salt
:param hash_alg: the hash algorithm to use (default: SHA512)
:param value: value to hash together with the salt
:return: hashed value
|
[
"Hashes",
"a",
"value",
"together",
"with",
"a",
"salt",
"with",
"the",
"given",
"hash",
"algorithm",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/util.py#L15-L32
|
237,005
|
IdentityPython/SATOSA
|
src/satosa/micro_services/ldap_attribute_store.py
|
LdapAttributeStore._construct_filter_value
|
def _construct_filter_value(self, candidate, data):
"""
Construct and return a LDAP directory search filter value from the
candidate identifier.
Argument 'canidate' is a dictionary with one required key and
two optional keys:
key required value
--------------- -------- ---------------------------------
attribute_names Y list of identifier names
name_id_format N NameID format (string)
add_scope N "issuer_entityid" or other string
Argument 'data' is that object passed into the microservice
method process().
If the attribute_names list consists of more than one identifier
name then the values of the identifiers will be concatenated together
to create the filter value.
If one of the identifier names in the attribute_names is the string
'name_id' then the NameID value with format name_id_format
will be concatenated to the filter value.
If the add_scope key is present with value 'issuer_entityid' then the
entityID for the IdP will be concatenated to "scope" the value. If the
string is any other value it will be directly concatenated.
"""
context = self.context
attributes = data.attributes
satosa_logging(logger, logging.DEBUG, "Input attributes {}".format(attributes), context.state)
# Get the values configured list of identifier names for this candidate
# and substitute None if there are no values for a configured identifier.
values = []
for identifier_name in candidate['attribute_names']:
v = attributes.get(identifier_name, None)
if isinstance(v, list):
v = v[0]
values.append(v)
satosa_logging(logger, logging.DEBUG, "Found candidate values {}".format(values), context.state)
# If one of the configured identifier names is name_id then if there is also a configured
# name_id_format add the value for the NameID of that format if it was asserted by the IdP
# or else add the value None.
if 'name_id' in candidate['attribute_names']:
candidate_nameid_value = None
candidate_name_id_format = candidate.get('name_id_format')
name_id_value = data.subject_id
name_id_format = data.subject_type
if (
name_id_value
and candidate_name_id_format
and candidate_name_id_format == name_id_format
):
satosa_logging(logger, logging.DEBUG, "IdP asserted NameID {}".format(name_id_value), context.state)
candidate_nameid_value = name_id_value
# Only add the NameID value asserted by the IdP if it is not already
# in the list of values. This is necessary because some non-compliant IdPs
# have been known, for example, to assert the value of eduPersonPrincipalName
# in the value for SAML2 persistent NameID as well as asserting
# eduPersonPrincipalName.
if candidate_nameid_value not in values:
satosa_logging(logger, logging.DEBUG, "Added NameID {} to candidate values".format(candidate_nameid_value), context.state)
values.append(candidate_nameid_value)
else:
satosa_logging(logger, logging.WARN, "NameID {} value also asserted as attribute value".format(candidate_nameid_value), context.state)
# If no value was asserted by the IdP for one of the configured list of identifier names
# for this candidate then go onto the next candidate.
if None in values:
satosa_logging(logger, logging.DEBUG, "Candidate is missing value so skipping", context.state)
return None
# All values for the configured list of attribute names are present
# so we can create a value. Add a scope if configured
# to do so.
if 'add_scope' in candidate:
if candidate['add_scope'] == 'issuer_entityid':
scope = data.auth_info.issuer
else:
scope = candidate['add_scope']
satosa_logging(logger, logging.DEBUG, "Added scope {} to values".format(scope), context.state)
values.append(scope)
# Concatenate all values to create the filter value.
value = ''.join(values)
satosa_logging(logger, logging.DEBUG, "Constructed filter value {}".format(value), context.state)
return value
|
python
|
def _construct_filter_value(self, candidate, data):
"""
Construct and return a LDAP directory search filter value from the
candidate identifier.
Argument 'canidate' is a dictionary with one required key and
two optional keys:
key required value
--------------- -------- ---------------------------------
attribute_names Y list of identifier names
name_id_format N NameID format (string)
add_scope N "issuer_entityid" or other string
Argument 'data' is that object passed into the microservice
method process().
If the attribute_names list consists of more than one identifier
name then the values of the identifiers will be concatenated together
to create the filter value.
If one of the identifier names in the attribute_names is the string
'name_id' then the NameID value with format name_id_format
will be concatenated to the filter value.
If the add_scope key is present with value 'issuer_entityid' then the
entityID for the IdP will be concatenated to "scope" the value. If the
string is any other value it will be directly concatenated.
"""
context = self.context
attributes = data.attributes
satosa_logging(logger, logging.DEBUG, "Input attributes {}".format(attributes), context.state)
# Get the values configured list of identifier names for this candidate
# and substitute None if there are no values for a configured identifier.
values = []
for identifier_name in candidate['attribute_names']:
v = attributes.get(identifier_name, None)
if isinstance(v, list):
v = v[0]
values.append(v)
satosa_logging(logger, logging.DEBUG, "Found candidate values {}".format(values), context.state)
# If one of the configured identifier names is name_id then if there is also a configured
# name_id_format add the value for the NameID of that format if it was asserted by the IdP
# or else add the value None.
if 'name_id' in candidate['attribute_names']:
candidate_nameid_value = None
candidate_name_id_format = candidate.get('name_id_format')
name_id_value = data.subject_id
name_id_format = data.subject_type
if (
name_id_value
and candidate_name_id_format
and candidate_name_id_format == name_id_format
):
satosa_logging(logger, logging.DEBUG, "IdP asserted NameID {}".format(name_id_value), context.state)
candidate_nameid_value = name_id_value
# Only add the NameID value asserted by the IdP if it is not already
# in the list of values. This is necessary because some non-compliant IdPs
# have been known, for example, to assert the value of eduPersonPrincipalName
# in the value for SAML2 persistent NameID as well as asserting
# eduPersonPrincipalName.
if candidate_nameid_value not in values:
satosa_logging(logger, logging.DEBUG, "Added NameID {} to candidate values".format(candidate_nameid_value), context.state)
values.append(candidate_nameid_value)
else:
satosa_logging(logger, logging.WARN, "NameID {} value also asserted as attribute value".format(candidate_nameid_value), context.state)
# If no value was asserted by the IdP for one of the configured list of identifier names
# for this candidate then go onto the next candidate.
if None in values:
satosa_logging(logger, logging.DEBUG, "Candidate is missing value so skipping", context.state)
return None
# All values for the configured list of attribute names are present
# so we can create a value. Add a scope if configured
# to do so.
if 'add_scope' in candidate:
if candidate['add_scope'] == 'issuer_entityid':
scope = data.auth_info.issuer
else:
scope = candidate['add_scope']
satosa_logging(logger, logging.DEBUG, "Added scope {} to values".format(scope), context.state)
values.append(scope)
# Concatenate all values to create the filter value.
value = ''.join(values)
satosa_logging(logger, logging.DEBUG, "Constructed filter value {}".format(value), context.state)
return value
|
[
"def",
"_construct_filter_value",
"(",
"self",
",",
"candidate",
",",
"data",
")",
":",
"context",
"=",
"self",
".",
"context",
"attributes",
"=",
"data",
".",
"attributes",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Input attributes {}\"",
".",
"format",
"(",
"attributes",
")",
",",
"context",
".",
"state",
")",
"# Get the values configured list of identifier names for this candidate",
"# and substitute None if there are no values for a configured identifier.",
"values",
"=",
"[",
"]",
"for",
"identifier_name",
"in",
"candidate",
"[",
"'attribute_names'",
"]",
":",
"v",
"=",
"attributes",
".",
"get",
"(",
"identifier_name",
",",
"None",
")",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"v",
"=",
"v",
"[",
"0",
"]",
"values",
".",
"append",
"(",
"v",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Found candidate values {}\"",
".",
"format",
"(",
"values",
")",
",",
"context",
".",
"state",
")",
"# If one of the configured identifier names is name_id then if there is also a configured",
"# name_id_format add the value for the NameID of that format if it was asserted by the IdP",
"# or else add the value None.",
"if",
"'name_id'",
"in",
"candidate",
"[",
"'attribute_names'",
"]",
":",
"candidate_nameid_value",
"=",
"None",
"candidate_name_id_format",
"=",
"candidate",
".",
"get",
"(",
"'name_id_format'",
")",
"name_id_value",
"=",
"data",
".",
"subject_id",
"name_id_format",
"=",
"data",
".",
"subject_type",
"if",
"(",
"name_id_value",
"and",
"candidate_name_id_format",
"and",
"candidate_name_id_format",
"==",
"name_id_format",
")",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"IdP asserted NameID {}\"",
".",
"format",
"(",
"name_id_value",
")",
",",
"context",
".",
"state",
")",
"candidate_nameid_value",
"=",
"name_id_value",
"# Only add the NameID value asserted by the IdP if it is not already",
"# in the list of values. This is necessary because some non-compliant IdPs",
"# have been known, for example, to assert the value of eduPersonPrincipalName",
"# in the value for SAML2 persistent NameID as well as asserting",
"# eduPersonPrincipalName.",
"if",
"candidate_nameid_value",
"not",
"in",
"values",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Added NameID {} to candidate values\"",
".",
"format",
"(",
"candidate_nameid_value",
")",
",",
"context",
".",
"state",
")",
"values",
".",
"append",
"(",
"candidate_nameid_value",
")",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARN",
",",
"\"NameID {} value also asserted as attribute value\"",
".",
"format",
"(",
"candidate_nameid_value",
")",
",",
"context",
".",
"state",
")",
"# If no value was asserted by the IdP for one of the configured list of identifier names",
"# for this candidate then go onto the next candidate.",
"if",
"None",
"in",
"values",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Candidate is missing value so skipping\"",
",",
"context",
".",
"state",
")",
"return",
"None",
"# All values for the configured list of attribute names are present",
"# so we can create a value. Add a scope if configured",
"# to do so.",
"if",
"'add_scope'",
"in",
"candidate",
":",
"if",
"candidate",
"[",
"'add_scope'",
"]",
"==",
"'issuer_entityid'",
":",
"scope",
"=",
"data",
".",
"auth_info",
".",
"issuer",
"else",
":",
"scope",
"=",
"candidate",
"[",
"'add_scope'",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Added scope {} to values\"",
".",
"format",
"(",
"scope",
")",
",",
"context",
".",
"state",
")",
"values",
".",
"append",
"(",
"scope",
")",
"# Concatenate all values to create the filter value.",
"value",
"=",
"''",
".",
"join",
"(",
"values",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Constructed filter value {}\"",
".",
"format",
"(",
"value",
")",
",",
"context",
".",
"state",
")",
"return",
"value"
] |
Construct and return a LDAP directory search filter value from the
candidate identifier.
Argument 'canidate' is a dictionary with one required key and
two optional keys:
key required value
--------------- -------- ---------------------------------
attribute_names Y list of identifier names
name_id_format N NameID format (string)
add_scope N "issuer_entityid" or other string
Argument 'data' is that object passed into the microservice
method process().
If the attribute_names list consists of more than one identifier
name then the values of the identifiers will be concatenated together
to create the filter value.
If one of the identifier names in the attribute_names is the string
'name_id' then the NameID value with format name_id_format
will be concatenated to the filter value.
If the add_scope key is present with value 'issuer_entityid' then the
entityID for the IdP will be concatenated to "scope" the value. If the
string is any other value it will be directly concatenated.
|
[
"Construct",
"and",
"return",
"a",
"LDAP",
"directory",
"search",
"filter",
"value",
"from",
"the",
"candidate",
"identifier",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L119-L214
|
237,006
|
IdentityPython/SATOSA
|
src/satosa/micro_services/ldap_attribute_store.py
|
LdapAttributeStore._filter_config
|
def _filter_config(self, config, fields=None):
"""
Filter sensitive details like passwords from a configuration
dictionary.
"""
filter_fields_default = [
'bind_password',
'connection'
]
filter_fields = fields or filter_fields_default
return dict(
map(
lambda key: (key, '<hidden>' if key in filter_fields else config[key]),
config.keys()
)
)
|
python
|
def _filter_config(self, config, fields=None):
"""
Filter sensitive details like passwords from a configuration
dictionary.
"""
filter_fields_default = [
'bind_password',
'connection'
]
filter_fields = fields or filter_fields_default
return dict(
map(
lambda key: (key, '<hidden>' if key in filter_fields else config[key]),
config.keys()
)
)
|
[
"def",
"_filter_config",
"(",
"self",
",",
"config",
",",
"fields",
"=",
"None",
")",
":",
"filter_fields_default",
"=",
"[",
"'bind_password'",
",",
"'connection'",
"]",
"filter_fields",
"=",
"fields",
"or",
"filter_fields_default",
"return",
"dict",
"(",
"map",
"(",
"lambda",
"key",
":",
"(",
"key",
",",
"'<hidden>'",
"if",
"key",
"in",
"filter_fields",
"else",
"config",
"[",
"key",
"]",
")",
",",
"config",
".",
"keys",
"(",
")",
")",
")"
] |
Filter sensitive details like passwords from a configuration
dictionary.
|
[
"Filter",
"sensitive",
"details",
"like",
"passwords",
"from",
"a",
"configuration",
"dictionary",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L216-L232
|
237,007
|
IdentityPython/SATOSA
|
src/satosa/micro_services/ldap_attribute_store.py
|
LdapAttributeStore._ldap_connection_factory
|
def _ldap_connection_factory(self, config):
"""
Use the input configuration to instantiate and return
a ldap3 Connection object.
"""
ldap_url = config['ldap_url']
bind_dn = config['bind_dn']
bind_password = config['bind_password']
if not ldap_url:
raise LdapAttributeStoreError("ldap_url is not configured")
if not bind_dn:
raise LdapAttributeStoreError("bind_dn is not configured")
if not bind_password:
raise LdapAttributeStoreError("bind_password is not configured")
pool_size = config['pool_size']
pool_keepalive = config['pool_keepalive']
server = ldap3.Server(config['ldap_url'])
satosa_logging(logger, logging.DEBUG, "Creating a new LDAP connection", None)
satosa_logging(logger, logging.DEBUG, "Using LDAP URL {}".format(ldap_url), None)
satosa_logging(logger, logging.DEBUG, "Using bind DN {}".format(bind_dn), None)
satosa_logging(logger, logging.DEBUG, "Using pool size {}".format(pool_size), None)
satosa_logging(logger, logging.DEBUG, "Using pool keep alive {}".format(pool_keepalive), None)
try:
connection = ldap3.Connection(
server,
bind_dn,
bind_password,
auto_bind=True,
client_strategy=ldap3.REUSABLE,
pool_size=pool_size,
pool_keepalive=pool_keepalive
)
except LDAPException as e:
msg = "Caught exception when connecting to LDAP server: {}".format(e)
satosa_logging(logger, logging.ERROR, msg, None)
raise LdapAttributeStoreError(msg)
satosa_logging(logger, logging.DEBUG, "Successfully connected to LDAP server", None)
return connection
|
python
|
def _ldap_connection_factory(self, config):
"""
Use the input configuration to instantiate and return
a ldap3 Connection object.
"""
ldap_url = config['ldap_url']
bind_dn = config['bind_dn']
bind_password = config['bind_password']
if not ldap_url:
raise LdapAttributeStoreError("ldap_url is not configured")
if not bind_dn:
raise LdapAttributeStoreError("bind_dn is not configured")
if not bind_password:
raise LdapAttributeStoreError("bind_password is not configured")
pool_size = config['pool_size']
pool_keepalive = config['pool_keepalive']
server = ldap3.Server(config['ldap_url'])
satosa_logging(logger, logging.DEBUG, "Creating a new LDAP connection", None)
satosa_logging(logger, logging.DEBUG, "Using LDAP URL {}".format(ldap_url), None)
satosa_logging(logger, logging.DEBUG, "Using bind DN {}".format(bind_dn), None)
satosa_logging(logger, logging.DEBUG, "Using pool size {}".format(pool_size), None)
satosa_logging(logger, logging.DEBUG, "Using pool keep alive {}".format(pool_keepalive), None)
try:
connection = ldap3.Connection(
server,
bind_dn,
bind_password,
auto_bind=True,
client_strategy=ldap3.REUSABLE,
pool_size=pool_size,
pool_keepalive=pool_keepalive
)
except LDAPException as e:
msg = "Caught exception when connecting to LDAP server: {}".format(e)
satosa_logging(logger, logging.ERROR, msg, None)
raise LdapAttributeStoreError(msg)
satosa_logging(logger, logging.DEBUG, "Successfully connected to LDAP server", None)
return connection
|
[
"def",
"_ldap_connection_factory",
"(",
"self",
",",
"config",
")",
":",
"ldap_url",
"=",
"config",
"[",
"'ldap_url'",
"]",
"bind_dn",
"=",
"config",
"[",
"'bind_dn'",
"]",
"bind_password",
"=",
"config",
"[",
"'bind_password'",
"]",
"if",
"not",
"ldap_url",
":",
"raise",
"LdapAttributeStoreError",
"(",
"\"ldap_url is not configured\"",
")",
"if",
"not",
"bind_dn",
":",
"raise",
"LdapAttributeStoreError",
"(",
"\"bind_dn is not configured\"",
")",
"if",
"not",
"bind_password",
":",
"raise",
"LdapAttributeStoreError",
"(",
"\"bind_password is not configured\"",
")",
"pool_size",
"=",
"config",
"[",
"'pool_size'",
"]",
"pool_keepalive",
"=",
"config",
"[",
"'pool_keepalive'",
"]",
"server",
"=",
"ldap3",
".",
"Server",
"(",
"config",
"[",
"'ldap_url'",
"]",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Creating a new LDAP connection\"",
",",
"None",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Using LDAP URL {}\"",
".",
"format",
"(",
"ldap_url",
")",
",",
"None",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Using bind DN {}\"",
".",
"format",
"(",
"bind_dn",
")",
",",
"None",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Using pool size {}\"",
".",
"format",
"(",
"pool_size",
")",
",",
"None",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Using pool keep alive {}\"",
".",
"format",
"(",
"pool_keepalive",
")",
",",
"None",
")",
"try",
":",
"connection",
"=",
"ldap3",
".",
"Connection",
"(",
"server",
",",
"bind_dn",
",",
"bind_password",
",",
"auto_bind",
"=",
"True",
",",
"client_strategy",
"=",
"ldap3",
".",
"REUSABLE",
",",
"pool_size",
"=",
"pool_size",
",",
"pool_keepalive",
"=",
"pool_keepalive",
")",
"except",
"LDAPException",
"as",
"e",
":",
"msg",
"=",
"\"Caught exception when connecting to LDAP server: {}\"",
".",
"format",
"(",
"e",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"msg",
",",
"None",
")",
"raise",
"LdapAttributeStoreError",
"(",
"msg",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Successfully connected to LDAP server\"",
",",
"None",
")",
"return",
"connection"
] |
Use the input configuration to instantiate and return
a ldap3 Connection object.
|
[
"Use",
"the",
"input",
"configuration",
"to",
"instantiate",
"and",
"return",
"a",
"ldap3",
"Connection",
"object",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L234-L279
|
237,008
|
IdentityPython/SATOSA
|
src/satosa/micro_services/ldap_attribute_store.py
|
LdapAttributeStore._populate_attributes
|
def _populate_attributes(self, config, record, context, data):
"""
Use a record found in LDAP to populate attributes.
"""
search_return_attributes = config['search_return_attributes']
for attr in search_return_attributes.keys():
if attr in record["attributes"]:
if record["attributes"][attr]:
data.attributes[search_return_attributes[attr]] = record["attributes"][attr]
satosa_logging(
logger,
logging.DEBUG,
"Setting internal attribute {} with values {}".format(
search_return_attributes[attr],
record["attributes"][attr]
),
context.state
)
else:
satosa_logging(
logger,
logging.DEBUG,
"Not setting internal attribute {} because value {} is null or empty".format(
search_return_attributes[attr],
record["attributes"][attr]
),
context.state
)
|
python
|
def _populate_attributes(self, config, record, context, data):
"""
Use a record found in LDAP to populate attributes.
"""
search_return_attributes = config['search_return_attributes']
for attr in search_return_attributes.keys():
if attr in record["attributes"]:
if record["attributes"][attr]:
data.attributes[search_return_attributes[attr]] = record["attributes"][attr]
satosa_logging(
logger,
logging.DEBUG,
"Setting internal attribute {} with values {}".format(
search_return_attributes[attr],
record["attributes"][attr]
),
context.state
)
else:
satosa_logging(
logger,
logging.DEBUG,
"Not setting internal attribute {} because value {} is null or empty".format(
search_return_attributes[attr],
record["attributes"][attr]
),
context.state
)
|
[
"def",
"_populate_attributes",
"(",
"self",
",",
"config",
",",
"record",
",",
"context",
",",
"data",
")",
":",
"search_return_attributes",
"=",
"config",
"[",
"'search_return_attributes'",
"]",
"for",
"attr",
"in",
"search_return_attributes",
".",
"keys",
"(",
")",
":",
"if",
"attr",
"in",
"record",
"[",
"\"attributes\"",
"]",
":",
"if",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
":",
"data",
".",
"attributes",
"[",
"search_return_attributes",
"[",
"attr",
"]",
"]",
"=",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Setting internal attribute {} with values {}\"",
".",
"format",
"(",
"search_return_attributes",
"[",
"attr",
"]",
",",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
")",
",",
"context",
".",
"state",
")",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Not setting internal attribute {} because value {} is null or empty\"",
".",
"format",
"(",
"search_return_attributes",
"[",
"attr",
"]",
",",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
")",
",",
"context",
".",
"state",
")"
] |
Use a record found in LDAP to populate attributes.
|
[
"Use",
"a",
"record",
"found",
"in",
"LDAP",
"to",
"populate",
"attributes",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L281-L308
|
237,009
|
IdentityPython/SATOSA
|
src/satosa/micro_services/ldap_attribute_store.py
|
LdapAttributeStore._populate_input_for_name_id
|
def _populate_input_for_name_id(self, config, record, context, data):
"""
Use a record found in LDAP to populate input for
NameID generation.
"""
user_id = ""
user_id_from_attrs = config['user_id_from_attrs']
for attr in user_id_from_attrs:
if attr in record["attributes"]:
value = record["attributes"][attr]
if isinstance(value, list):
# Use a default sort to ensure some predictability since the
# LDAP directory server may return multi-valued attributes
# in any order.
value.sort()
user_id += "".join(value)
satosa_logging(
logger,
logging.DEBUG,
"Added attribute {} with values {} to input for NameID".format(attr, value),
context.state
)
else:
user_id += value
satosa_logging(
logger,
logging.DEBUG,
"Added attribute {} with value {} to input for NameID".format(attr, value),
context.state
)
if not user_id:
satosa_logging(
logger,
logging.WARNING,
"Input for NameID is empty so not overriding default",
context.state
)
else:
data.subject_id = user_id
satosa_logging(
logger,
logging.DEBUG,
"Input for NameID is {}".format(data.subject_id),
context.state
)
|
python
|
def _populate_input_for_name_id(self, config, record, context, data):
"""
Use a record found in LDAP to populate input for
NameID generation.
"""
user_id = ""
user_id_from_attrs = config['user_id_from_attrs']
for attr in user_id_from_attrs:
if attr in record["attributes"]:
value = record["attributes"][attr]
if isinstance(value, list):
# Use a default sort to ensure some predictability since the
# LDAP directory server may return multi-valued attributes
# in any order.
value.sort()
user_id += "".join(value)
satosa_logging(
logger,
logging.DEBUG,
"Added attribute {} with values {} to input for NameID".format(attr, value),
context.state
)
else:
user_id += value
satosa_logging(
logger,
logging.DEBUG,
"Added attribute {} with value {} to input for NameID".format(attr, value),
context.state
)
if not user_id:
satosa_logging(
logger,
logging.WARNING,
"Input for NameID is empty so not overriding default",
context.state
)
else:
data.subject_id = user_id
satosa_logging(
logger,
logging.DEBUG,
"Input for NameID is {}".format(data.subject_id),
context.state
)
|
[
"def",
"_populate_input_for_name_id",
"(",
"self",
",",
"config",
",",
"record",
",",
"context",
",",
"data",
")",
":",
"user_id",
"=",
"\"\"",
"user_id_from_attrs",
"=",
"config",
"[",
"'user_id_from_attrs'",
"]",
"for",
"attr",
"in",
"user_id_from_attrs",
":",
"if",
"attr",
"in",
"record",
"[",
"\"attributes\"",
"]",
":",
"value",
"=",
"record",
"[",
"\"attributes\"",
"]",
"[",
"attr",
"]",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"# Use a default sort to ensure some predictability since the",
"# LDAP directory server may return multi-valued attributes",
"# in any order.",
"value",
".",
"sort",
"(",
")",
"user_id",
"+=",
"\"\"",
".",
"join",
"(",
"value",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Added attribute {} with values {} to input for NameID\"",
".",
"format",
"(",
"attr",
",",
"value",
")",
",",
"context",
".",
"state",
")",
"else",
":",
"user_id",
"+=",
"value",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Added attribute {} with value {} to input for NameID\"",
".",
"format",
"(",
"attr",
",",
"value",
")",
",",
"context",
".",
"state",
")",
"if",
"not",
"user_id",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARNING",
",",
"\"Input for NameID is empty so not overriding default\"",
",",
"context",
".",
"state",
")",
"else",
":",
"data",
".",
"subject_id",
"=",
"user_id",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Input for NameID is {}\"",
".",
"format",
"(",
"data",
".",
"subject_id",
")",
",",
"context",
".",
"state",
")"
] |
Use a record found in LDAP to populate input for
NameID generation.
|
[
"Use",
"a",
"record",
"found",
"in",
"LDAP",
"to",
"populate",
"input",
"for",
"NameID",
"generation",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/ldap_attribute_store.py#L310-L354
|
237,010
|
IdentityPython/SATOSA
|
src/satosa/satosa_config.py
|
SATOSAConfig._verify_dict
|
def _verify_dict(self, conf):
"""
Check that the configuration contains all necessary keys.
:type conf: dict
:rtype: None
:raise SATOSAConfigurationError: if the configuration is incorrect
:param conf: config to verify
:return: None
"""
if not conf:
raise SATOSAConfigurationError("Missing configuration or unknown format")
for key in SATOSAConfig.mandatory_dict_keys:
if key not in conf:
raise SATOSAConfigurationError("Missing key '%s' in config" % key)
for key in SATOSAConfig.sensitive_dict_keys:
if key not in conf and "SATOSA_{key}".format(key=key) not in os.environ:
raise SATOSAConfigurationError("Missing key '%s' from config and ENVIRONMENT" % key)
|
python
|
def _verify_dict(self, conf):
"""
Check that the configuration contains all necessary keys.
:type conf: dict
:rtype: None
:raise SATOSAConfigurationError: if the configuration is incorrect
:param conf: config to verify
:return: None
"""
if not conf:
raise SATOSAConfigurationError("Missing configuration or unknown format")
for key in SATOSAConfig.mandatory_dict_keys:
if key not in conf:
raise SATOSAConfigurationError("Missing key '%s' in config" % key)
for key in SATOSAConfig.sensitive_dict_keys:
if key not in conf and "SATOSA_{key}".format(key=key) not in os.environ:
raise SATOSAConfigurationError("Missing key '%s' from config and ENVIRONMENT" % key)
|
[
"def",
"_verify_dict",
"(",
"self",
",",
"conf",
")",
":",
"if",
"not",
"conf",
":",
"raise",
"SATOSAConfigurationError",
"(",
"\"Missing configuration or unknown format\"",
")",
"for",
"key",
"in",
"SATOSAConfig",
".",
"mandatory_dict_keys",
":",
"if",
"key",
"not",
"in",
"conf",
":",
"raise",
"SATOSAConfigurationError",
"(",
"\"Missing key '%s' in config\"",
"%",
"key",
")",
"for",
"key",
"in",
"SATOSAConfig",
".",
"sensitive_dict_keys",
":",
"if",
"key",
"not",
"in",
"conf",
"and",
"\"SATOSA_{key}\"",
".",
"format",
"(",
"key",
"=",
"key",
")",
"not",
"in",
"os",
".",
"environ",
":",
"raise",
"SATOSAConfigurationError",
"(",
"\"Missing key '%s' from config and ENVIRONMENT\"",
"%",
"key",
")"
] |
Check that the configuration contains all necessary keys.
:type conf: dict
:rtype: None
:raise SATOSAConfigurationError: if the configuration is incorrect
:param conf: config to verify
:return: None
|
[
"Check",
"that",
"the",
"configuration",
"contains",
"all",
"necessary",
"keys",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/satosa_config.py#L68-L88
|
237,011
|
IdentityPython/SATOSA
|
src/satosa/satosa_config.py
|
SATOSAConfig._load_yaml
|
def _load_yaml(self, config_file):
"""
Load config from yaml file or string
:type config_file: str
:rtype: dict
:param config_file: config to load. Can be file path or yaml string
:return: Loaded config
"""
try:
with open(config_file) as f:
return yaml.safe_load(f.read())
except yaml.YAMLError as exc:
logger.error("Could not parse config as YAML: {}", str(exc))
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
logger.error("Error position: (%s:%s)" % (mark.line + 1, mark.column + 1))
except IOError as e:
logger.debug("Could not open config file: {}", str(e))
return None
|
python
|
def _load_yaml(self, config_file):
"""
Load config from yaml file or string
:type config_file: str
:rtype: dict
:param config_file: config to load. Can be file path or yaml string
:return: Loaded config
"""
try:
with open(config_file) as f:
return yaml.safe_load(f.read())
except yaml.YAMLError as exc:
logger.error("Could not parse config as YAML: {}", str(exc))
if hasattr(exc, 'problem_mark'):
mark = exc.problem_mark
logger.error("Error position: (%s:%s)" % (mark.line + 1, mark.column + 1))
except IOError as e:
logger.debug("Could not open config file: {}", str(e))
return None
|
[
"def",
"_load_yaml",
"(",
"self",
",",
"config_file",
")",
":",
"try",
":",
"with",
"open",
"(",
"config_file",
")",
"as",
"f",
":",
"return",
"yaml",
".",
"safe_load",
"(",
"f",
".",
"read",
"(",
")",
")",
"except",
"yaml",
".",
"YAMLError",
"as",
"exc",
":",
"logger",
".",
"error",
"(",
"\"Could not parse config as YAML: {}\"",
",",
"str",
"(",
"exc",
")",
")",
"if",
"hasattr",
"(",
"exc",
",",
"'problem_mark'",
")",
":",
"mark",
"=",
"exc",
".",
"problem_mark",
"logger",
".",
"error",
"(",
"\"Error position: (%s:%s)\"",
"%",
"(",
"mark",
".",
"line",
"+",
"1",
",",
"mark",
".",
"column",
"+",
"1",
")",
")",
"except",
"IOError",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"\"Could not open config file: {}\"",
",",
"str",
"(",
"e",
")",
")",
"return",
"None"
] |
Load config from yaml file or string
:type config_file: str
:rtype: dict
:param config_file: config to load. Can be file path or yaml string
:return: Loaded config
|
[
"Load",
"config",
"from",
"yaml",
"file",
"or",
"string"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/satosa_config.py#L136-L157
|
237,012
|
IdentityPython/SATOSA
|
src/satosa/logging_util.py
|
satosa_logging
|
def satosa_logging(logger, level, message, state, **kwargs):
"""
Adds a session ID to the message.
:type logger: logging
:type level: int
:type message: str
:type state: satosa.state.State
:param logger: Logger to use
:param level: Logger level (ex: logging.DEBUG/logging.WARN/...)
:param message: Message
:param state: The current state
:param kwargs: set exc_info=True to get an exception stack trace in the log
"""
if state is None:
session_id = "UNKNOWN"
else:
try:
session_id = state[LOGGER_STATE_KEY]
except KeyError:
session_id = uuid4().urn
state[LOGGER_STATE_KEY] = session_id
logger.log(level, "[{id}] {msg}".format(id=session_id, msg=message), **kwargs)
|
python
|
def satosa_logging(logger, level, message, state, **kwargs):
"""
Adds a session ID to the message.
:type logger: logging
:type level: int
:type message: str
:type state: satosa.state.State
:param logger: Logger to use
:param level: Logger level (ex: logging.DEBUG/logging.WARN/...)
:param message: Message
:param state: The current state
:param kwargs: set exc_info=True to get an exception stack trace in the log
"""
if state is None:
session_id = "UNKNOWN"
else:
try:
session_id = state[LOGGER_STATE_KEY]
except KeyError:
session_id = uuid4().urn
state[LOGGER_STATE_KEY] = session_id
logger.log(level, "[{id}] {msg}".format(id=session_id, msg=message), **kwargs)
|
[
"def",
"satosa_logging",
"(",
"logger",
",",
"level",
",",
"message",
",",
"state",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"state",
"is",
"None",
":",
"session_id",
"=",
"\"UNKNOWN\"",
"else",
":",
"try",
":",
"session_id",
"=",
"state",
"[",
"LOGGER_STATE_KEY",
"]",
"except",
"KeyError",
":",
"session_id",
"=",
"uuid4",
"(",
")",
".",
"urn",
"state",
"[",
"LOGGER_STATE_KEY",
"]",
"=",
"session_id",
"logger",
".",
"log",
"(",
"level",
",",
"\"[{id}] {msg}\"",
".",
"format",
"(",
"id",
"=",
"session_id",
",",
"msg",
"=",
"message",
")",
",",
"*",
"*",
"kwargs",
")"
] |
Adds a session ID to the message.
:type logger: logging
:type level: int
:type message: str
:type state: satosa.state.State
:param logger: Logger to use
:param level: Logger level (ex: logging.DEBUG/logging.WARN/...)
:param message: Message
:param state: The current state
:param kwargs: set exc_info=True to get an exception stack trace in the log
|
[
"Adds",
"a",
"session",
"ID",
"to",
"the",
"message",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/logging_util.py#L10-L33
|
237,013
|
IdentityPython/SATOSA
|
src/satosa/micro_services/consent.py
|
Consent.process
|
def process(self, context, internal_response):
"""
Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
"""
consent_state = context.state[STATE_KEY]
internal_response.attributes = self._filter_attributes(internal_response.attributes, consent_state["filter"])
id_hash = self._get_consent_id(internal_response.requester, internal_response.subject_id,
internal_response.attributes)
try:
# Check if consent is already given
consent_attributes = self._verify_consent(id_hash)
except requests.exceptions.ConnectionError as e:
satosa_logging(logger, logging.ERROR,
"Consent service is not reachable, no consent given.", context.state)
# Send an internal_response without any attributes
internal_response.attributes = {}
return self._end_consent(context, internal_response)
# Previous consent was given
if consent_attributes is not None:
satosa_logging(logger, logging.DEBUG, "Previous consent was given", context.state)
internal_response.attributes = self._filter_attributes(internal_response.attributes, consent_attributes)
return self._end_consent(context, internal_response)
# No previous consent, request consent by user
return self._approve_new_consent(context, internal_response, id_hash)
|
python
|
def process(self, context, internal_response):
"""
Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
"""
consent_state = context.state[STATE_KEY]
internal_response.attributes = self._filter_attributes(internal_response.attributes, consent_state["filter"])
id_hash = self._get_consent_id(internal_response.requester, internal_response.subject_id,
internal_response.attributes)
try:
# Check if consent is already given
consent_attributes = self._verify_consent(id_hash)
except requests.exceptions.ConnectionError as e:
satosa_logging(logger, logging.ERROR,
"Consent service is not reachable, no consent given.", context.state)
# Send an internal_response without any attributes
internal_response.attributes = {}
return self._end_consent(context, internal_response)
# Previous consent was given
if consent_attributes is not None:
satosa_logging(logger, logging.DEBUG, "Previous consent was given", context.state)
internal_response.attributes = self._filter_attributes(internal_response.attributes, consent_attributes)
return self._end_consent(context, internal_response)
# No previous consent, request consent by user
return self._approve_new_consent(context, internal_response, id_hash)
|
[
"def",
"process",
"(",
"self",
",",
"context",
",",
"internal_response",
")",
":",
"consent_state",
"=",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"internal_response",
".",
"attributes",
"=",
"self",
".",
"_filter_attributes",
"(",
"internal_response",
".",
"attributes",
",",
"consent_state",
"[",
"\"filter\"",
"]",
")",
"id_hash",
"=",
"self",
".",
"_get_consent_id",
"(",
"internal_response",
".",
"requester",
",",
"internal_response",
".",
"subject_id",
",",
"internal_response",
".",
"attributes",
")",
"try",
":",
"# Check if consent is already given",
"consent_attributes",
"=",
"self",
".",
"_verify_consent",
"(",
"id_hash",
")",
"except",
"requests",
".",
"exceptions",
".",
"ConnectionError",
"as",
"e",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"Consent service is not reachable, no consent given.\"",
",",
"context",
".",
"state",
")",
"# Send an internal_response without any attributes",
"internal_response",
".",
"attributes",
"=",
"{",
"}",
"return",
"self",
".",
"_end_consent",
"(",
"context",
",",
"internal_response",
")",
"# Previous consent was given",
"if",
"consent_attributes",
"is",
"not",
"None",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Previous consent was given\"",
",",
"context",
".",
"state",
")",
"internal_response",
".",
"attributes",
"=",
"self",
".",
"_filter_attributes",
"(",
"internal_response",
".",
"attributes",
",",
"consent_attributes",
")",
"return",
"self",
".",
"_end_consent",
"(",
"context",
",",
"internal_response",
")",
"# No previous consent, request consent by user",
"return",
"self",
".",
"_approve_new_consent",
"(",
"context",
",",
"internal_response",
",",
"id_hash",
")"
] |
Manage consent and attribute filtering
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
|
[
"Manage",
"consent",
"and",
"attribute",
"filtering"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L106-L141
|
237,014
|
IdentityPython/SATOSA
|
src/satosa/micro_services/consent.py
|
Consent._get_consent_id
|
def _get_consent_id(self, requester, user_id, filtered_attr):
"""
Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling requester
:param user_id: The authorized user id
:param filtered_attr: a list containing all attributes to be sent
:return: an id
"""
filtered_attr_key_list = sorted(filtered_attr.keys())
hash_str = ""
for key in filtered_attr_key_list:
_hash_value = "".join(sorted(filtered_attr[key]))
hash_str += key + _hash_value
id_string = "%s%s%s" % (requester, user_id, hash_str)
return urlsafe_b64encode(hashlib.sha512(id_string.encode("utf-8")).hexdigest().encode("utf-8")).decode("utf-8")
|
python
|
def _get_consent_id(self, requester, user_id, filtered_attr):
"""
Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling requester
:param user_id: The authorized user id
:param filtered_attr: a list containing all attributes to be sent
:return: an id
"""
filtered_attr_key_list = sorted(filtered_attr.keys())
hash_str = ""
for key in filtered_attr_key_list:
_hash_value = "".join(sorted(filtered_attr[key]))
hash_str += key + _hash_value
id_string = "%s%s%s" % (requester, user_id, hash_str)
return urlsafe_b64encode(hashlib.sha512(id_string.encode("utf-8")).hexdigest().encode("utf-8")).decode("utf-8")
|
[
"def",
"_get_consent_id",
"(",
"self",
",",
"requester",
",",
"user_id",
",",
"filtered_attr",
")",
":",
"filtered_attr_key_list",
"=",
"sorted",
"(",
"filtered_attr",
".",
"keys",
"(",
")",
")",
"hash_str",
"=",
"\"\"",
"for",
"key",
"in",
"filtered_attr_key_list",
":",
"_hash_value",
"=",
"\"\"",
".",
"join",
"(",
"sorted",
"(",
"filtered_attr",
"[",
"key",
"]",
")",
")",
"hash_str",
"+=",
"key",
"+",
"_hash_value",
"id_string",
"=",
"\"%s%s%s\"",
"%",
"(",
"requester",
",",
"user_id",
",",
"hash_str",
")",
"return",
"urlsafe_b64encode",
"(",
"hashlib",
".",
"sha512",
"(",
"id_string",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"decode",
"(",
"\"utf-8\"",
")"
] |
Get a hashed id based on requester, user id and filtered attributes
:type requester: str
:type user_id: str
:type filtered_attr: dict[str, str]
:param requester: The calling requester
:param user_id: The authorized user id
:param filtered_attr: a list containing all attributes to be sent
:return: an id
|
[
"Get",
"a",
"hashed",
"id",
"based",
"on",
"requester",
"user",
"id",
"and",
"filtered",
"attributes"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L146-L166
|
237,015
|
IdentityPython/SATOSA
|
src/satosa/micro_services/consent.py
|
Consent._consent_registration
|
def _consent_registration(self, consent_args):
"""
Register a request at the consent service
:type consent_args: dict
:rtype: str
:param consent_args: All necessary parameters for the consent request
:return: Ticket received from the consent service
"""
jws = JWS(json.dumps(consent_args), alg=self.signing_key.alg).sign_compact([self.signing_key])
request = "{}/creq/{}".format(self.api_url, jws)
res = requests.get(request)
if res.status_code != 200:
raise UnexpectedResponseError("Consent service error: %s %s", res.status_code, res.text)
return res.text
|
python
|
def _consent_registration(self, consent_args):
"""
Register a request at the consent service
:type consent_args: dict
:rtype: str
:param consent_args: All necessary parameters for the consent request
:return: Ticket received from the consent service
"""
jws = JWS(json.dumps(consent_args), alg=self.signing_key.alg).sign_compact([self.signing_key])
request = "{}/creq/{}".format(self.api_url, jws)
res = requests.get(request)
if res.status_code != 200:
raise UnexpectedResponseError("Consent service error: %s %s", res.status_code, res.text)
return res.text
|
[
"def",
"_consent_registration",
"(",
"self",
",",
"consent_args",
")",
":",
"jws",
"=",
"JWS",
"(",
"json",
".",
"dumps",
"(",
"consent_args",
")",
",",
"alg",
"=",
"self",
".",
"signing_key",
".",
"alg",
")",
".",
"sign_compact",
"(",
"[",
"self",
".",
"signing_key",
"]",
")",
"request",
"=",
"\"{}/creq/{}\"",
".",
"format",
"(",
"self",
".",
"api_url",
",",
"jws",
")",
"res",
"=",
"requests",
".",
"get",
"(",
"request",
")",
"if",
"res",
".",
"status_code",
"!=",
"200",
":",
"raise",
"UnexpectedResponseError",
"(",
"\"Consent service error: %s %s\"",
",",
"res",
".",
"status_code",
",",
"res",
".",
"text",
")",
"return",
"res",
".",
"text"
] |
Register a request at the consent service
:type consent_args: dict
:rtype: str
:param consent_args: All necessary parameters for the consent request
:return: Ticket received from the consent service
|
[
"Register",
"a",
"request",
"at",
"the",
"consent",
"service"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L168-L185
|
237,016
|
IdentityPython/SATOSA
|
src/satosa/micro_services/consent.py
|
Consent._verify_consent
|
def _verify_consent(self, consent_id):
"""
Connects to the consent service using the REST api and checks if the user has given consent
:type consent_id: str
:rtype: Optional[List[str]]
:param consent_id: An id associated to the authenticated user, the calling requester and
attributes to be sent.
:return: list attributes given which have been approved by user consent
"""
request = "{}/verify/{}".format(self.api_url, consent_id)
res = requests.get(request)
if res.status_code == 200:
return json.loads(res.text)
return None
|
python
|
def _verify_consent(self, consent_id):
"""
Connects to the consent service using the REST api and checks if the user has given consent
:type consent_id: str
:rtype: Optional[List[str]]
:param consent_id: An id associated to the authenticated user, the calling requester and
attributes to be sent.
:return: list attributes given which have been approved by user consent
"""
request = "{}/verify/{}".format(self.api_url, consent_id)
res = requests.get(request)
if res.status_code == 200:
return json.loads(res.text)
return None
|
[
"def",
"_verify_consent",
"(",
"self",
",",
"consent_id",
")",
":",
"request",
"=",
"\"{}/verify/{}\"",
".",
"format",
"(",
"self",
".",
"api_url",
",",
"consent_id",
")",
"res",
"=",
"requests",
".",
"get",
"(",
"request",
")",
"if",
"res",
".",
"status_code",
"==",
"200",
":",
"return",
"json",
".",
"loads",
"(",
"res",
".",
"text",
")",
"return",
"None"
] |
Connects to the consent service using the REST api and checks if the user has given consent
:type consent_id: str
:rtype: Optional[List[str]]
:param consent_id: An id associated to the authenticated user, the calling requester and
attributes to be sent.
:return: list attributes given which have been approved by user consent
|
[
"Connects",
"to",
"the",
"consent",
"service",
"using",
"the",
"REST",
"api",
"and",
"checks",
"if",
"the",
"user",
"has",
"given",
"consent"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L187-L204
|
237,017
|
IdentityPython/SATOSA
|
src/satosa/micro_services/consent.py
|
Consent._end_consent
|
def _end_consent(self, context, internal_response):
"""
Clear the state for consent and end the consent step
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
"""
del context.state[STATE_KEY]
return super().process(context, internal_response)
|
python
|
def _end_consent(self, context, internal_response):
"""
Clear the state for consent and end the consent step
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
"""
del context.state[STATE_KEY]
return super().process(context, internal_response)
|
[
"def",
"_end_consent",
"(",
"self",
",",
"context",
",",
"internal_response",
")",
":",
"del",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"return",
"super",
"(",
")",
".",
"process",
"(",
"context",
",",
"internal_response",
")"
] |
Clear the state for consent and end the consent step
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: response context
:param internal_response: the response
:return: response
|
[
"Clear",
"the",
"state",
"for",
"consent",
"and",
"end",
"the",
"consent",
"step"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/consent.py#L206-L219
|
237,018
|
IdentityPython/SATOSA
|
src/satosa/micro_services/primary_identifier.py
|
PrimaryIdentifier.constructPrimaryIdentifier
|
def constructPrimaryIdentifier(self, data, ordered_identifier_candidates):
"""
Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration.
"""
logprefix = PrimaryIdentifier.logprefix
context = self.context
attributes = data.attributes
satosa_logging(logger, logging.DEBUG, "{} Input attributes {}".format(logprefix, attributes), context.state)
value = None
for candidate in ordered_identifier_candidates:
satosa_logging(logger, logging.DEBUG, "{} Considering candidate {}".format(logprefix, candidate), context.state)
# Get the values asserted by the IdP for the configured list of attribute names for this candidate
# and substitute None if the IdP did not assert any value for a configured attribute.
values = [ attributes.get(attribute_name, [None])[0] for attribute_name in candidate['attribute_names'] ]
satosa_logging(logger, logging.DEBUG, "{} Found candidate values {}".format(logprefix, values), context.state)
# If one of the configured attribute names is name_id then if there is also a configured
# name_id_format add the value for the NameID of that format if it was asserted by the IdP
# or else add the value None.
if 'name_id' in candidate['attribute_names']:
candidate_nameid_value = None
candidate_nameid_value = None
candidate_name_id_format = candidate.get('name_id_format')
name_id_value = data.subject_id
name_id_format = data.subject_type
if (
name_id_value
and candidate_name_id_format
and candidate_name_id_format == name_id_format
):
satosa_logging(logger, logging.DEBUG, "{} IdP asserted NameID {}".format(logprefix, name_id_value), context.state)
candidate_nameid_value = name_id_value
# Only add the NameID value asserted by the IdP if it is not already
# in the list of values. This is necessary because some non-compliant IdPs
# have been known, for example, to assert the value of eduPersonPrincipalName
# in the value for SAML2 persistent NameID as well as asserting
# eduPersonPrincipalName.
if candidate_nameid_value not in values:
satosa_logging(logger, logging.DEBUG, "{} Added NameID {} to candidate values".format(logprefix, candidate_nameid_value), context.state)
values.append(candidate_nameid_value)
else:
satosa_logging(logger, logging.WARN, "{} NameID {} value also asserted as attribute value".format(logprefix, candidate_nameid_value), context.state)
# If no value was asserted by the IdP for one of the configured list of attribute names
# for this candidate then go onto the next candidate.
if None in values:
satosa_logging(logger, logging.DEBUG, "{} Candidate is missing value so skipping".format(logprefix), context.state)
continue
# All values for the configured list of attribute names are present
# so we can create a primary identifer. Add a scope if configured
# to do so.
if 'add_scope' in candidate:
if candidate['add_scope'] == 'issuer_entityid':
scope = data.auth_info.issuer
else:
scope = candidate['add_scope']
satosa_logging(logger, logging.DEBUG, "{} Added scope {} to values".format(logprefix, scope), context.state)
values.append(scope)
# Concatenate all values to create the primary identifier.
value = ''.join(values)
break
return value
|
python
|
def constructPrimaryIdentifier(self, data, ordered_identifier_candidates):
"""
Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration.
"""
logprefix = PrimaryIdentifier.logprefix
context = self.context
attributes = data.attributes
satosa_logging(logger, logging.DEBUG, "{} Input attributes {}".format(logprefix, attributes), context.state)
value = None
for candidate in ordered_identifier_candidates:
satosa_logging(logger, logging.DEBUG, "{} Considering candidate {}".format(logprefix, candidate), context.state)
# Get the values asserted by the IdP for the configured list of attribute names for this candidate
# and substitute None if the IdP did not assert any value for a configured attribute.
values = [ attributes.get(attribute_name, [None])[0] for attribute_name in candidate['attribute_names'] ]
satosa_logging(logger, logging.DEBUG, "{} Found candidate values {}".format(logprefix, values), context.state)
# If one of the configured attribute names is name_id then if there is also a configured
# name_id_format add the value for the NameID of that format if it was asserted by the IdP
# or else add the value None.
if 'name_id' in candidate['attribute_names']:
candidate_nameid_value = None
candidate_nameid_value = None
candidate_name_id_format = candidate.get('name_id_format')
name_id_value = data.subject_id
name_id_format = data.subject_type
if (
name_id_value
and candidate_name_id_format
and candidate_name_id_format == name_id_format
):
satosa_logging(logger, logging.DEBUG, "{} IdP asserted NameID {}".format(logprefix, name_id_value), context.state)
candidate_nameid_value = name_id_value
# Only add the NameID value asserted by the IdP if it is not already
# in the list of values. This is necessary because some non-compliant IdPs
# have been known, for example, to assert the value of eduPersonPrincipalName
# in the value for SAML2 persistent NameID as well as asserting
# eduPersonPrincipalName.
if candidate_nameid_value not in values:
satosa_logging(logger, logging.DEBUG, "{} Added NameID {} to candidate values".format(logprefix, candidate_nameid_value), context.state)
values.append(candidate_nameid_value)
else:
satosa_logging(logger, logging.WARN, "{} NameID {} value also asserted as attribute value".format(logprefix, candidate_nameid_value), context.state)
# If no value was asserted by the IdP for one of the configured list of attribute names
# for this candidate then go onto the next candidate.
if None in values:
satosa_logging(logger, logging.DEBUG, "{} Candidate is missing value so skipping".format(logprefix), context.state)
continue
# All values for the configured list of attribute names are present
# so we can create a primary identifer. Add a scope if configured
# to do so.
if 'add_scope' in candidate:
if candidate['add_scope'] == 'issuer_entityid':
scope = data.auth_info.issuer
else:
scope = candidate['add_scope']
satosa_logging(logger, logging.DEBUG, "{} Added scope {} to values".format(logprefix, scope), context.state)
values.append(scope)
# Concatenate all values to create the primary identifier.
value = ''.join(values)
break
return value
|
[
"def",
"constructPrimaryIdentifier",
"(",
"self",
",",
"data",
",",
"ordered_identifier_candidates",
")",
":",
"logprefix",
"=",
"PrimaryIdentifier",
".",
"logprefix",
"context",
"=",
"self",
".",
"context",
"attributes",
"=",
"data",
".",
"attributes",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Input attributes {}\"",
".",
"format",
"(",
"logprefix",
",",
"attributes",
")",
",",
"context",
".",
"state",
")",
"value",
"=",
"None",
"for",
"candidate",
"in",
"ordered_identifier_candidates",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Considering candidate {}\"",
".",
"format",
"(",
"logprefix",
",",
"candidate",
")",
",",
"context",
".",
"state",
")",
"# Get the values asserted by the IdP for the configured list of attribute names for this candidate",
"# and substitute None if the IdP did not assert any value for a configured attribute.",
"values",
"=",
"[",
"attributes",
".",
"get",
"(",
"attribute_name",
",",
"[",
"None",
"]",
")",
"[",
"0",
"]",
"for",
"attribute_name",
"in",
"candidate",
"[",
"'attribute_names'",
"]",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Found candidate values {}\"",
".",
"format",
"(",
"logprefix",
",",
"values",
")",
",",
"context",
".",
"state",
")",
"# If one of the configured attribute names is name_id then if there is also a configured",
"# name_id_format add the value for the NameID of that format if it was asserted by the IdP",
"# or else add the value None.",
"if",
"'name_id'",
"in",
"candidate",
"[",
"'attribute_names'",
"]",
":",
"candidate_nameid_value",
"=",
"None",
"candidate_nameid_value",
"=",
"None",
"candidate_name_id_format",
"=",
"candidate",
".",
"get",
"(",
"'name_id_format'",
")",
"name_id_value",
"=",
"data",
".",
"subject_id",
"name_id_format",
"=",
"data",
".",
"subject_type",
"if",
"(",
"name_id_value",
"and",
"candidate_name_id_format",
"and",
"candidate_name_id_format",
"==",
"name_id_format",
")",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} IdP asserted NameID {}\"",
".",
"format",
"(",
"logprefix",
",",
"name_id_value",
")",
",",
"context",
".",
"state",
")",
"candidate_nameid_value",
"=",
"name_id_value",
"# Only add the NameID value asserted by the IdP if it is not already",
"# in the list of values. This is necessary because some non-compliant IdPs",
"# have been known, for example, to assert the value of eduPersonPrincipalName",
"# in the value for SAML2 persistent NameID as well as asserting",
"# eduPersonPrincipalName.",
"if",
"candidate_nameid_value",
"not",
"in",
"values",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Added NameID {} to candidate values\"",
".",
"format",
"(",
"logprefix",
",",
"candidate_nameid_value",
")",
",",
"context",
".",
"state",
")",
"values",
".",
"append",
"(",
"candidate_nameid_value",
")",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARN",
",",
"\"{} NameID {} value also asserted as attribute value\"",
".",
"format",
"(",
"logprefix",
",",
"candidate_nameid_value",
")",
",",
"context",
".",
"state",
")",
"# If no value was asserted by the IdP for one of the configured list of attribute names",
"# for this candidate then go onto the next candidate.",
"if",
"None",
"in",
"values",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Candidate is missing value so skipping\"",
".",
"format",
"(",
"logprefix",
")",
",",
"context",
".",
"state",
")",
"continue",
"# All values for the configured list of attribute names are present",
"# so we can create a primary identifer. Add a scope if configured",
"# to do so.",
"if",
"'add_scope'",
"in",
"candidate",
":",
"if",
"candidate",
"[",
"'add_scope'",
"]",
"==",
"'issuer_entityid'",
":",
"scope",
"=",
"data",
".",
"auth_info",
".",
"issuer",
"else",
":",
"scope",
"=",
"candidate",
"[",
"'add_scope'",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"{} Added scope {} to values\"",
".",
"format",
"(",
"logprefix",
",",
"scope",
")",
",",
"context",
".",
"state",
")",
"values",
".",
"append",
"(",
"scope",
")",
"# Concatenate all values to create the primary identifier.",
"value",
"=",
"''",
".",
"join",
"(",
"values",
")",
"break",
"return",
"value"
] |
Construct and return a primary identifier value from the
data asserted by the IdP using the ordered list of candidates
from the configuration.
|
[
"Construct",
"and",
"return",
"a",
"primary",
"identifier",
"value",
"from",
"the",
"data",
"asserted",
"by",
"the",
"IdP",
"using",
"the",
"ordered",
"list",
"of",
"candidates",
"from",
"the",
"configuration",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/primary_identifier.py#L32-L103
|
237,019
|
IdentityPython/SATOSA
|
src/satosa/state.py
|
state_to_cookie
|
def state_to_cookie(state, name, path, encryption_key):
"""
Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the cookie
:param path: Endpoint path the cookie will be associated to
:param encryption_key: Key to encrypt the state information
:return: A cookie
"""
cookie_data = "" if state.delete else state.urlstate(encryption_key)
max_age = 0 if state.delete else STATE_COOKIE_MAX_AGE
satosa_logging(logger, logging.DEBUG,
"Saving state as cookie, secure: %s, max-age: %s, path: %s" %
(STATE_COOKIE_SECURE, STATE_COOKIE_MAX_AGE, path), state)
cookie = SimpleCookie()
cookie[name] = cookie_data
cookie[name]["secure"] = STATE_COOKIE_SECURE
cookie[name]["path"] = path
cookie[name]["max-age"] = max_age
return cookie
|
python
|
def state_to_cookie(state, name, path, encryption_key):
"""
Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the cookie
:param path: Endpoint path the cookie will be associated to
:param encryption_key: Key to encrypt the state information
:return: A cookie
"""
cookie_data = "" if state.delete else state.urlstate(encryption_key)
max_age = 0 if state.delete else STATE_COOKIE_MAX_AGE
satosa_logging(logger, logging.DEBUG,
"Saving state as cookie, secure: %s, max-age: %s, path: %s" %
(STATE_COOKIE_SECURE, STATE_COOKIE_MAX_AGE, path), state)
cookie = SimpleCookie()
cookie[name] = cookie_data
cookie[name]["secure"] = STATE_COOKIE_SECURE
cookie[name]["path"] = path
cookie[name]["max-age"] = max_age
return cookie
|
[
"def",
"state_to_cookie",
"(",
"state",
",",
"name",
",",
"path",
",",
"encryption_key",
")",
":",
"cookie_data",
"=",
"\"\"",
"if",
"state",
".",
"delete",
"else",
"state",
".",
"urlstate",
"(",
"encryption_key",
")",
"max_age",
"=",
"0",
"if",
"state",
".",
"delete",
"else",
"STATE_COOKIE_MAX_AGE",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Saving state as cookie, secure: %s, max-age: %s, path: %s\"",
"%",
"(",
"STATE_COOKIE_SECURE",
",",
"STATE_COOKIE_MAX_AGE",
",",
"path",
")",
",",
"state",
")",
"cookie",
"=",
"SimpleCookie",
"(",
")",
"cookie",
"[",
"name",
"]",
"=",
"cookie_data",
"cookie",
"[",
"name",
"]",
"[",
"\"secure\"",
"]",
"=",
"STATE_COOKIE_SECURE",
"cookie",
"[",
"name",
"]",
"[",
"\"path\"",
"]",
"=",
"path",
"cookie",
"[",
"name",
"]",
"[",
"\"max-age\"",
"]",
"=",
"max_age",
"return",
"cookie"
] |
Saves a state to a cookie
:type state: satosa.state.State
:type name: str
:type path: str
:type encryption_key: str
:rtype: http.cookies.SimpleCookie
:param state: The state to save
:param name: Name identifier of the cookie
:param path: Endpoint path the cookie will be associated to
:param encryption_key: Key to encrypt the state information
:return: A cookie
|
[
"Saves",
"a",
"state",
"to",
"a",
"cookie"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L26-L54
|
237,020
|
IdentityPython/SATOSA
|
src/satosa/state.py
|
cookie_to_state
|
def cookie_to_state(cookie_str, name, encryption_key):
"""
Loads a state from a cookie
:type cookie_str: str
:type name: str
:type encryption_key: str
:rtype: satosa.state.State
:param cookie_str: string representation of cookie/s
:param name: Name identifier of the cookie
:param encryption_key: Key to encrypt the state information
:return: A state
"""
try:
cookie = SimpleCookie(cookie_str)
state = State(cookie[name].value, encryption_key)
except KeyError as e:
msg_tmpl = 'No cookie named {name} in {data}'
msg = msg_tmpl.format(name=name, data=cookie_str)
logger.exception(msg)
raise SATOSAStateError(msg) from e
except ValueError as e:
msg_tmpl = 'Failed to process {name} from {data}'
msg = msg_tmpl.format(name=name, data=cookie_str)
logger.exception(msg)
raise SATOSAStateError(msg) from e
else:
msg_tmpl = 'Loading state from cookie {data}'
msg = msg_tmpl.format(data=cookie_str)
satosa_logging(logger, logging.DEBUG, msg, state)
return state
|
python
|
def cookie_to_state(cookie_str, name, encryption_key):
"""
Loads a state from a cookie
:type cookie_str: str
:type name: str
:type encryption_key: str
:rtype: satosa.state.State
:param cookie_str: string representation of cookie/s
:param name: Name identifier of the cookie
:param encryption_key: Key to encrypt the state information
:return: A state
"""
try:
cookie = SimpleCookie(cookie_str)
state = State(cookie[name].value, encryption_key)
except KeyError as e:
msg_tmpl = 'No cookie named {name} in {data}'
msg = msg_tmpl.format(name=name, data=cookie_str)
logger.exception(msg)
raise SATOSAStateError(msg) from e
except ValueError as e:
msg_tmpl = 'Failed to process {name} from {data}'
msg = msg_tmpl.format(name=name, data=cookie_str)
logger.exception(msg)
raise SATOSAStateError(msg) from e
else:
msg_tmpl = 'Loading state from cookie {data}'
msg = msg_tmpl.format(data=cookie_str)
satosa_logging(logger, logging.DEBUG, msg, state)
return state
|
[
"def",
"cookie_to_state",
"(",
"cookie_str",
",",
"name",
",",
"encryption_key",
")",
":",
"try",
":",
"cookie",
"=",
"SimpleCookie",
"(",
"cookie_str",
")",
"state",
"=",
"State",
"(",
"cookie",
"[",
"name",
"]",
".",
"value",
",",
"encryption_key",
")",
"except",
"KeyError",
"as",
"e",
":",
"msg_tmpl",
"=",
"'No cookie named {name} in {data}'",
"msg",
"=",
"msg_tmpl",
".",
"format",
"(",
"name",
"=",
"name",
",",
"data",
"=",
"cookie_str",
")",
"logger",
".",
"exception",
"(",
"msg",
")",
"raise",
"SATOSAStateError",
"(",
"msg",
")",
"from",
"e",
"except",
"ValueError",
"as",
"e",
":",
"msg_tmpl",
"=",
"'Failed to process {name} from {data}'",
"msg",
"=",
"msg_tmpl",
".",
"format",
"(",
"name",
"=",
"name",
",",
"data",
"=",
"cookie_str",
")",
"logger",
".",
"exception",
"(",
"msg",
")",
"raise",
"SATOSAStateError",
"(",
"msg",
")",
"from",
"e",
"else",
":",
"msg_tmpl",
"=",
"'Loading state from cookie {data}'",
"msg",
"=",
"msg_tmpl",
".",
"format",
"(",
"data",
"=",
"cookie_str",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"msg",
",",
"state",
")",
"return",
"state"
] |
Loads a state from a cookie
:type cookie_str: str
:type name: str
:type encryption_key: str
:rtype: satosa.state.State
:param cookie_str: string representation of cookie/s
:param name: Name identifier of the cookie
:param encryption_key: Key to encrypt the state information
:return: A state
|
[
"Loads",
"a",
"state",
"from",
"a",
"cookie"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L57-L88
|
237,021
|
IdentityPython/SATOSA
|
src/satosa/state.py
|
_AESCipher.encrypt
|
def encrypt(self, raw):
"""
Encryptes the parameter raw.
:type raw: bytes
:rtype: str
:param: bytes to be encrypted.
:return: A base 64 encoded string.
"""
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.urlsafe_b64encode(iv + cipher.encrypt(raw))
|
python
|
def encrypt(self, raw):
"""
Encryptes the parameter raw.
:type raw: bytes
:rtype: str
:param: bytes to be encrypted.
:return: A base 64 encoded string.
"""
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.urlsafe_b64encode(iv + cipher.encrypt(raw))
|
[
"def",
"encrypt",
"(",
"self",
",",
"raw",
")",
":",
"raw",
"=",
"self",
".",
"_pad",
"(",
"raw",
")",
"iv",
"=",
"Random",
".",
"new",
"(",
")",
".",
"read",
"(",
"AES",
".",
"block_size",
")",
"cipher",
"=",
"AES",
".",
"new",
"(",
"self",
".",
"key",
",",
"AES",
".",
"MODE_CBC",
",",
"iv",
")",
"return",
"base64",
".",
"urlsafe_b64encode",
"(",
"iv",
"+",
"cipher",
".",
"encrypt",
"(",
"raw",
")",
")"
] |
Encryptes the parameter raw.
:type raw: bytes
:rtype: str
:param: bytes to be encrypted.
:return: A base 64 encoded string.
|
[
"Encryptes",
"the",
"parameter",
"raw",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L109-L123
|
237,022
|
IdentityPython/SATOSA
|
src/satosa/state.py
|
_AESCipher._pad
|
def _pad(self, b):
"""
Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes
"""
return b + (self.bs - len(b) % self.bs) * chr(self.bs - len(b) % self.bs).encode("UTF-8")
|
python
|
def _pad(self, b):
"""
Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes
"""
return b + (self.bs - len(b) % self.bs) * chr(self.bs - len(b) % self.bs).encode("UTF-8")
|
[
"def",
"_pad",
"(",
"self",
",",
"b",
")",
":",
"return",
"b",
"+",
"(",
"self",
".",
"bs",
"-",
"len",
"(",
"b",
")",
"%",
"self",
".",
"bs",
")",
"*",
"chr",
"(",
"self",
".",
"bs",
"-",
"len",
"(",
"b",
")",
"%",
"self",
".",
"bs",
")",
".",
"encode",
"(",
"\"UTF-8\"",
")"
] |
Will padd the param to be of the correct length for the encryption alg.
:type b: bytes
:rtype: bytes
|
[
"Will",
"padd",
"the",
"param",
"to",
"be",
"of",
"the",
"correct",
"length",
"for",
"the",
"encryption",
"alg",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L140-L147
|
237,023
|
IdentityPython/SATOSA
|
src/satosa/state.py
|
State.urlstate
|
def urlstate(self, encryption_key):
"""
Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state.
"""
lzma = LZMACompressor()
urlstate_data = json.dumps(self._state_dict)
urlstate_data = lzma.compress(urlstate_data.encode("UTF-8"))
urlstate_data += lzma.flush()
urlstate_data = _AESCipher(encryption_key).encrypt(urlstate_data)
lzma = LZMACompressor()
urlstate_data = lzma.compress(urlstate_data)
urlstate_data += lzma.flush()
urlstate_data = base64.urlsafe_b64encode(urlstate_data)
return urlstate_data.decode("utf-8")
|
python
|
def urlstate(self, encryption_key):
"""
Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state.
"""
lzma = LZMACompressor()
urlstate_data = json.dumps(self._state_dict)
urlstate_data = lzma.compress(urlstate_data.encode("UTF-8"))
urlstate_data += lzma.flush()
urlstate_data = _AESCipher(encryption_key).encrypt(urlstate_data)
lzma = LZMACompressor()
urlstate_data = lzma.compress(urlstate_data)
urlstate_data += lzma.flush()
urlstate_data = base64.urlsafe_b64encode(urlstate_data)
return urlstate_data.decode("utf-8")
|
[
"def",
"urlstate",
"(",
"self",
",",
"encryption_key",
")",
":",
"lzma",
"=",
"LZMACompressor",
"(",
")",
"urlstate_data",
"=",
"json",
".",
"dumps",
"(",
"self",
".",
"_state_dict",
")",
"urlstate_data",
"=",
"lzma",
".",
"compress",
"(",
"urlstate_data",
".",
"encode",
"(",
"\"UTF-8\"",
")",
")",
"urlstate_data",
"+=",
"lzma",
".",
"flush",
"(",
")",
"urlstate_data",
"=",
"_AESCipher",
"(",
"encryption_key",
")",
".",
"encrypt",
"(",
"urlstate_data",
")",
"lzma",
"=",
"LZMACompressor",
"(",
")",
"urlstate_data",
"=",
"lzma",
".",
"compress",
"(",
"urlstate_data",
")",
"urlstate_data",
"+=",
"lzma",
".",
"flush",
"(",
")",
"urlstate_data",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"urlstate_data",
")",
"return",
"urlstate_data",
".",
"decode",
"(",
"\"utf-8\"",
")"
] |
Will return a url safe representation of the state.
:type encryption_key: Key used for encryption.
:rtype: str
:return: Url representation av of the state.
|
[
"Will",
"return",
"a",
"url",
"safe",
"representation",
"of",
"the",
"state",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L235-L253
|
237,024
|
IdentityPython/SATOSA
|
src/satosa/state.py
|
State.copy
|
def copy(self):
"""
Returns a deepcopy of the state
:rtype: satosa.state.State
:return: A copy of the state
"""
state_copy = State()
state_copy._state_dict = copy.deepcopy(self._state_dict)
return state_copy
|
python
|
def copy(self):
"""
Returns a deepcopy of the state
:rtype: satosa.state.State
:return: A copy of the state
"""
state_copy = State()
state_copy._state_dict = copy.deepcopy(self._state_dict)
return state_copy
|
[
"def",
"copy",
"(",
"self",
")",
":",
"state_copy",
"=",
"State",
"(",
")",
"state_copy",
".",
"_state_dict",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_state_dict",
")",
"return",
"state_copy"
] |
Returns a deepcopy of the state
:rtype: satosa.state.State
:return: A copy of the state
|
[
"Returns",
"a",
"deepcopy",
"of",
"the",
"state"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/state.py#L255-L265
|
237,025
|
IdentityPython/SATOSA
|
src/satosa/deprecated.py
|
saml_name_id_format_to_hash_type
|
def saml_name_id_format_to_hash_type(name_format):
"""
Translate pySAML2 name format to satosa format
:type name_format: str
:rtype: satosa.internal_data.UserIdHashType
:param name_format: SAML2 name format
:return: satosa format
"""
msg = "saml_name_id_format_to_hash_type is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
name_id_format_to_hash_type = {
NAMEID_FORMAT_TRANSIENT: UserIdHashType.transient,
NAMEID_FORMAT_PERSISTENT: UserIdHashType.persistent,
NAMEID_FORMAT_EMAILADDRESS: UserIdHashType.emailaddress,
NAMEID_FORMAT_UNSPECIFIED: UserIdHashType.unspecified,
}
return name_id_format_to_hash_type.get(
name_format, UserIdHashType.transient
)
|
python
|
def saml_name_id_format_to_hash_type(name_format):
"""
Translate pySAML2 name format to satosa format
:type name_format: str
:rtype: satosa.internal_data.UserIdHashType
:param name_format: SAML2 name format
:return: satosa format
"""
msg = "saml_name_id_format_to_hash_type is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
name_id_format_to_hash_type = {
NAMEID_FORMAT_TRANSIENT: UserIdHashType.transient,
NAMEID_FORMAT_PERSISTENT: UserIdHashType.persistent,
NAMEID_FORMAT_EMAILADDRESS: UserIdHashType.emailaddress,
NAMEID_FORMAT_UNSPECIFIED: UserIdHashType.unspecified,
}
return name_id_format_to_hash_type.get(
name_format, UserIdHashType.transient
)
|
[
"def",
"saml_name_id_format_to_hash_type",
"(",
"name_format",
")",
":",
"msg",
"=",
"\"saml_name_id_format_to_hash_type is deprecated and will be removed.\"",
"_warnings",
".",
"warn",
"(",
"msg",
",",
"DeprecationWarning",
")",
"name_id_format_to_hash_type",
"=",
"{",
"NAMEID_FORMAT_TRANSIENT",
":",
"UserIdHashType",
".",
"transient",
",",
"NAMEID_FORMAT_PERSISTENT",
":",
"UserIdHashType",
".",
"persistent",
",",
"NAMEID_FORMAT_EMAILADDRESS",
":",
"UserIdHashType",
".",
"emailaddress",
",",
"NAMEID_FORMAT_UNSPECIFIED",
":",
"UserIdHashType",
".",
"unspecified",
",",
"}",
"return",
"name_id_format_to_hash_type",
".",
"get",
"(",
"name_format",
",",
"UserIdHashType",
".",
"transient",
")"
] |
Translate pySAML2 name format to satosa format
:type name_format: str
:rtype: satosa.internal_data.UserIdHashType
:param name_format: SAML2 name format
:return: satosa format
|
[
"Translate",
"pySAML2",
"name",
"format",
"to",
"satosa",
"format"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L204-L225
|
237,026
|
IdentityPython/SATOSA
|
src/satosa/deprecated.py
|
hash_type_to_saml_name_id_format
|
def hash_type_to_saml_name_id_format(hash_type):
"""
Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format
"""
msg = "hash_type_to_saml_name_id_format is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
hash_type_to_name_id_format = {
UserIdHashType.transient: NAMEID_FORMAT_TRANSIENT,
UserIdHashType.persistent: NAMEID_FORMAT_PERSISTENT,
UserIdHashType.emailaddress: NAMEID_FORMAT_EMAILADDRESS,
UserIdHashType.unspecified: NAMEID_FORMAT_UNSPECIFIED,
}
return hash_type_to_name_id_format.get(hash_type, NAMEID_FORMAT_PERSISTENT)
|
python
|
def hash_type_to_saml_name_id_format(hash_type):
"""
Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format
"""
msg = "hash_type_to_saml_name_id_format is deprecated and will be removed."
_warnings.warn(msg, DeprecationWarning)
hash_type_to_name_id_format = {
UserIdHashType.transient: NAMEID_FORMAT_TRANSIENT,
UserIdHashType.persistent: NAMEID_FORMAT_PERSISTENT,
UserIdHashType.emailaddress: NAMEID_FORMAT_EMAILADDRESS,
UserIdHashType.unspecified: NAMEID_FORMAT_UNSPECIFIED,
}
return hash_type_to_name_id_format.get(hash_type, NAMEID_FORMAT_PERSISTENT)
|
[
"def",
"hash_type_to_saml_name_id_format",
"(",
"hash_type",
")",
":",
"msg",
"=",
"\"hash_type_to_saml_name_id_format is deprecated and will be removed.\"",
"_warnings",
".",
"warn",
"(",
"msg",
",",
"DeprecationWarning",
")",
"hash_type_to_name_id_format",
"=",
"{",
"UserIdHashType",
".",
"transient",
":",
"NAMEID_FORMAT_TRANSIENT",
",",
"UserIdHashType",
".",
"persistent",
":",
"NAMEID_FORMAT_PERSISTENT",
",",
"UserIdHashType",
".",
"emailaddress",
":",
"NAMEID_FORMAT_EMAILADDRESS",
",",
"UserIdHashType",
".",
"unspecified",
":",
"NAMEID_FORMAT_UNSPECIFIED",
",",
"}",
"return",
"hash_type_to_name_id_format",
".",
"get",
"(",
"hash_type",
",",
"NAMEID_FORMAT_PERSISTENT",
")"
] |
Translate satosa format to pySAML2 name format
:type hash_type: satosa.internal_data.UserIdHashType
:rtype: str
:param hash_type: satosa format
:return: pySAML2 name format
|
[
"Translate",
"satosa",
"format",
"to",
"pySAML2",
"name",
"format"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L228-L247
|
237,027
|
IdentityPython/SATOSA
|
src/satosa/deprecated.py
|
UserIdHasher.save_state
|
def save_state(internal_request, state):
"""
Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state
"""
state_data = {"hash_type": internal_request.user_id_hash_type}
state[UserIdHasher.STATE_KEY] = state_data
|
python
|
def save_state(internal_request, state):
"""
Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state
"""
state_data = {"hash_type": internal_request.user_id_hash_type}
state[UserIdHasher.STATE_KEY] = state_data
|
[
"def",
"save_state",
"(",
"internal_request",
",",
"state",
")",
":",
"state_data",
"=",
"{",
"\"hash_type\"",
":",
"internal_request",
".",
"user_id_hash_type",
"}",
"state",
"[",
"UserIdHasher",
".",
"STATE_KEY",
"]",
"=",
"state_data"
] |
Saves all necessary information needed by the UserIdHasher
:type internal_request: satosa.internal_data.InternalRequest
:param internal_request: The request
:param state: The current state
|
[
"Saves",
"all",
"necessary",
"information",
"needed",
"by",
"the",
"UserIdHasher"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L122-L132
|
237,028
|
IdentityPython/SATOSA
|
src/satosa/deprecated.py
|
UserIdHasher.hash_id
|
def hash_id(salt, user_id, requester, state):
"""
Sets a user id to the internal_response,
in the format specified by the internal response
:type salt: str
:type user_id: str
:type requester: str
:type state: satosa.state.State
:rtype: str
:param salt: A salt string for the ID hashing
:param user_id: the user id
:param user_id_hash_type: Hashing type
:param state: The current state
:return: the internal_response containing the hashed user ID
"""
hash_type_to_format = {
NAMEID_FORMAT_TRANSIENT: "{id}{req}{time}",
NAMEID_FORMAT_PERSISTENT: "{id}{req}",
"pairwise": "{id}{req}",
"public": "{id}",
NAMEID_FORMAT_EMAILADDRESS: "{id}",
NAMEID_FORMAT_UNSPECIFIED: "{id}",
}
format_args = {
"id": user_id,
"req": requester,
"time": datetime.datetime.utcnow().timestamp(),
}
hash_type = UserIdHasher.hash_type(state)
try:
fmt = hash_type_to_format[hash_type]
except KeyError as e:
raise ValueError("Unknown hash type: {}".format(hash_type)) from e
else:
user_id = fmt.format(**format_args)
hasher = (
(lambda salt, value: value)
if hash_type
in [NAMEID_FORMAT_EMAILADDRESS, NAMEID_FORMAT_UNSPECIFIED]
else util.hash_data
)
return hasher(salt, user_id)
|
python
|
def hash_id(salt, user_id, requester, state):
"""
Sets a user id to the internal_response,
in the format specified by the internal response
:type salt: str
:type user_id: str
:type requester: str
:type state: satosa.state.State
:rtype: str
:param salt: A salt string for the ID hashing
:param user_id: the user id
:param user_id_hash_type: Hashing type
:param state: The current state
:return: the internal_response containing the hashed user ID
"""
hash_type_to_format = {
NAMEID_FORMAT_TRANSIENT: "{id}{req}{time}",
NAMEID_FORMAT_PERSISTENT: "{id}{req}",
"pairwise": "{id}{req}",
"public": "{id}",
NAMEID_FORMAT_EMAILADDRESS: "{id}",
NAMEID_FORMAT_UNSPECIFIED: "{id}",
}
format_args = {
"id": user_id,
"req": requester,
"time": datetime.datetime.utcnow().timestamp(),
}
hash_type = UserIdHasher.hash_type(state)
try:
fmt = hash_type_to_format[hash_type]
except KeyError as e:
raise ValueError("Unknown hash type: {}".format(hash_type)) from e
else:
user_id = fmt.format(**format_args)
hasher = (
(lambda salt, value: value)
if hash_type
in [NAMEID_FORMAT_EMAILADDRESS, NAMEID_FORMAT_UNSPECIFIED]
else util.hash_data
)
return hasher(salt, user_id)
|
[
"def",
"hash_id",
"(",
"salt",
",",
"user_id",
",",
"requester",
",",
"state",
")",
":",
"hash_type_to_format",
"=",
"{",
"NAMEID_FORMAT_TRANSIENT",
":",
"\"{id}{req}{time}\"",
",",
"NAMEID_FORMAT_PERSISTENT",
":",
"\"{id}{req}\"",
",",
"\"pairwise\"",
":",
"\"{id}{req}\"",
",",
"\"public\"",
":",
"\"{id}\"",
",",
"NAMEID_FORMAT_EMAILADDRESS",
":",
"\"{id}\"",
",",
"NAMEID_FORMAT_UNSPECIFIED",
":",
"\"{id}\"",
",",
"}",
"format_args",
"=",
"{",
"\"id\"",
":",
"user_id",
",",
"\"req\"",
":",
"requester",
",",
"\"time\"",
":",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timestamp",
"(",
")",
",",
"}",
"hash_type",
"=",
"UserIdHasher",
".",
"hash_type",
"(",
"state",
")",
"try",
":",
"fmt",
"=",
"hash_type_to_format",
"[",
"hash_type",
"]",
"except",
"KeyError",
"as",
"e",
":",
"raise",
"ValueError",
"(",
"\"Unknown hash type: {}\"",
".",
"format",
"(",
"hash_type",
")",
")",
"from",
"e",
"else",
":",
"user_id",
"=",
"fmt",
".",
"format",
"(",
"*",
"*",
"format_args",
")",
"hasher",
"=",
"(",
"(",
"lambda",
"salt",
",",
"value",
":",
"value",
")",
"if",
"hash_type",
"in",
"[",
"NAMEID_FORMAT_EMAILADDRESS",
",",
"NAMEID_FORMAT_UNSPECIFIED",
"]",
"else",
"util",
".",
"hash_data",
")",
"return",
"hasher",
"(",
"salt",
",",
"user_id",
")"
] |
Sets a user id to the internal_response,
in the format specified by the internal response
:type salt: str
:type user_id: str
:type requester: str
:type state: satosa.state.State
:rtype: str
:param salt: A salt string for the ID hashing
:param user_id: the user id
:param user_id_hash_type: Hashing type
:param state: The current state
:return: the internal_response containing the hashed user ID
|
[
"Sets",
"a",
"user",
"id",
"to",
"the",
"internal_response",
"in",
"the",
"format",
"specified",
"by",
"the",
"internal",
"response"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/deprecated.py#L155-L201
|
237,029
|
IdentityPython/SATOSA
|
src/satosa/plugin_loader.py
|
load_backends
|
def load_backends(config, callback, internal_attributes):
"""
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.base.BackendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the backend after the authentication is done.
:return: A list of backend modules
"""
backend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["BACKEND_MODULES"], backend_filter,
config["BASE"], internal_attributes, callback)
logger.info("Setup backends: %s" % [backend.name for backend in backend_modules])
return backend_modules
|
python
|
def load_backends(config, callback, internal_attributes):
"""
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.base.BackendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the backend after the authentication is done.
:return: A list of backend modules
"""
backend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["BACKEND_MODULES"], backend_filter,
config["BASE"], internal_attributes, callback)
logger.info("Setup backends: %s" % [backend.name for backend in backend_modules])
return backend_modules
|
[
"def",
"load_backends",
"(",
"config",
",",
"callback",
",",
"internal_attributes",
")",
":",
"backend_modules",
"=",
"_load_plugins",
"(",
"config",
".",
"get",
"(",
"\"CUSTOM_PLUGIN_MODULE_PATHS\"",
")",
",",
"config",
"[",
"\"BACKEND_MODULES\"",
"]",
",",
"backend_filter",
",",
"config",
"[",
"\"BASE\"",
"]",
",",
"internal_attributes",
",",
"callback",
")",
"logger",
".",
"info",
"(",
"\"Setup backends: %s\"",
"%",
"[",
"backend",
".",
"name",
"for",
"backend",
"in",
"backend_modules",
"]",
")",
"return",
"backend_modules"
] |
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.base.BackendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the backend after the authentication is done.
:return: A list of backend modules
|
[
"Load",
"all",
"backend",
"modules",
"specified",
"in",
"the",
"config"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/plugin_loader.py#L30-L47
|
237,030
|
IdentityPython/SATOSA
|
src/satosa/plugin_loader.py
|
load_frontends
|
def load_frontends(config, callback, internal_attributes):
"""
Load all frontend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.frontends.base.FrontendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the frontend after the authentication request
has been processed.
:return: A list of frontend modules
"""
frontend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["FRONTEND_MODULES"],
frontend_filter, config["BASE"], internal_attributes, callback)
logger.info("Setup frontends: %s" % [frontend.name for frontend in frontend_modules])
return frontend_modules
|
python
|
def load_frontends(config, callback, internal_attributes):
"""
Load all frontend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.frontends.base.FrontendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the frontend after the authentication request
has been processed.
:return: A list of frontend modules
"""
frontend_modules = _load_plugins(config.get("CUSTOM_PLUGIN_MODULE_PATHS"), config["FRONTEND_MODULES"],
frontend_filter, config["BASE"], internal_attributes, callback)
logger.info("Setup frontends: %s" % [frontend.name for frontend in frontend_modules])
return frontend_modules
|
[
"def",
"load_frontends",
"(",
"config",
",",
"callback",
",",
"internal_attributes",
")",
":",
"frontend_modules",
"=",
"_load_plugins",
"(",
"config",
".",
"get",
"(",
"\"CUSTOM_PLUGIN_MODULE_PATHS\"",
")",
",",
"config",
"[",
"\"FRONTEND_MODULES\"",
"]",
",",
"frontend_filter",
",",
"config",
"[",
"\"BASE\"",
"]",
",",
"internal_attributes",
",",
"callback",
")",
"logger",
".",
"info",
"(",
"\"Setup frontends: %s\"",
"%",
"[",
"frontend",
".",
"name",
"for",
"frontend",
"in",
"frontend_modules",
"]",
")",
"return",
"frontend_modules"
] |
Load all frontend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.frontends.base.FrontendModule]
:param config: The configuration of the satosa proxy
:param callback: Function that will be called by the frontend after the authentication request
has been processed.
:return: A list of frontend modules
|
[
"Load",
"all",
"frontend",
"modules",
"specified",
"in",
"the",
"config"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/plugin_loader.py#L50-L68
|
237,031
|
IdentityPython/SATOSA
|
src/satosa/plugin_loader.py
|
_micro_service_filter
|
def _micro_service_filter(cls):
"""
Will only give a find on classes that is a subclass of MicroService, with the exception that
the class is not allowed to be a direct ResponseMicroService or RequestMicroService.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
is_microservice_module = issubclass(cls, MicroService)
is_correct_subclass = cls != MicroService and cls != ResponseMicroService and cls != RequestMicroService
return is_microservice_module and is_correct_subclass
|
python
|
def _micro_service_filter(cls):
"""
Will only give a find on classes that is a subclass of MicroService, with the exception that
the class is not allowed to be a direct ResponseMicroService or RequestMicroService.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
"""
is_microservice_module = issubclass(cls, MicroService)
is_correct_subclass = cls != MicroService and cls != ResponseMicroService and cls != RequestMicroService
return is_microservice_module and is_correct_subclass
|
[
"def",
"_micro_service_filter",
"(",
"cls",
")",
":",
"is_microservice_module",
"=",
"issubclass",
"(",
"cls",
",",
"MicroService",
")",
"is_correct_subclass",
"=",
"cls",
"!=",
"MicroService",
"and",
"cls",
"!=",
"ResponseMicroService",
"and",
"cls",
"!=",
"RequestMicroService",
"return",
"is_microservice_module",
"and",
"is_correct_subclass"
] |
Will only give a find on classes that is a subclass of MicroService, with the exception that
the class is not allowed to be a direct ResponseMicroService or RequestMicroService.
:type cls: type
:rtype: bool
:param cls: A class object
:return: True if match, else false
|
[
"Will",
"only",
"give",
"a",
"find",
"on",
"classes",
"that",
"is",
"a",
"subclass",
"of",
"MicroService",
"with",
"the",
"exception",
"that",
"the",
"class",
"is",
"not",
"allowed",
"to",
"be",
"a",
"direct",
"ResponseMicroService",
"or",
"RequestMicroService",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/plugin_loader.py#L97-L110
|
237,032
|
IdentityPython/SATOSA
|
src/satosa/plugin_loader.py
|
_load_plugins
|
def _load_plugins(plugin_paths, plugins, plugin_filter, base_url, internal_attributes, callback):
"""
Loads endpoint plugins
:type plugin_paths: list[str]
:type plugins: list[str]
:type plugin_filter: (type | str) -> bool
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype list[satosa.plugin_base.endpoint.InterfaceModulePlugin]
:param plugin_paths: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param plugin_filter: Filter what to load from the module file
:param args: Arguments to the plugin
:return: A list with all the loaded plugins
"""
loaded_plugin_modules = []
with prepend_to_import_path(plugin_paths):
for plugin_config in plugins:
try:
module_class = _load_endpoint_module(plugin_config, plugin_filter)
except SATOSAConfigurationError as e:
raise SATOSAConfigurationError("Configuration error in {}".format(json.dumps(plugin_config))) from e
if module_class:
module_config = _replace_variables_in_plugin_module_config(plugin_config["config"], base_url,
plugin_config["name"])
instance = module_class(callback, internal_attributes, module_config, base_url,
plugin_config["name"])
loaded_plugin_modules.append(instance)
return loaded_plugin_modules
|
python
|
def _load_plugins(plugin_paths, plugins, plugin_filter, base_url, internal_attributes, callback):
"""
Loads endpoint plugins
:type plugin_paths: list[str]
:type plugins: list[str]
:type plugin_filter: (type | str) -> bool
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype list[satosa.plugin_base.endpoint.InterfaceModulePlugin]
:param plugin_paths: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param plugin_filter: Filter what to load from the module file
:param args: Arguments to the plugin
:return: A list with all the loaded plugins
"""
loaded_plugin_modules = []
with prepend_to_import_path(plugin_paths):
for plugin_config in plugins:
try:
module_class = _load_endpoint_module(plugin_config, plugin_filter)
except SATOSAConfigurationError as e:
raise SATOSAConfigurationError("Configuration error in {}".format(json.dumps(plugin_config))) from e
if module_class:
module_config = _replace_variables_in_plugin_module_config(plugin_config["config"], base_url,
plugin_config["name"])
instance = module_class(callback, internal_attributes, module_config, base_url,
plugin_config["name"])
loaded_plugin_modules.append(instance)
return loaded_plugin_modules
|
[
"def",
"_load_plugins",
"(",
"plugin_paths",
",",
"plugins",
",",
"plugin_filter",
",",
"base_url",
",",
"internal_attributes",
",",
"callback",
")",
":",
"loaded_plugin_modules",
"=",
"[",
"]",
"with",
"prepend_to_import_path",
"(",
"plugin_paths",
")",
":",
"for",
"plugin_config",
"in",
"plugins",
":",
"try",
":",
"module_class",
"=",
"_load_endpoint_module",
"(",
"plugin_config",
",",
"plugin_filter",
")",
"except",
"SATOSAConfigurationError",
"as",
"e",
":",
"raise",
"SATOSAConfigurationError",
"(",
"\"Configuration error in {}\"",
".",
"format",
"(",
"json",
".",
"dumps",
"(",
"plugin_config",
")",
")",
")",
"from",
"e",
"if",
"module_class",
":",
"module_config",
"=",
"_replace_variables_in_plugin_module_config",
"(",
"plugin_config",
"[",
"\"config\"",
"]",
",",
"base_url",
",",
"plugin_config",
"[",
"\"name\"",
"]",
")",
"instance",
"=",
"module_class",
"(",
"callback",
",",
"internal_attributes",
",",
"module_config",
",",
"base_url",
",",
"plugin_config",
"[",
"\"name\"",
"]",
")",
"loaded_plugin_modules",
".",
"append",
"(",
"instance",
")",
"return",
"loaded_plugin_modules"
] |
Loads endpoint plugins
:type plugin_paths: list[str]
:type plugins: list[str]
:type plugin_filter: (type | str) -> bool
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype list[satosa.plugin_base.endpoint.InterfaceModulePlugin]
:param plugin_paths: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param plugin_filter: Filter what to load from the module file
:param args: Arguments to the plugin
:return: A list with all the loaded plugins
|
[
"Loads",
"endpoint",
"plugins"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/plugin_loader.py#L151-L181
|
237,033
|
IdentityPython/SATOSA
|
src/satosa/scripts/satosa_saml_metadata.py
|
create_and_write_saml_metadata
|
def create_and_write_saml_metadata(proxy_conf, key, cert, dir, valid, split_frontend_metadata=False,
split_backend_metadata=False):
"""
Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT.
"""
satosa_config = SATOSAConfig(proxy_conf)
secc = _get_security_context(key, cert)
frontend_entities, backend_entities = create_entity_descriptors(satosa_config)
output = []
if frontend_entities:
if split_frontend_metadata:
output.extend(_create_split_entity_descriptors(frontend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(frontend_entities, secc, valid, "frontend.xml"))
if backend_entities:
if split_backend_metadata:
output.extend(_create_split_entity_descriptors(backend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(backend_entities, secc, valid, "backend.xml"))
for metadata, filename in output:
path = os.path.join(dir, filename)
print("Writing metadata to '{}'".format(path))
with open(path, "w") as f:
f.write(metadata)
|
python
|
def create_and_write_saml_metadata(proxy_conf, key, cert, dir, valid, split_frontend_metadata=False,
split_backend_metadata=False):
"""
Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT.
"""
satosa_config = SATOSAConfig(proxy_conf)
secc = _get_security_context(key, cert)
frontend_entities, backend_entities = create_entity_descriptors(satosa_config)
output = []
if frontend_entities:
if split_frontend_metadata:
output.extend(_create_split_entity_descriptors(frontend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(frontend_entities, secc, valid, "frontend.xml"))
if backend_entities:
if split_backend_metadata:
output.extend(_create_split_entity_descriptors(backend_entities, secc, valid))
else:
output.extend(_create_merged_entities_descriptors(backend_entities, secc, valid, "backend.xml"))
for metadata, filename in output:
path = os.path.join(dir, filename)
print("Writing metadata to '{}'".format(path))
with open(path, "w") as f:
f.write(metadata)
|
[
"def",
"create_and_write_saml_metadata",
"(",
"proxy_conf",
",",
"key",
",",
"cert",
",",
"dir",
",",
"valid",
",",
"split_frontend_metadata",
"=",
"False",
",",
"split_backend_metadata",
"=",
"False",
")",
":",
"satosa_config",
"=",
"SATOSAConfig",
"(",
"proxy_conf",
")",
"secc",
"=",
"_get_security_context",
"(",
"key",
",",
"cert",
")",
"frontend_entities",
",",
"backend_entities",
"=",
"create_entity_descriptors",
"(",
"satosa_config",
")",
"output",
"=",
"[",
"]",
"if",
"frontend_entities",
":",
"if",
"split_frontend_metadata",
":",
"output",
".",
"extend",
"(",
"_create_split_entity_descriptors",
"(",
"frontend_entities",
",",
"secc",
",",
"valid",
")",
")",
"else",
":",
"output",
".",
"extend",
"(",
"_create_merged_entities_descriptors",
"(",
"frontend_entities",
",",
"secc",
",",
"valid",
",",
"\"frontend.xml\"",
")",
")",
"if",
"backend_entities",
":",
"if",
"split_backend_metadata",
":",
"output",
".",
"extend",
"(",
"_create_split_entity_descriptors",
"(",
"backend_entities",
",",
"secc",
",",
"valid",
")",
")",
"else",
":",
"output",
".",
"extend",
"(",
"_create_merged_entities_descriptors",
"(",
"backend_entities",
",",
"secc",
",",
"valid",
",",
"\"backend.xml\"",
")",
")",
"for",
"metadata",
",",
"filename",
"in",
"output",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"filename",
")",
"print",
"(",
"\"Writing metadata to '{}'\"",
".",
"format",
"(",
"path",
")",
")",
"with",
"open",
"(",
"path",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"metadata",
")"
] |
Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT.
|
[
"Generates",
"SAML",
"metadata",
"for",
"the",
"given",
"PROXY_CONF",
"signed",
"with",
"the",
"given",
"KEY",
"and",
"associated",
"CERT",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/scripts/satosa_saml_metadata.py#L38-L63
|
237,034
|
IdentityPython/SATOSA
|
src/satosa/micro_services/account_linking.py
|
AccountLinking._handle_al_response
|
def _handle_al_response(self, context):
"""
Endpoint for handling account linking service response. When getting here
user might have approved or rejected linking their account
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
saved_state = context.state[self.name]
internal_response = InternalData.from_dict(saved_state)
#subject_id here is the linked id , not the facebook one, Figure out what to do
status_code, message = self._get_uuid(context, internal_response.auth_info.issuer, internal_response.attributes['issuer_user_id'])
if status_code == 200:
satosa_logging(logger, logging.INFO, "issuer/id pair is linked in AL service",
context.state)
internal_response.subject_id = message
if self.id_to_attr:
internal_response.attributes[self.id_to_attr] = [message]
del context.state[self.name]
return super().process(context, internal_response)
else:
# User selected not to link their accounts, so the internal.response.subject_id is based on the
# issuers id/sub which is fine
satosa_logging(logger, logging.INFO, "User selected to not link their identity in AL service",
context.state)
del context.state[self.name]
return super().process(context, internal_response)
|
python
|
def _handle_al_response(self, context):
"""
Endpoint for handling account linking service response. When getting here
user might have approved or rejected linking their account
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
saved_state = context.state[self.name]
internal_response = InternalData.from_dict(saved_state)
#subject_id here is the linked id , not the facebook one, Figure out what to do
status_code, message = self._get_uuid(context, internal_response.auth_info.issuer, internal_response.attributes['issuer_user_id'])
if status_code == 200:
satosa_logging(logger, logging.INFO, "issuer/id pair is linked in AL service",
context.state)
internal_response.subject_id = message
if self.id_to_attr:
internal_response.attributes[self.id_to_attr] = [message]
del context.state[self.name]
return super().process(context, internal_response)
else:
# User selected not to link their accounts, so the internal.response.subject_id is based on the
# issuers id/sub which is fine
satosa_logging(logger, logging.INFO, "User selected to not link their identity in AL service",
context.state)
del context.state[self.name]
return super().process(context, internal_response)
|
[
"def",
"_handle_al_response",
"(",
"self",
",",
"context",
")",
":",
"saved_state",
"=",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"internal_response",
"=",
"InternalData",
".",
"from_dict",
"(",
"saved_state",
")",
"#subject_id here is the linked id , not the facebook one, Figure out what to do",
"status_code",
",",
"message",
"=",
"self",
".",
"_get_uuid",
"(",
"context",
",",
"internal_response",
".",
"auth_info",
".",
"issuer",
",",
"internal_response",
".",
"attributes",
"[",
"'issuer_user_id'",
"]",
")",
"if",
"status_code",
"==",
"200",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"issuer/id pair is linked in AL service\"",
",",
"context",
".",
"state",
")",
"internal_response",
".",
"subject_id",
"=",
"message",
"if",
"self",
".",
"id_to_attr",
":",
"internal_response",
".",
"attributes",
"[",
"self",
".",
"id_to_attr",
"]",
"=",
"[",
"message",
"]",
"del",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"return",
"super",
"(",
")",
".",
"process",
"(",
"context",
",",
"internal_response",
")",
"else",
":",
"# User selected not to link their accounts, so the internal.response.subject_id is based on the",
"# issuers id/sub which is fine",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"User selected to not link their identity in AL service\"",
",",
"context",
".",
"state",
")",
"del",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"return",
"super",
"(",
")",
".",
"process",
"(",
"context",
",",
"internal_response",
")"
] |
Endpoint for handling account linking service response. When getting here
user might have approved or rejected linking their account
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
|
[
"Endpoint",
"for",
"handling",
"account",
"linking",
"service",
"response",
".",
"When",
"getting",
"here",
"user",
"might",
"have",
"approved",
"or",
"rejected",
"linking",
"their",
"account"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/account_linking.py#L38-L70
|
237,035
|
IdentityPython/SATOSA
|
src/satosa/micro_services/account_linking.py
|
AccountLinking.process
|
def process(self, context, internal_response):
"""
Manage account linking and recovery
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context:
:param internal_response:
:return: response
:
"""
status_code, message = self._get_uuid(context, internal_response.auth_info.issuer, internal_response.subject_id)
data = {
"issuer": internal_response.auth_info.issuer,
"redirect_endpoint": "%s/account_linking%s" % (self.base_url, self.endpoint)
}
# Store the issuer subject_id/sub because we'll need it in handle_al_response
internal_response.attributes['issuer_user_id'] = internal_response.subject_id
if status_code == 200:
satosa_logging(logger, logging.INFO, "issuer/id pair is linked in AL service",
context.state)
internal_response.subject_id = message
data['user_id'] = message
if self.id_to_attr:
internal_response.attributes[self.id_to_attr] = [message]
else:
satosa_logging(logger, logging.INFO, "issuer/id pair is not linked in AL service. Got a ticket",
context.state)
data['ticket'] = message
jws = JWS(json.dumps(data), alg=self.signing_key.alg).sign_compact([self.signing_key])
context.state[self.name] = internal_response.to_dict()
return Redirect("%s/%s" % (self.redirect_url, jws))
|
python
|
def process(self, context, internal_response):
"""
Manage account linking and recovery
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context:
:param internal_response:
:return: response
:
"""
status_code, message = self._get_uuid(context, internal_response.auth_info.issuer, internal_response.subject_id)
data = {
"issuer": internal_response.auth_info.issuer,
"redirect_endpoint": "%s/account_linking%s" % (self.base_url, self.endpoint)
}
# Store the issuer subject_id/sub because we'll need it in handle_al_response
internal_response.attributes['issuer_user_id'] = internal_response.subject_id
if status_code == 200:
satosa_logging(logger, logging.INFO, "issuer/id pair is linked in AL service",
context.state)
internal_response.subject_id = message
data['user_id'] = message
if self.id_to_attr:
internal_response.attributes[self.id_to_attr] = [message]
else:
satosa_logging(logger, logging.INFO, "issuer/id pair is not linked in AL service. Got a ticket",
context.state)
data['ticket'] = message
jws = JWS(json.dumps(data), alg=self.signing_key.alg).sign_compact([self.signing_key])
context.state[self.name] = internal_response.to_dict()
return Redirect("%s/%s" % (self.redirect_url, jws))
|
[
"def",
"process",
"(",
"self",
",",
"context",
",",
"internal_response",
")",
":",
"status_code",
",",
"message",
"=",
"self",
".",
"_get_uuid",
"(",
"context",
",",
"internal_response",
".",
"auth_info",
".",
"issuer",
",",
"internal_response",
".",
"subject_id",
")",
"data",
"=",
"{",
"\"issuer\"",
":",
"internal_response",
".",
"auth_info",
".",
"issuer",
",",
"\"redirect_endpoint\"",
":",
"\"%s/account_linking%s\"",
"%",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"endpoint",
")",
"}",
"# Store the issuer subject_id/sub because we'll need it in handle_al_response",
"internal_response",
".",
"attributes",
"[",
"'issuer_user_id'",
"]",
"=",
"internal_response",
".",
"subject_id",
"if",
"status_code",
"==",
"200",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"issuer/id pair is linked in AL service\"",
",",
"context",
".",
"state",
")",
"internal_response",
".",
"subject_id",
"=",
"message",
"data",
"[",
"'user_id'",
"]",
"=",
"message",
"if",
"self",
".",
"id_to_attr",
":",
"internal_response",
".",
"attributes",
"[",
"self",
".",
"id_to_attr",
"]",
"=",
"[",
"message",
"]",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"issuer/id pair is not linked in AL service. Got a ticket\"",
",",
"context",
".",
"state",
")",
"data",
"[",
"'ticket'",
"]",
"=",
"message",
"jws",
"=",
"JWS",
"(",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"alg",
"=",
"self",
".",
"signing_key",
".",
"alg",
")",
".",
"sign_compact",
"(",
"[",
"self",
".",
"signing_key",
"]",
")",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"=",
"internal_response",
".",
"to_dict",
"(",
")",
"return",
"Redirect",
"(",
"\"%s/%s\"",
"%",
"(",
"self",
".",
"redirect_url",
",",
"jws",
")",
")"
] |
Manage account linking and recovery
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context:
:param internal_response:
:return: response
:
|
[
"Manage",
"account",
"linking",
"and",
"recovery"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/micro_services/account_linking.py#L73-L109
|
237,036
|
IdentityPython/SATOSA
|
src/satosa/routing.py
|
ModuleRouter.backend_routing
|
def backend_routing(self, context):
"""
Returns the targeted backend and an updated state
:type context: satosa.context.Context
:rtype satosa.backends.base.BackendModule
:param context: The request context
:return: backend
"""
satosa_logging(logger, logging.DEBUG, "Routing to backend: %s " % context.target_backend, context.state)
backend = self.backends[context.target_backend]["instance"]
context.state[STATE_KEY] = context.target_frontend
return backend
|
python
|
def backend_routing(self, context):
"""
Returns the targeted backend and an updated state
:type context: satosa.context.Context
:rtype satosa.backends.base.BackendModule
:param context: The request context
:return: backend
"""
satosa_logging(logger, logging.DEBUG, "Routing to backend: %s " % context.target_backend, context.state)
backend = self.backends[context.target_backend]["instance"]
context.state[STATE_KEY] = context.target_frontend
return backend
|
[
"def",
"backend_routing",
"(",
"self",
",",
"context",
")",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Routing to backend: %s \"",
"%",
"context",
".",
"target_backend",
",",
"context",
".",
"state",
")",
"backend",
"=",
"self",
".",
"backends",
"[",
"context",
".",
"target_backend",
"]",
"[",
"\"instance\"",
"]",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"=",
"context",
".",
"target_frontend",
"return",
"backend"
] |
Returns the targeted backend and an updated state
:type context: satosa.context.Context
:rtype satosa.backends.base.BackendModule
:param context: The request context
:return: backend
|
[
"Returns",
"the",
"targeted",
"backend",
"and",
"an",
"updated",
"state"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/routing.py#L73-L86
|
237,037
|
IdentityPython/SATOSA
|
src/satosa/routing.py
|
ModuleRouter.frontend_routing
|
def frontend_routing(self, context):
"""
Returns the targeted frontend and original state
:type context: satosa.context.Context
:rtype satosa.frontends.base.FrontendModule
:param context: The response context
:return: frontend
"""
target_frontend = context.state[STATE_KEY]
satosa_logging(logger, logging.DEBUG, "Routing to frontend: %s " % target_frontend, context.state)
context.target_frontend = target_frontend
frontend = self.frontends[context.target_frontend]["instance"]
return frontend
|
python
|
def frontend_routing(self, context):
"""
Returns the targeted frontend and original state
:type context: satosa.context.Context
:rtype satosa.frontends.base.FrontendModule
:param context: The response context
:return: frontend
"""
target_frontend = context.state[STATE_KEY]
satosa_logging(logger, logging.DEBUG, "Routing to frontend: %s " % target_frontend, context.state)
context.target_frontend = target_frontend
frontend = self.frontends[context.target_frontend]["instance"]
return frontend
|
[
"def",
"frontend_routing",
"(",
"self",
",",
"context",
")",
":",
"target_frontend",
"=",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Routing to frontend: %s \"",
"%",
"target_frontend",
",",
"context",
".",
"state",
")",
"context",
".",
"target_frontend",
"=",
"target_frontend",
"frontend",
"=",
"self",
".",
"frontends",
"[",
"context",
".",
"target_frontend",
"]",
"[",
"\"instance\"",
"]",
"return",
"frontend"
] |
Returns the targeted frontend and original state
:type context: satosa.context.Context
:rtype satosa.frontends.base.FrontendModule
:param context: The response context
:return: frontend
|
[
"Returns",
"the",
"targeted",
"frontend",
"and",
"original",
"state"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/routing.py#L88-L103
|
237,038
|
IdentityPython/SATOSA
|
src/satosa/routing.py
|
ModuleRouter.endpoint_routing
|
def endpoint_routing(self, context):
"""
Finds and returns the endpoint function bound to the path
:type context: satosa.context.Context
:rtype: ((satosa.context.Context, Any) -> Any, Any)
:param context: The request context
:return: registered endpoint and bound parameters
"""
if context.path is None:
satosa_logging(logger, logging.DEBUG, "Context did not contain a path!", context.state)
raise SATOSABadContextError("Context did not contain any path")
satosa_logging(logger, logging.DEBUG, "Routing path: %s" % context.path, context.state)
path_split = context.path.split("/")
backend = path_split[0]
if backend in self.backends:
context.target_backend = backend
else:
satosa_logging(logger, logging.DEBUG, "Unknown backend %s" % backend, context.state)
try:
name, frontend_endpoint = self._find_registered_endpoint(context, self.frontends)
except ModuleRouter.UnknownEndpoint as e:
pass
else:
context.target_frontend = name
return frontend_endpoint
try:
name, micro_service_endpoint = self._find_registered_endpoint(context, self.micro_services)
except ModuleRouter.UnknownEndpoint as e:
pass
else:
context.target_micro_service = name
return micro_service_endpoint
if backend in self.backends:
backend_endpoint = self._find_registered_backend_endpoint(context)
if backend_endpoint:
return backend_endpoint
raise SATOSANoBoundEndpointError("'{}' not bound to any function".format(context.path))
|
python
|
def endpoint_routing(self, context):
"""
Finds and returns the endpoint function bound to the path
:type context: satosa.context.Context
:rtype: ((satosa.context.Context, Any) -> Any, Any)
:param context: The request context
:return: registered endpoint and bound parameters
"""
if context.path is None:
satosa_logging(logger, logging.DEBUG, "Context did not contain a path!", context.state)
raise SATOSABadContextError("Context did not contain any path")
satosa_logging(logger, logging.DEBUG, "Routing path: %s" % context.path, context.state)
path_split = context.path.split("/")
backend = path_split[0]
if backend in self.backends:
context.target_backend = backend
else:
satosa_logging(logger, logging.DEBUG, "Unknown backend %s" % backend, context.state)
try:
name, frontend_endpoint = self._find_registered_endpoint(context, self.frontends)
except ModuleRouter.UnknownEndpoint as e:
pass
else:
context.target_frontend = name
return frontend_endpoint
try:
name, micro_service_endpoint = self._find_registered_endpoint(context, self.micro_services)
except ModuleRouter.UnknownEndpoint as e:
pass
else:
context.target_micro_service = name
return micro_service_endpoint
if backend in self.backends:
backend_endpoint = self._find_registered_backend_endpoint(context)
if backend_endpoint:
return backend_endpoint
raise SATOSANoBoundEndpointError("'{}' not bound to any function".format(context.path))
|
[
"def",
"endpoint_routing",
"(",
"self",
",",
"context",
")",
":",
"if",
"context",
".",
"path",
"is",
"None",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Context did not contain a path!\"",
",",
"context",
".",
"state",
")",
"raise",
"SATOSABadContextError",
"(",
"\"Context did not contain any path\"",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Routing path: %s\"",
"%",
"context",
".",
"path",
",",
"context",
".",
"state",
")",
"path_split",
"=",
"context",
".",
"path",
".",
"split",
"(",
"\"/\"",
")",
"backend",
"=",
"path_split",
"[",
"0",
"]",
"if",
"backend",
"in",
"self",
".",
"backends",
":",
"context",
".",
"target_backend",
"=",
"backend",
"else",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Unknown backend %s\"",
"%",
"backend",
",",
"context",
".",
"state",
")",
"try",
":",
"name",
",",
"frontend_endpoint",
"=",
"self",
".",
"_find_registered_endpoint",
"(",
"context",
",",
"self",
".",
"frontends",
")",
"except",
"ModuleRouter",
".",
"UnknownEndpoint",
"as",
"e",
":",
"pass",
"else",
":",
"context",
".",
"target_frontend",
"=",
"name",
"return",
"frontend_endpoint",
"try",
":",
"name",
",",
"micro_service_endpoint",
"=",
"self",
".",
"_find_registered_endpoint",
"(",
"context",
",",
"self",
".",
"micro_services",
")",
"except",
"ModuleRouter",
".",
"UnknownEndpoint",
"as",
"e",
":",
"pass",
"else",
":",
"context",
".",
"target_micro_service",
"=",
"name",
"return",
"micro_service_endpoint",
"if",
"backend",
"in",
"self",
".",
"backends",
":",
"backend_endpoint",
"=",
"self",
".",
"_find_registered_backend_endpoint",
"(",
"context",
")",
"if",
"backend_endpoint",
":",
"return",
"backend_endpoint",
"raise",
"SATOSANoBoundEndpointError",
"(",
"\"'{}' not bound to any function\"",
".",
"format",
"(",
"context",
".",
"path",
")",
")"
] |
Finds and returns the endpoint function bound to the path
:type context: satosa.context.Context
:rtype: ((satosa.context.Context, Any) -> Any, Any)
:param context: The request context
:return: registered endpoint and bound parameters
|
[
"Finds",
"and",
"returns",
"the",
"endpoint",
"function",
"bound",
"to",
"the",
"path"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/routing.py#L128-L172
|
237,039
|
IdentityPython/SATOSA
|
src/satosa/base.py
|
SATOSABase._auth_req_callback_func
|
def _auth_req_callback_func(self, context, internal_request):
"""
This function is called by a frontend module when an authorization request has been
processed.
:type context: satosa.context.Context
:type internal_request: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_request: request processed by the frontend
:return: response
"""
state = context.state
state[STATE_KEY] = {"requester": internal_request.requester}
# TODO consent module should manage any state it needs by itself
try:
state_dict = context.state[consent.STATE_KEY]
except KeyError:
state_dict = context.state[consent.STATE_KEY] = {}
finally:
state_dict.update({
"filter": internal_request.attributes or [],
"requester_name": internal_request.requester_name,
})
satosa_logging(logger, logging.INFO,
"Requesting provider: {}".format(internal_request.requester), state)
if self.request_micro_services:
return self.request_micro_services[0].process(context, internal_request)
return self._auth_req_finish(context, internal_request)
|
python
|
def _auth_req_callback_func(self, context, internal_request):
"""
This function is called by a frontend module when an authorization request has been
processed.
:type context: satosa.context.Context
:type internal_request: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_request: request processed by the frontend
:return: response
"""
state = context.state
state[STATE_KEY] = {"requester": internal_request.requester}
# TODO consent module should manage any state it needs by itself
try:
state_dict = context.state[consent.STATE_KEY]
except KeyError:
state_dict = context.state[consent.STATE_KEY] = {}
finally:
state_dict.update({
"filter": internal_request.attributes or [],
"requester_name": internal_request.requester_name,
})
satosa_logging(logger, logging.INFO,
"Requesting provider: {}".format(internal_request.requester), state)
if self.request_micro_services:
return self.request_micro_services[0].process(context, internal_request)
return self._auth_req_finish(context, internal_request)
|
[
"def",
"_auth_req_callback_func",
"(",
"self",
",",
"context",
",",
"internal_request",
")",
":",
"state",
"=",
"context",
".",
"state",
"state",
"[",
"STATE_KEY",
"]",
"=",
"{",
"\"requester\"",
":",
"internal_request",
".",
"requester",
"}",
"# TODO consent module should manage any state it needs by itself",
"try",
":",
"state_dict",
"=",
"context",
".",
"state",
"[",
"consent",
".",
"STATE_KEY",
"]",
"except",
"KeyError",
":",
"state_dict",
"=",
"context",
".",
"state",
"[",
"consent",
".",
"STATE_KEY",
"]",
"=",
"{",
"}",
"finally",
":",
"state_dict",
".",
"update",
"(",
"{",
"\"filter\"",
":",
"internal_request",
".",
"attributes",
"or",
"[",
"]",
",",
"\"requester_name\"",
":",
"internal_request",
".",
"requester_name",
",",
"}",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"INFO",
",",
"\"Requesting provider: {}\"",
".",
"format",
"(",
"internal_request",
".",
"requester",
")",
",",
"state",
")",
"if",
"self",
".",
"request_micro_services",
":",
"return",
"self",
".",
"request_micro_services",
"[",
"0",
"]",
".",
"process",
"(",
"context",
",",
"internal_request",
")",
"return",
"self",
".",
"_auth_req_finish",
"(",
"context",
",",
"internal_request",
")"
] |
This function is called by a frontend module when an authorization request has been
processed.
:type context: satosa.context.Context
:type internal_request: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_request: request processed by the frontend
:return: response
|
[
"This",
"function",
"is",
"called",
"by",
"a",
"frontend",
"module",
"when",
"an",
"authorization",
"request",
"has",
"been",
"processed",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L114-L146
|
237,040
|
IdentityPython/SATOSA
|
src/satosa/base.py
|
SATOSABase._auth_resp_callback_func
|
def _auth_resp_callback_func(self, context, internal_response):
"""
This function is called by a backend module when the authorization is
complete.
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_response: The authentication response
:return: response
"""
context.request = None
internal_response.requester = context.state[STATE_KEY]["requester"]
# If configured construct the user id from attribute values.
if "user_id_from_attrs" in self.config["INTERNAL_ATTRIBUTES"]:
subject_id = [
"".join(internal_response.attributes[attr]) for attr in
self.config["INTERNAL_ATTRIBUTES"]["user_id_from_attrs"]
]
internal_response.subject_id = "".join(subject_id)
if self.response_micro_services:
return self.response_micro_services[0].process(
context, internal_response)
return self._auth_resp_finish(context, internal_response)
|
python
|
def _auth_resp_callback_func(self, context, internal_response):
"""
This function is called by a backend module when the authorization is
complete.
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_response: The authentication response
:return: response
"""
context.request = None
internal_response.requester = context.state[STATE_KEY]["requester"]
# If configured construct the user id from attribute values.
if "user_id_from_attrs" in self.config["INTERNAL_ATTRIBUTES"]:
subject_id = [
"".join(internal_response.attributes[attr]) for attr in
self.config["INTERNAL_ATTRIBUTES"]["user_id_from_attrs"]
]
internal_response.subject_id = "".join(subject_id)
if self.response_micro_services:
return self.response_micro_services[0].process(
context, internal_response)
return self._auth_resp_finish(context, internal_response)
|
[
"def",
"_auth_resp_callback_func",
"(",
"self",
",",
"context",
",",
"internal_response",
")",
":",
"context",
".",
"request",
"=",
"None",
"internal_response",
".",
"requester",
"=",
"context",
".",
"state",
"[",
"STATE_KEY",
"]",
"[",
"\"requester\"",
"]",
"# If configured construct the user id from attribute values.",
"if",
"\"user_id_from_attrs\"",
"in",
"self",
".",
"config",
"[",
"\"INTERNAL_ATTRIBUTES\"",
"]",
":",
"subject_id",
"=",
"[",
"\"\"",
".",
"join",
"(",
"internal_response",
".",
"attributes",
"[",
"attr",
"]",
")",
"for",
"attr",
"in",
"self",
".",
"config",
"[",
"\"INTERNAL_ATTRIBUTES\"",
"]",
"[",
"\"user_id_from_attrs\"",
"]",
"]",
"internal_response",
".",
"subject_id",
"=",
"\"\"",
".",
"join",
"(",
"subject_id",
")",
"if",
"self",
".",
"response_micro_services",
":",
"return",
"self",
".",
"response_micro_services",
"[",
"0",
"]",
".",
"process",
"(",
"context",
",",
"internal_response",
")",
"return",
"self",
".",
"_auth_resp_finish",
"(",
"context",
",",
"internal_response",
")"
] |
This function is called by a backend module when the authorization is
complete.
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype: satosa.response.Response
:param context: The request context
:param internal_response: The authentication response
:return: response
|
[
"This",
"function",
"is",
"called",
"by",
"a",
"backend",
"module",
"when",
"the",
"authorization",
"is",
"complete",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L170-L199
|
237,041
|
IdentityPython/SATOSA
|
src/satosa/base.py
|
SATOSABase._handle_satosa_authentication_error
|
def _handle_satosa_authentication_error(self, error):
"""
Sends a response to the requester about the error
:type error: satosa.exception.SATOSAAuthenticationError
:rtype: satosa.response.Response
:param error: The exception
:return: response
"""
context = Context()
context.state = error.state
frontend = self.module_router.frontend_routing(context)
return frontend.handle_backend_error(error)
|
python
|
def _handle_satosa_authentication_error(self, error):
"""
Sends a response to the requester about the error
:type error: satosa.exception.SATOSAAuthenticationError
:rtype: satosa.response.Response
:param error: The exception
:return: response
"""
context = Context()
context.state = error.state
frontend = self.module_router.frontend_routing(context)
return frontend.handle_backend_error(error)
|
[
"def",
"_handle_satosa_authentication_error",
"(",
"self",
",",
"error",
")",
":",
"context",
"=",
"Context",
"(",
")",
"context",
".",
"state",
"=",
"error",
".",
"state",
"frontend",
"=",
"self",
".",
"module_router",
".",
"frontend_routing",
"(",
"context",
")",
"return",
"frontend",
".",
"handle_backend_error",
"(",
"error",
")"
] |
Sends a response to the requester about the error
:type error: satosa.exception.SATOSAAuthenticationError
:rtype: satosa.response.Response
:param error: The exception
:return: response
|
[
"Sends",
"a",
"response",
"to",
"the",
"requester",
"about",
"the",
"error"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L201-L214
|
237,042
|
IdentityPython/SATOSA
|
src/satosa/base.py
|
SATOSABase._load_state
|
def _load_state(self, context):
"""
Load state from cookie to the context
:type context: satosa.context.Context
:param context: Session context
"""
try:
state = cookie_to_state(
context.cookie,
self.config["COOKIE_STATE_NAME"],
self.config["STATE_ENCRYPTION_KEY"])
except SATOSAStateError as e:
msg_tmpl = 'Failed to decrypt state {state} with {error}'
msg = msg_tmpl.format(state=context.cookie, error=str(e))
satosa_logging(logger, logging.WARNING, msg, None)
state = State()
finally:
context.state = state
|
python
|
def _load_state(self, context):
"""
Load state from cookie to the context
:type context: satosa.context.Context
:param context: Session context
"""
try:
state = cookie_to_state(
context.cookie,
self.config["COOKIE_STATE_NAME"],
self.config["STATE_ENCRYPTION_KEY"])
except SATOSAStateError as e:
msg_tmpl = 'Failed to decrypt state {state} with {error}'
msg = msg_tmpl.format(state=context.cookie, error=str(e))
satosa_logging(logger, logging.WARNING, msg, None)
state = State()
finally:
context.state = state
|
[
"def",
"_load_state",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"state",
"=",
"cookie_to_state",
"(",
"context",
".",
"cookie",
",",
"self",
".",
"config",
"[",
"\"COOKIE_STATE_NAME\"",
"]",
",",
"self",
".",
"config",
"[",
"\"STATE_ENCRYPTION_KEY\"",
"]",
")",
"except",
"SATOSAStateError",
"as",
"e",
":",
"msg_tmpl",
"=",
"'Failed to decrypt state {state} with {error}'",
"msg",
"=",
"msg_tmpl",
".",
"format",
"(",
"state",
"=",
"context",
".",
"cookie",
",",
"error",
"=",
"str",
"(",
"e",
")",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"WARNING",
",",
"msg",
",",
"None",
")",
"state",
"=",
"State",
"(",
")",
"finally",
":",
"context",
".",
"state",
"=",
"state"
] |
Load state from cookie to the context
:type context: satosa.context.Context
:param context: Session context
|
[
"Load",
"state",
"from",
"cookie",
"to",
"the",
"context"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L238-L256
|
237,043
|
IdentityPython/SATOSA
|
src/satosa/base.py
|
SATOSABase._save_state
|
def _save_state(self, resp, context):
"""
Saves a state from context to cookie
:type resp: satosa.response.Response
:type context: satosa.context.Context
:param resp: The response
:param context: Session context
"""
cookie = state_to_cookie(context.state, self.config["COOKIE_STATE_NAME"], "/",
self.config["STATE_ENCRYPTION_KEY"])
resp.headers.append(tuple(cookie.output().split(": ", 1)))
|
python
|
def _save_state(self, resp, context):
"""
Saves a state from context to cookie
:type resp: satosa.response.Response
:type context: satosa.context.Context
:param resp: The response
:param context: Session context
"""
cookie = state_to_cookie(context.state, self.config["COOKIE_STATE_NAME"], "/",
self.config["STATE_ENCRYPTION_KEY"])
resp.headers.append(tuple(cookie.output().split(": ", 1)))
|
[
"def",
"_save_state",
"(",
"self",
",",
"resp",
",",
"context",
")",
":",
"cookie",
"=",
"state_to_cookie",
"(",
"context",
".",
"state",
",",
"self",
".",
"config",
"[",
"\"COOKIE_STATE_NAME\"",
"]",
",",
"\"/\"",
",",
"self",
".",
"config",
"[",
"\"STATE_ENCRYPTION_KEY\"",
"]",
")",
"resp",
".",
"headers",
".",
"append",
"(",
"tuple",
"(",
"cookie",
".",
"output",
"(",
")",
".",
"split",
"(",
"\": \"",
",",
"1",
")",
")",
")"
] |
Saves a state from context to cookie
:type resp: satosa.response.Response
:type context: satosa.context.Context
:param resp: The response
:param context: Session context
|
[
"Saves",
"a",
"state",
"from",
"context",
"to",
"cookie"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L258-L271
|
237,044
|
IdentityPython/SATOSA
|
src/satosa/base.py
|
SATOSABase.run
|
def run(self, context):
"""
Runs the satosa proxy with the given context.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The request context
:return: response
"""
try:
self._load_state(context)
spec = self.module_router.endpoint_routing(context)
resp = self._run_bound_endpoint(context, spec)
self._save_state(resp, context)
except SATOSANoBoundEndpointError:
raise
except SATOSAError:
satosa_logging(logger, logging.ERROR, "Uncaught SATOSA error ", context.state,
exc_info=True)
raise
except UnknownSystemEntity as err:
satosa_logging(logger, logging.ERROR,
"configuration error: unknown system entity " + str(err),
context.state, exc_info=False)
raise
except Exception as err:
satosa_logging(logger, logging.ERROR, "Uncaught exception", context.state,
exc_info=True)
raise SATOSAUnknownError("Unknown error") from err
return resp
|
python
|
def run(self, context):
"""
Runs the satosa proxy with the given context.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The request context
:return: response
"""
try:
self._load_state(context)
spec = self.module_router.endpoint_routing(context)
resp = self._run_bound_endpoint(context, spec)
self._save_state(resp, context)
except SATOSANoBoundEndpointError:
raise
except SATOSAError:
satosa_logging(logger, logging.ERROR, "Uncaught SATOSA error ", context.state,
exc_info=True)
raise
except UnknownSystemEntity as err:
satosa_logging(logger, logging.ERROR,
"configuration error: unknown system entity " + str(err),
context.state, exc_info=False)
raise
except Exception as err:
satosa_logging(logger, logging.ERROR, "Uncaught exception", context.state,
exc_info=True)
raise SATOSAUnknownError("Unknown error") from err
return resp
|
[
"def",
"run",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"self",
".",
"_load_state",
"(",
"context",
")",
"spec",
"=",
"self",
".",
"module_router",
".",
"endpoint_routing",
"(",
"context",
")",
"resp",
"=",
"self",
".",
"_run_bound_endpoint",
"(",
"context",
",",
"spec",
")",
"self",
".",
"_save_state",
"(",
"resp",
",",
"context",
")",
"except",
"SATOSANoBoundEndpointError",
":",
"raise",
"except",
"SATOSAError",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"Uncaught SATOSA error \"",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"True",
")",
"raise",
"except",
"UnknownSystemEntity",
"as",
"err",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"configuration error: unknown system entity \"",
"+",
"str",
"(",
"err",
")",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"False",
")",
"raise",
"except",
"Exception",
"as",
"err",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"ERROR",
",",
"\"Uncaught exception\"",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"True",
")",
"raise",
"SATOSAUnknownError",
"(",
"\"Unknown error\"",
")",
"from",
"err",
"return",
"resp"
] |
Runs the satosa proxy with the given context.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The request context
:return: response
|
[
"Runs",
"the",
"satosa",
"proxy",
"with",
"the",
"given",
"context",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/base.py#L273-L303
|
237,045
|
IdentityPython/SATOSA
|
src/satosa/backends/saml2.py
|
SAMLBackend.disco_query
|
def disco_query(self):
"""
Makes a request to the discovery server
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.SeeOther
:param context: The current context
:param internal_req: The request
:return: Response
"""
return_url = self.sp.config.getattr("endpoints", "sp")["discovery_response"][0][0]
loc = self.sp.create_discovery_service_request(self.discosrv, self.sp.config.entityid, **{"return": return_url})
return SeeOther(loc)
|
python
|
def disco_query(self):
"""
Makes a request to the discovery server
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.SeeOther
:param context: The current context
:param internal_req: The request
:return: Response
"""
return_url = self.sp.config.getattr("endpoints", "sp")["discovery_response"][0][0]
loc = self.sp.create_discovery_service_request(self.discosrv, self.sp.config.entityid, **{"return": return_url})
return SeeOther(loc)
|
[
"def",
"disco_query",
"(",
"self",
")",
":",
"return_url",
"=",
"self",
".",
"sp",
".",
"config",
".",
"getattr",
"(",
"\"endpoints\"",
",",
"\"sp\"",
")",
"[",
"\"discovery_response\"",
"]",
"[",
"0",
"]",
"[",
"0",
"]",
"loc",
"=",
"self",
".",
"sp",
".",
"create_discovery_service_request",
"(",
"self",
".",
"discosrv",
",",
"self",
".",
"sp",
".",
"config",
".",
"entityid",
",",
"*",
"*",
"{",
"\"return\"",
":",
"return_url",
"}",
")",
"return",
"SeeOther",
"(",
"loc",
")"
] |
Makes a request to the discovery server
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.SeeOther
:param context: The current context
:param internal_req: The request
:return: Response
|
[
"Makes",
"a",
"request",
"to",
"the",
"discovery",
"server"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L107-L121
|
237,046
|
IdentityPython/SATOSA
|
src/satosa/backends/saml2.py
|
SAMLBackend.authn_request
|
def authn_request(self, context, entity_id):
"""
Do an authorization request on idp with given entity id.
This is the start of the authorization.
:type context: satosa.context.Context
:type entity_id: str
:rtype: satosa.response.Response
:param context: The current context
:param entity_id: Target IDP entity id
:return: response to the user agent
"""
# If IDP blacklisting is enabled and the selected IDP is blacklisted,
# stop here
if self.idp_blacklist_file:
with open(self.idp_blacklist_file) as blacklist_file:
blacklist_array = json.load(blacklist_file)['blacklist']
if entity_id in blacklist_array:
satosa_logging(logger, logging.DEBUG, "IdP with EntityID {} is blacklisted".format(entity_id), context.state, exc_info=False)
raise SATOSAAuthenticationError(context.state, "Selected IdP is blacklisted for this backend")
kwargs = {}
authn_context = self.construct_requested_authn_context(entity_id)
if authn_context:
kwargs['requested_authn_context'] = authn_context
try:
binding, destination = self.sp.pick_binding(
"single_sign_on_service", None, "idpsso", entity_id=entity_id)
satosa_logging(logger, logging.DEBUG, "binding: %s, destination: %s" % (binding, destination),
context.state)
acs_endp, response_binding = self.sp.config.getattr("endpoints", "sp")["assertion_consumer_service"][0]
req_id, req = self.sp.create_authn_request(
destination, binding=response_binding, **kwargs)
relay_state = util.rndstr()
ht_args = self.sp.apply_binding(binding, "%s" % req, destination, relay_state=relay_state)
satosa_logging(logger, logging.DEBUG, "ht_args: %s" % ht_args, context.state)
except Exception as exc:
satosa_logging(logger, logging.DEBUG, "Failed to construct the AuthnRequest for state", context.state,
exc_info=True)
raise SATOSAAuthenticationError(context.state, "Failed to construct the AuthnRequest") from exc
if self.sp.config.getattr('allow_unsolicited', 'sp') is False:
if req_id in self.outstanding_queries:
errmsg = "Request with duplicate id {}".format(req_id)
satosa_logging(logger, logging.DEBUG, errmsg, context.state)
raise SATOSAAuthenticationError(context.state, errmsg)
self.outstanding_queries[req_id] = req
context.state[self.name] = {"relay_state": relay_state}
return make_saml_response(binding, ht_args)
|
python
|
def authn_request(self, context, entity_id):
"""
Do an authorization request on idp with given entity id.
This is the start of the authorization.
:type context: satosa.context.Context
:type entity_id: str
:rtype: satosa.response.Response
:param context: The current context
:param entity_id: Target IDP entity id
:return: response to the user agent
"""
# If IDP blacklisting is enabled and the selected IDP is blacklisted,
# stop here
if self.idp_blacklist_file:
with open(self.idp_blacklist_file) as blacklist_file:
blacklist_array = json.load(blacklist_file)['blacklist']
if entity_id in blacklist_array:
satosa_logging(logger, logging.DEBUG, "IdP with EntityID {} is blacklisted".format(entity_id), context.state, exc_info=False)
raise SATOSAAuthenticationError(context.state, "Selected IdP is blacklisted for this backend")
kwargs = {}
authn_context = self.construct_requested_authn_context(entity_id)
if authn_context:
kwargs['requested_authn_context'] = authn_context
try:
binding, destination = self.sp.pick_binding(
"single_sign_on_service", None, "idpsso", entity_id=entity_id)
satosa_logging(logger, logging.DEBUG, "binding: %s, destination: %s" % (binding, destination),
context.state)
acs_endp, response_binding = self.sp.config.getattr("endpoints", "sp")["assertion_consumer_service"][0]
req_id, req = self.sp.create_authn_request(
destination, binding=response_binding, **kwargs)
relay_state = util.rndstr()
ht_args = self.sp.apply_binding(binding, "%s" % req, destination, relay_state=relay_state)
satosa_logging(logger, logging.DEBUG, "ht_args: %s" % ht_args, context.state)
except Exception as exc:
satosa_logging(logger, logging.DEBUG, "Failed to construct the AuthnRequest for state", context.state,
exc_info=True)
raise SATOSAAuthenticationError(context.state, "Failed to construct the AuthnRequest") from exc
if self.sp.config.getattr('allow_unsolicited', 'sp') is False:
if req_id in self.outstanding_queries:
errmsg = "Request with duplicate id {}".format(req_id)
satosa_logging(logger, logging.DEBUG, errmsg, context.state)
raise SATOSAAuthenticationError(context.state, errmsg)
self.outstanding_queries[req_id] = req
context.state[self.name] = {"relay_state": relay_state}
return make_saml_response(binding, ht_args)
|
[
"def",
"authn_request",
"(",
"self",
",",
"context",
",",
"entity_id",
")",
":",
"# If IDP blacklisting is enabled and the selected IDP is blacklisted,",
"# stop here",
"if",
"self",
".",
"idp_blacklist_file",
":",
"with",
"open",
"(",
"self",
".",
"idp_blacklist_file",
")",
"as",
"blacklist_file",
":",
"blacklist_array",
"=",
"json",
".",
"load",
"(",
"blacklist_file",
")",
"[",
"'blacklist'",
"]",
"if",
"entity_id",
"in",
"blacklist_array",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"IdP with EntityID {} is blacklisted\"",
".",
"format",
"(",
"entity_id",
")",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"False",
")",
"raise",
"SATOSAAuthenticationError",
"(",
"context",
".",
"state",
",",
"\"Selected IdP is blacklisted for this backend\"",
")",
"kwargs",
"=",
"{",
"}",
"authn_context",
"=",
"self",
".",
"construct_requested_authn_context",
"(",
"entity_id",
")",
"if",
"authn_context",
":",
"kwargs",
"[",
"'requested_authn_context'",
"]",
"=",
"authn_context",
"try",
":",
"binding",
",",
"destination",
"=",
"self",
".",
"sp",
".",
"pick_binding",
"(",
"\"single_sign_on_service\"",
",",
"None",
",",
"\"idpsso\"",
",",
"entity_id",
"=",
"entity_id",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"binding: %s, destination: %s\"",
"%",
"(",
"binding",
",",
"destination",
")",
",",
"context",
".",
"state",
")",
"acs_endp",
",",
"response_binding",
"=",
"self",
".",
"sp",
".",
"config",
".",
"getattr",
"(",
"\"endpoints\"",
",",
"\"sp\"",
")",
"[",
"\"assertion_consumer_service\"",
"]",
"[",
"0",
"]",
"req_id",
",",
"req",
"=",
"self",
".",
"sp",
".",
"create_authn_request",
"(",
"destination",
",",
"binding",
"=",
"response_binding",
",",
"*",
"*",
"kwargs",
")",
"relay_state",
"=",
"util",
".",
"rndstr",
"(",
")",
"ht_args",
"=",
"self",
".",
"sp",
".",
"apply_binding",
"(",
"binding",
",",
"\"%s\"",
"%",
"req",
",",
"destination",
",",
"relay_state",
"=",
"relay_state",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"ht_args: %s\"",
"%",
"ht_args",
",",
"context",
".",
"state",
")",
"except",
"Exception",
"as",
"exc",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"Failed to construct the AuthnRequest for state\"",
",",
"context",
".",
"state",
",",
"exc_info",
"=",
"True",
")",
"raise",
"SATOSAAuthenticationError",
"(",
"context",
".",
"state",
",",
"\"Failed to construct the AuthnRequest\"",
")",
"from",
"exc",
"if",
"self",
".",
"sp",
".",
"config",
".",
"getattr",
"(",
"'allow_unsolicited'",
",",
"'sp'",
")",
"is",
"False",
":",
"if",
"req_id",
"in",
"self",
".",
"outstanding_queries",
":",
"errmsg",
"=",
"\"Request with duplicate id {}\"",
".",
"format",
"(",
"req_id",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"errmsg",
",",
"context",
".",
"state",
")",
"raise",
"SATOSAAuthenticationError",
"(",
"context",
".",
"state",
",",
"errmsg",
")",
"self",
".",
"outstanding_queries",
"[",
"req_id",
"]",
"=",
"req",
"context",
".",
"state",
"[",
"self",
".",
"name",
"]",
"=",
"{",
"\"relay_state\"",
":",
"relay_state",
"}",
"return",
"make_saml_response",
"(",
"binding",
",",
"ht_args",
")"
] |
Do an authorization request on idp with given entity id.
This is the start of the authorization.
:type context: satosa.context.Context
:type entity_id: str
:rtype: satosa.response.Response
:param context: The current context
:param entity_id: Target IDP entity id
:return: response to the user agent
|
[
"Do",
"an",
"authorization",
"request",
"on",
"idp",
"with",
"given",
"entity",
"id",
".",
"This",
"is",
"the",
"start",
"of",
"the",
"authorization",
"."
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L143-L195
|
237,047
|
IdentityPython/SATOSA
|
src/satosa/backends/saml2.py
|
SAMLBackend.disco_response
|
def disco_response(self, context):
"""
Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
info = context.request
state = context.state
try:
entity_id = info["entityID"]
except KeyError as err:
satosa_logging(logger, logging.DEBUG, "No IDP chosen for state", state, exc_info=True)
raise SATOSAAuthenticationError(state, "No IDP chosen") from err
return self.authn_request(context, entity_id)
|
python
|
def disco_response(self, context):
"""
Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
"""
info = context.request
state = context.state
try:
entity_id = info["entityID"]
except KeyError as err:
satosa_logging(logger, logging.DEBUG, "No IDP chosen for state", state, exc_info=True)
raise SATOSAAuthenticationError(state, "No IDP chosen") from err
return self.authn_request(context, entity_id)
|
[
"def",
"disco_response",
"(",
"self",
",",
"context",
")",
":",
"info",
"=",
"context",
".",
"request",
"state",
"=",
"context",
".",
"state",
"try",
":",
"entity_id",
"=",
"info",
"[",
"\"entityID\"",
"]",
"except",
"KeyError",
"as",
"err",
":",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"No IDP chosen for state\"",
",",
"state",
",",
"exc_info",
"=",
"True",
")",
"raise",
"SATOSAAuthenticationError",
"(",
"state",
",",
"\"No IDP chosen\"",
")",
"from",
"err",
"return",
"self",
".",
"authn_request",
"(",
"context",
",",
"entity_id",
")"
] |
Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response
|
[
"Endpoint",
"for",
"the",
"discovery",
"server",
"response"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L240-L259
|
237,048
|
IdentityPython/SATOSA
|
src/satosa/backends/saml2.py
|
SAMLBackend._translate_response
|
def _translate_response(self, response, state):
"""
Translates a saml authorization response to an internal response
:type response: saml2.response.AuthnResponse
:rtype: satosa.internal.InternalData
:param response: The saml authorization response
:return: A translated internal response
"""
# The response may have been encrypted by the IdP so if we have an
# encryption key, try it.
if self.encryption_keys:
response.parse_assertion(self.encryption_keys)
authn_info = response.authn_info()[0]
auth_class_ref = authn_info[0]
timestamp = response.assertion.authn_statement[0].authn_instant
issuer = response.response.issuer.text
auth_info = AuthenticationInformation(
auth_class_ref, timestamp, issuer,
)
# The SAML response may not include a NameID.
subject = response.get_subject()
name_id = subject.text if subject else None
name_id_format = subject.format if subject else None
attributes = self.converter.to_internal(
self.attribute_profile, response.ava,
)
internal_resp = InternalData(
auth_info=auth_info,
attributes=attributes,
subject_type=name_id_format,
subject_id=name_id,
)
satosa_logging(logger, logging.DEBUG,
"backend received attributes:\n%s" %
json.dumps(response.ava, indent=4), state)
return internal_resp
|
python
|
def _translate_response(self, response, state):
"""
Translates a saml authorization response to an internal response
:type response: saml2.response.AuthnResponse
:rtype: satosa.internal.InternalData
:param response: The saml authorization response
:return: A translated internal response
"""
# The response may have been encrypted by the IdP so if we have an
# encryption key, try it.
if self.encryption_keys:
response.parse_assertion(self.encryption_keys)
authn_info = response.authn_info()[0]
auth_class_ref = authn_info[0]
timestamp = response.assertion.authn_statement[0].authn_instant
issuer = response.response.issuer.text
auth_info = AuthenticationInformation(
auth_class_ref, timestamp, issuer,
)
# The SAML response may not include a NameID.
subject = response.get_subject()
name_id = subject.text if subject else None
name_id_format = subject.format if subject else None
attributes = self.converter.to_internal(
self.attribute_profile, response.ava,
)
internal_resp = InternalData(
auth_info=auth_info,
attributes=attributes,
subject_type=name_id_format,
subject_id=name_id,
)
satosa_logging(logger, logging.DEBUG,
"backend received attributes:\n%s" %
json.dumps(response.ava, indent=4), state)
return internal_resp
|
[
"def",
"_translate_response",
"(",
"self",
",",
"response",
",",
"state",
")",
":",
"# The response may have been encrypted by the IdP so if we have an",
"# encryption key, try it.",
"if",
"self",
".",
"encryption_keys",
":",
"response",
".",
"parse_assertion",
"(",
"self",
".",
"encryption_keys",
")",
"authn_info",
"=",
"response",
".",
"authn_info",
"(",
")",
"[",
"0",
"]",
"auth_class_ref",
"=",
"authn_info",
"[",
"0",
"]",
"timestamp",
"=",
"response",
".",
"assertion",
".",
"authn_statement",
"[",
"0",
"]",
".",
"authn_instant",
"issuer",
"=",
"response",
".",
"response",
".",
"issuer",
".",
"text",
"auth_info",
"=",
"AuthenticationInformation",
"(",
"auth_class_ref",
",",
"timestamp",
",",
"issuer",
",",
")",
"# The SAML response may not include a NameID.",
"subject",
"=",
"response",
".",
"get_subject",
"(",
")",
"name_id",
"=",
"subject",
".",
"text",
"if",
"subject",
"else",
"None",
"name_id_format",
"=",
"subject",
".",
"format",
"if",
"subject",
"else",
"None",
"attributes",
"=",
"self",
".",
"converter",
".",
"to_internal",
"(",
"self",
".",
"attribute_profile",
",",
"response",
".",
"ava",
",",
")",
"internal_resp",
"=",
"InternalData",
"(",
"auth_info",
"=",
"auth_info",
",",
"attributes",
"=",
"attributes",
",",
"subject_type",
"=",
"name_id_format",
",",
"subject_id",
"=",
"name_id",
",",
")",
"satosa_logging",
"(",
"logger",
",",
"logging",
".",
"DEBUG",
",",
"\"backend received attributes:\\n%s\"",
"%",
"json",
".",
"dumps",
"(",
"response",
".",
"ava",
",",
"indent",
"=",
"4",
")",
",",
"state",
")",
"return",
"internal_resp"
] |
Translates a saml authorization response to an internal response
:type response: saml2.response.AuthnResponse
:rtype: satosa.internal.InternalData
:param response: The saml authorization response
:return: A translated internal response
|
[
"Translates",
"a",
"saml",
"authorization",
"response",
"to",
"an",
"internal",
"response"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/backends/saml2.py#L261-L304
|
237,049
|
IdentityPython/SATOSA
|
src/satosa/attribute_mapping.py
|
AttributeMapper.to_internal_filter
|
def to_internal_filter(self, attribute_profile, external_attribute_names):
"""
Converts attribute names from external "type" to internal
:type attribute_profile: str
:type external_attribute_names: list[str]
:type case_insensitive: bool
:rtype: list[str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_attribute_names: A list of attribute names
:param case_insensitive: Create a case insensitive filter
:return: A list of attribute names in the internal format
"""
try:
profile_mapping = self.to_internal_attributes[attribute_profile]
except KeyError:
logger.warn("no attribute mapping found for the given attribute profile '%s'", attribute_profile)
# no attributes since the given profile is not configured
return []
internal_attribute_names = set() # use set to ensure only unique values
for external_attribute_name in external_attribute_names:
try:
internal_attribute_name = profile_mapping[external_attribute_name]
internal_attribute_names.add(internal_attribute_name)
except KeyError:
pass
return list(internal_attribute_names)
|
python
|
def to_internal_filter(self, attribute_profile, external_attribute_names):
"""
Converts attribute names from external "type" to internal
:type attribute_profile: str
:type external_attribute_names: list[str]
:type case_insensitive: bool
:rtype: list[str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_attribute_names: A list of attribute names
:param case_insensitive: Create a case insensitive filter
:return: A list of attribute names in the internal format
"""
try:
profile_mapping = self.to_internal_attributes[attribute_profile]
except KeyError:
logger.warn("no attribute mapping found for the given attribute profile '%s'", attribute_profile)
# no attributes since the given profile is not configured
return []
internal_attribute_names = set() # use set to ensure only unique values
for external_attribute_name in external_attribute_names:
try:
internal_attribute_name = profile_mapping[external_attribute_name]
internal_attribute_names.add(internal_attribute_name)
except KeyError:
pass
return list(internal_attribute_names)
|
[
"def",
"to_internal_filter",
"(",
"self",
",",
"attribute_profile",
",",
"external_attribute_names",
")",
":",
"try",
":",
"profile_mapping",
"=",
"self",
".",
"to_internal_attributes",
"[",
"attribute_profile",
"]",
"except",
"KeyError",
":",
"logger",
".",
"warn",
"(",
"\"no attribute mapping found for the given attribute profile '%s'\"",
",",
"attribute_profile",
")",
"# no attributes since the given profile is not configured",
"return",
"[",
"]",
"internal_attribute_names",
"=",
"set",
"(",
")",
"# use set to ensure only unique values",
"for",
"external_attribute_name",
"in",
"external_attribute_names",
":",
"try",
":",
"internal_attribute_name",
"=",
"profile_mapping",
"[",
"external_attribute_name",
"]",
"internal_attribute_names",
".",
"add",
"(",
"internal_attribute_name",
")",
"except",
"KeyError",
":",
"pass",
"return",
"list",
"(",
"internal_attribute_names",
")"
] |
Converts attribute names from external "type" to internal
:type attribute_profile: str
:type external_attribute_names: list[str]
:type case_insensitive: bool
:rtype: list[str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_attribute_names: A list of attribute names
:param case_insensitive: Create a case insensitive filter
:return: A list of attribute names in the internal format
|
[
"Converts",
"attribute",
"names",
"from",
"external",
"type",
"to",
"internal"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/attribute_mapping.py#L44-L73
|
237,050
|
IdentityPython/SATOSA
|
src/satosa/attribute_mapping.py
|
AttributeMapper.to_internal
|
def to_internal(self, attribute_profile, external_dict):
"""
Converts the external data from "type" to internal
:type attribute_profile: str
:type external_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_dict: Attributes in the external format
:return: Attributes in the internal format
"""
internal_dict = {}
for internal_attribute_name, mapping in self.from_internal_attributes.items():
if attribute_profile not in mapping:
logger.debug("no attribute mapping found for internal attribute '%s' the attribute profile '%s'" % (
internal_attribute_name, attribute_profile))
# skip this internal attribute if we have no mapping in the specified profile
continue
external_attribute_name = mapping[attribute_profile]
attribute_values = self._collate_attribute_values_by_priority_order(external_attribute_name,
external_dict)
if attribute_values: # Only insert key if it has some values
logger.debug("backend attribute '%s' mapped to %s" % (external_attribute_name,
internal_attribute_name))
internal_dict[internal_attribute_name] = attribute_values
else:
logger.debug("skipped backend attribute '%s': no value found", external_attribute_name)
internal_dict = self._handle_template_attributes(attribute_profile, internal_dict)
return internal_dict
|
python
|
def to_internal(self, attribute_profile, external_dict):
"""
Converts the external data from "type" to internal
:type attribute_profile: str
:type external_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_dict: Attributes in the external format
:return: Attributes in the internal format
"""
internal_dict = {}
for internal_attribute_name, mapping in self.from_internal_attributes.items():
if attribute_profile not in mapping:
logger.debug("no attribute mapping found for internal attribute '%s' the attribute profile '%s'" % (
internal_attribute_name, attribute_profile))
# skip this internal attribute if we have no mapping in the specified profile
continue
external_attribute_name = mapping[attribute_profile]
attribute_values = self._collate_attribute_values_by_priority_order(external_attribute_name,
external_dict)
if attribute_values: # Only insert key if it has some values
logger.debug("backend attribute '%s' mapped to %s" % (external_attribute_name,
internal_attribute_name))
internal_dict[internal_attribute_name] = attribute_values
else:
logger.debug("skipped backend attribute '%s': no value found", external_attribute_name)
internal_dict = self._handle_template_attributes(attribute_profile, internal_dict)
return internal_dict
|
[
"def",
"to_internal",
"(",
"self",
",",
"attribute_profile",
",",
"external_dict",
")",
":",
"internal_dict",
"=",
"{",
"}",
"for",
"internal_attribute_name",
",",
"mapping",
"in",
"self",
".",
"from_internal_attributes",
".",
"items",
"(",
")",
":",
"if",
"attribute_profile",
"not",
"in",
"mapping",
":",
"logger",
".",
"debug",
"(",
"\"no attribute mapping found for internal attribute '%s' the attribute profile '%s'\"",
"%",
"(",
"internal_attribute_name",
",",
"attribute_profile",
")",
")",
"# skip this internal attribute if we have no mapping in the specified profile",
"continue",
"external_attribute_name",
"=",
"mapping",
"[",
"attribute_profile",
"]",
"attribute_values",
"=",
"self",
".",
"_collate_attribute_values_by_priority_order",
"(",
"external_attribute_name",
",",
"external_dict",
")",
"if",
"attribute_values",
":",
"# Only insert key if it has some values",
"logger",
".",
"debug",
"(",
"\"backend attribute '%s' mapped to %s\"",
"%",
"(",
"external_attribute_name",
",",
"internal_attribute_name",
")",
")",
"internal_dict",
"[",
"internal_attribute_name",
"]",
"=",
"attribute_values",
"else",
":",
"logger",
".",
"debug",
"(",
"\"skipped backend attribute '%s': no value found\"",
",",
"external_attribute_name",
")",
"internal_dict",
"=",
"self",
".",
"_handle_template_attributes",
"(",
"attribute_profile",
",",
"internal_dict",
")",
"return",
"internal_dict"
] |
Converts the external data from "type" to internal
:type attribute_profile: str
:type external_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: From which external type to convert (ex: oidc, saml, ...)
:param external_dict: Attributes in the external format
:return: Attributes in the internal format
|
[
"Converts",
"the",
"external",
"data",
"from",
"type",
"to",
"internal"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/attribute_mapping.py#L75-L107
|
237,051
|
IdentityPython/SATOSA
|
src/satosa/attribute_mapping.py
|
AttributeMapper.from_internal
|
def from_internal(self, attribute_profile, internal_dict):
"""
Converts the internal data to "type"
:type attribute_profile: str
:type internal_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: To which external type to convert (ex: oidc, saml, ...)
:param internal_dict: attributes to map
:return: attribute values and names in the specified "profile"
"""
external_dict = {}
for internal_attribute_name in internal_dict:
try:
attribute_mapping = self.from_internal_attributes[internal_attribute_name]
except KeyError:
logger.debug("no attribute mapping found for the internal attribute '%s'", internal_attribute_name)
continue
if attribute_profile not in attribute_mapping:
# skip this internal attribute if we have no mapping in the specified profile
logger.debug("no mapping found for '%s' in attribute profile '%s'" %
(internal_attribute_name,
attribute_profile))
continue
external_attribute_names = self.from_internal_attributes[internal_attribute_name][attribute_profile]
# select the first attribute name
external_attribute_name = external_attribute_names[0]
logger.debug("frontend attribute %s mapped from %s" % (external_attribute_name,
internal_attribute_name))
if self.separator in external_attribute_name:
nested_attribute_names = external_attribute_name.split(self.separator)
nested_dict = self._create_nested_attribute_value(nested_attribute_names[1:],
internal_dict[internal_attribute_name])
external_dict[nested_attribute_names[0]] = nested_dict
else:
external_dict[external_attribute_name] = internal_dict[internal_attribute_name]
return external_dict
|
python
|
def from_internal(self, attribute_profile, internal_dict):
"""
Converts the internal data to "type"
:type attribute_profile: str
:type internal_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: To which external type to convert (ex: oidc, saml, ...)
:param internal_dict: attributes to map
:return: attribute values and names in the specified "profile"
"""
external_dict = {}
for internal_attribute_name in internal_dict:
try:
attribute_mapping = self.from_internal_attributes[internal_attribute_name]
except KeyError:
logger.debug("no attribute mapping found for the internal attribute '%s'", internal_attribute_name)
continue
if attribute_profile not in attribute_mapping:
# skip this internal attribute if we have no mapping in the specified profile
logger.debug("no mapping found for '%s' in attribute profile '%s'" %
(internal_attribute_name,
attribute_profile))
continue
external_attribute_names = self.from_internal_attributes[internal_attribute_name][attribute_profile]
# select the first attribute name
external_attribute_name = external_attribute_names[0]
logger.debug("frontend attribute %s mapped from %s" % (external_attribute_name,
internal_attribute_name))
if self.separator in external_attribute_name:
nested_attribute_names = external_attribute_name.split(self.separator)
nested_dict = self._create_nested_attribute_value(nested_attribute_names[1:],
internal_dict[internal_attribute_name])
external_dict[nested_attribute_names[0]] = nested_dict
else:
external_dict[external_attribute_name] = internal_dict[internal_attribute_name]
return external_dict
|
[
"def",
"from_internal",
"(",
"self",
",",
"attribute_profile",
",",
"internal_dict",
")",
":",
"external_dict",
"=",
"{",
"}",
"for",
"internal_attribute_name",
"in",
"internal_dict",
":",
"try",
":",
"attribute_mapping",
"=",
"self",
".",
"from_internal_attributes",
"[",
"internal_attribute_name",
"]",
"except",
"KeyError",
":",
"logger",
".",
"debug",
"(",
"\"no attribute mapping found for the internal attribute '%s'\"",
",",
"internal_attribute_name",
")",
"continue",
"if",
"attribute_profile",
"not",
"in",
"attribute_mapping",
":",
"# skip this internal attribute if we have no mapping in the specified profile",
"logger",
".",
"debug",
"(",
"\"no mapping found for '%s' in attribute profile '%s'\"",
"%",
"(",
"internal_attribute_name",
",",
"attribute_profile",
")",
")",
"continue",
"external_attribute_names",
"=",
"self",
".",
"from_internal_attributes",
"[",
"internal_attribute_name",
"]",
"[",
"attribute_profile",
"]",
"# select the first attribute name",
"external_attribute_name",
"=",
"external_attribute_names",
"[",
"0",
"]",
"logger",
".",
"debug",
"(",
"\"frontend attribute %s mapped from %s\"",
"%",
"(",
"external_attribute_name",
",",
"internal_attribute_name",
")",
")",
"if",
"self",
".",
"separator",
"in",
"external_attribute_name",
":",
"nested_attribute_names",
"=",
"external_attribute_name",
".",
"split",
"(",
"self",
".",
"separator",
")",
"nested_dict",
"=",
"self",
".",
"_create_nested_attribute_value",
"(",
"nested_attribute_names",
"[",
"1",
":",
"]",
",",
"internal_dict",
"[",
"internal_attribute_name",
"]",
")",
"external_dict",
"[",
"nested_attribute_names",
"[",
"0",
"]",
"]",
"=",
"nested_dict",
"else",
":",
"external_dict",
"[",
"external_attribute_name",
"]",
"=",
"internal_dict",
"[",
"internal_attribute_name",
"]",
"return",
"external_dict"
] |
Converts the internal data to "type"
:type attribute_profile: str
:type internal_dict: dict[str, str]
:rtype: dict[str, str]
:param attribute_profile: To which external type to convert (ex: oidc, saml, ...)
:param internal_dict: attributes to map
:return: attribute values and names in the specified "profile"
|
[
"Converts",
"the",
"internal",
"data",
"to",
"type"
] |
49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb
|
https://github.com/IdentityPython/SATOSA/blob/49da5d4c0ac1a5ebf1a71b4f7aaf04f0e52d8fdb/src/satosa/attribute_mapping.py#L167-L208
|
237,052
|
c4urself/bump2version
|
bumpversion/version_part.py
|
VersionConfig._serialize
|
def _serialize(self, version, serialize_format, context, raise_if_incomplete=False):
"""
Attempts to serialize a version with the given serialization format.
Raises MissingValueForSerializationException if not serializable
"""
values = context.copy()
for k in version:
values[k] = version[k]
# TODO dump complete context on debug level
try:
# test whether all parts required in the format have values
serialized = serialize_format.format(**values)
except KeyError as e:
missing_key = getattr(e, "message", e.args[0])
raise MissingValueForSerializationException(
"Did not find key {} in {} when serializing version number".format(
repr(missing_key), repr(version)
)
)
keys_needing_representation = set()
found_required = False
for k in self.order():
v = values[k]
if not isinstance(v, VersionPart):
# values coming from environment variables don't need
# representation
continue
if not v.is_optional():
found_required = True
keys_needing_representation.add(k)
elif not found_required:
keys_needing_representation.add(k)
required_by_format = set(self._labels_for_format(serialize_format))
# try whether all parsed keys are represented
if raise_if_incomplete:
if not (keys_needing_representation <= required_by_format):
raise IncompleteVersionRepresentationException(
"Could not represent '{}' in format '{}'".format(
"', '".join(keys_needing_representation ^ required_by_format),
serialize_format,
)
)
return serialized
|
python
|
def _serialize(self, version, serialize_format, context, raise_if_incomplete=False):
"""
Attempts to serialize a version with the given serialization format.
Raises MissingValueForSerializationException if not serializable
"""
values = context.copy()
for k in version:
values[k] = version[k]
# TODO dump complete context on debug level
try:
# test whether all parts required in the format have values
serialized = serialize_format.format(**values)
except KeyError as e:
missing_key = getattr(e, "message", e.args[0])
raise MissingValueForSerializationException(
"Did not find key {} in {} when serializing version number".format(
repr(missing_key), repr(version)
)
)
keys_needing_representation = set()
found_required = False
for k in self.order():
v = values[k]
if not isinstance(v, VersionPart):
# values coming from environment variables don't need
# representation
continue
if not v.is_optional():
found_required = True
keys_needing_representation.add(k)
elif not found_required:
keys_needing_representation.add(k)
required_by_format = set(self._labels_for_format(serialize_format))
# try whether all parsed keys are represented
if raise_if_incomplete:
if not (keys_needing_representation <= required_by_format):
raise IncompleteVersionRepresentationException(
"Could not represent '{}' in format '{}'".format(
"', '".join(keys_needing_representation ^ required_by_format),
serialize_format,
)
)
return serialized
|
[
"def",
"_serialize",
"(",
"self",
",",
"version",
",",
"serialize_format",
",",
"context",
",",
"raise_if_incomplete",
"=",
"False",
")",
":",
"values",
"=",
"context",
".",
"copy",
"(",
")",
"for",
"k",
"in",
"version",
":",
"values",
"[",
"k",
"]",
"=",
"version",
"[",
"k",
"]",
"# TODO dump complete context on debug level",
"try",
":",
"# test whether all parts required in the format have values",
"serialized",
"=",
"serialize_format",
".",
"format",
"(",
"*",
"*",
"values",
")",
"except",
"KeyError",
"as",
"e",
":",
"missing_key",
"=",
"getattr",
"(",
"e",
",",
"\"message\"",
",",
"e",
".",
"args",
"[",
"0",
"]",
")",
"raise",
"MissingValueForSerializationException",
"(",
"\"Did not find key {} in {} when serializing version number\"",
".",
"format",
"(",
"repr",
"(",
"missing_key",
")",
",",
"repr",
"(",
"version",
")",
")",
")",
"keys_needing_representation",
"=",
"set",
"(",
")",
"found_required",
"=",
"False",
"for",
"k",
"in",
"self",
".",
"order",
"(",
")",
":",
"v",
"=",
"values",
"[",
"k",
"]",
"if",
"not",
"isinstance",
"(",
"v",
",",
"VersionPart",
")",
":",
"# values coming from environment variables don't need",
"# representation",
"continue",
"if",
"not",
"v",
".",
"is_optional",
"(",
")",
":",
"found_required",
"=",
"True",
"keys_needing_representation",
".",
"add",
"(",
"k",
")",
"elif",
"not",
"found_required",
":",
"keys_needing_representation",
".",
"add",
"(",
"k",
")",
"required_by_format",
"=",
"set",
"(",
"self",
".",
"_labels_for_format",
"(",
"serialize_format",
")",
")",
"# try whether all parsed keys are represented",
"if",
"raise_if_incomplete",
":",
"if",
"not",
"(",
"keys_needing_representation",
"<=",
"required_by_format",
")",
":",
"raise",
"IncompleteVersionRepresentationException",
"(",
"\"Could not represent '{}' in format '{}'\"",
".",
"format",
"(",
"\"', '\"",
".",
"join",
"(",
"keys_needing_representation",
"^",
"required_by_format",
")",
",",
"serialize_format",
",",
")",
")",
"return",
"serialized"
] |
Attempts to serialize a version with the given serialization format.
Raises MissingValueForSerializationException if not serializable
|
[
"Attempts",
"to",
"serialize",
"a",
"version",
"with",
"the",
"given",
"serialization",
"format",
"."
] |
22d981ebfb94a7d26716e2b936f932a58883aa30
|
https://github.com/c4urself/bump2version/blob/22d981ebfb94a7d26716e2b936f932a58883aa30/bumpversion/version_part.py#L194-L247
|
237,053
|
lawsie/guizero
|
guizero/ButtonGroup.py
|
ButtonGroup.value_text
|
def value_text(self):
"""
Sets or returns the option selected in a ButtonGroup by its text value.
"""
search = self._selected.get() # a string containing the selected option
# This is a bit nasty - suggestions welcome
for item in self._rbuttons:
if item.value == search:
return item.text
return ""
|
python
|
def value_text(self):
"""
Sets or returns the option selected in a ButtonGroup by its text value.
"""
search = self._selected.get() # a string containing the selected option
# This is a bit nasty - suggestions welcome
for item in self._rbuttons:
if item.value == search:
return item.text
return ""
|
[
"def",
"value_text",
"(",
"self",
")",
":",
"search",
"=",
"self",
".",
"_selected",
".",
"get",
"(",
")",
"# a string containing the selected option",
"# This is a bit nasty - suggestions welcome",
"for",
"item",
"in",
"self",
".",
"_rbuttons",
":",
"if",
"item",
".",
"value",
"==",
"search",
":",
"return",
"item",
".",
"text",
"return",
"\"\""
] |
Sets or returns the option selected in a ButtonGroup by its text value.
|
[
"Sets",
"or",
"returns",
"the",
"option",
"selected",
"in",
"a",
"ButtonGroup",
"by",
"its",
"text",
"value",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L171-L180
|
237,054
|
lawsie/guizero
|
guizero/ButtonGroup.py
|
ButtonGroup.append
|
def append(self, option):
"""
Appends a new `option` to the end of the ButtonGroup.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.append(self._parse_option(option))
self._refresh_options()
self.resize(self._width, self._height)
|
python
|
def append(self, option):
"""
Appends a new `option` to the end of the ButtonGroup.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.append(self._parse_option(option))
self._refresh_options()
self.resize(self._width, self._height)
|
[
"def",
"append",
"(",
"self",
",",
"option",
")",
":",
"self",
".",
"_options",
".",
"append",
"(",
"self",
".",
"_parse_option",
"(",
"option",
")",
")",
"self",
".",
"_refresh_options",
"(",
")",
"self",
".",
"resize",
"(",
"self",
".",
"_width",
",",
"self",
".",
"_height",
")"
] |
Appends a new `option` to the end of the ButtonGroup.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
|
[
"Appends",
"a",
"new",
"option",
"to",
"the",
"end",
"of",
"the",
"ButtonGroup",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L235-L245
|
237,055
|
lawsie/guizero
|
guizero/ButtonGroup.py
|
ButtonGroup.insert
|
def insert(self, index, option):
"""
Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.insert(index, self._parse_option(option))
self._refresh_options()
self.resize(self._width, self._height)
|
python
|
def insert(self, index, option):
"""
Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
"""
self._options.insert(index, self._parse_option(option))
self._refresh_options()
self.resize(self._width, self._height)
|
[
"def",
"insert",
"(",
"self",
",",
"index",
",",
"option",
")",
":",
"self",
".",
"_options",
".",
"insert",
"(",
"index",
",",
"self",
".",
"_parse_option",
"(",
"option",
")",
")",
"self",
".",
"_refresh_options",
"(",
")",
"self",
".",
"resize",
"(",
"self",
".",
"_width",
",",
"self",
".",
"_height",
")"
] |
Insert a new `option` in the ButtonGroup at `index`.
:param int option:
The index of where to insert the option.
:param string/List option:
The option to append to the ButtonGroup. If a 2D list is specified,
the first element is the text, the second is the value.
|
[
"Insert",
"a",
"new",
"option",
"in",
"the",
"ButtonGroup",
"at",
"index",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L247-L260
|
237,056
|
lawsie/guizero
|
guizero/ButtonGroup.py
|
ButtonGroup.remove
|
def remove(self, option):
"""
Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup.
"""
for existing_option in self._options:
if existing_option[1] == option:
self._options.remove(existing_option)
self._refresh_options()
return True
return False
|
python
|
def remove(self, option):
"""
Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup.
"""
for existing_option in self._options:
if existing_option[1] == option:
self._options.remove(existing_option)
self._refresh_options()
return True
return False
|
[
"def",
"remove",
"(",
"self",
",",
"option",
")",
":",
"for",
"existing_option",
"in",
"self",
".",
"_options",
":",
"if",
"existing_option",
"[",
"1",
"]",
"==",
"option",
":",
"self",
".",
"_options",
".",
"remove",
"(",
"existing_option",
")",
"self",
".",
"_refresh_options",
"(",
")",
"return",
"True",
"return",
"False"
] |
Removes the first `option` from the ButtonGroup.
Returns `True` if an item was removed.
:param string option:
The value of the option to remove from the ButtonGroup.
|
[
"Removes",
"the",
"first",
"option",
"from",
"the",
"ButtonGroup",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L262-L276
|
237,057
|
lawsie/guizero
|
guizero/ButtonGroup.py
|
ButtonGroup.update_command
|
def update_command(self, command, args=None):
"""
Updates the callback command which is called when the ButtonGroup
changes.
Setting to `None` stops the callback.
:param callback command:
The callback function to call.
:param callback args:
A list of arguments to pass to the widgets `command`, defaults to
`None`.
"""
if command is None:
self._command = lambda: None
else:
if args is None:
self._command = command
else:
self._command = utils.with_args(command, *args)
|
python
|
def update_command(self, command, args=None):
"""
Updates the callback command which is called when the ButtonGroup
changes.
Setting to `None` stops the callback.
:param callback command:
The callback function to call.
:param callback args:
A list of arguments to pass to the widgets `command`, defaults to
`None`.
"""
if command is None:
self._command = lambda: None
else:
if args is None:
self._command = command
else:
self._command = utils.with_args(command, *args)
|
[
"def",
"update_command",
"(",
"self",
",",
"command",
",",
"args",
"=",
"None",
")",
":",
"if",
"command",
"is",
"None",
":",
"self",
".",
"_command",
"=",
"lambda",
":",
"None",
"else",
":",
"if",
"args",
"is",
"None",
":",
"self",
".",
"_command",
"=",
"command",
"else",
":",
"self",
".",
"_command",
"=",
"utils",
".",
"with_args",
"(",
"command",
",",
"*",
"args",
")"
] |
Updates the callback command which is called when the ButtonGroup
changes.
Setting to `None` stops the callback.
:param callback command:
The callback function to call.
:param callback args:
A list of arguments to pass to the widgets `command`, defaults to
`None`.
|
[
"Updates",
"the",
"callback",
"command",
"which",
"is",
"called",
"when",
"the",
"ButtonGroup",
"changes",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/ButtonGroup.py#L290-L310
|
237,058
|
lawsie/guizero
|
guizero/Combo.py
|
Combo.insert
|
def insert(self, index, option):
"""
Insert a new `option` in the Combo at `index`.
:param int option:
The index of where to insert the option.
:param string option:
The option to insert into to the Combo.
"""
option = str(option)
self._options.insert(index, option)
# if this is the first option, set it.
if len(self._options) == 1:
self.value = option
self._refresh_options()
|
python
|
def insert(self, index, option):
"""
Insert a new `option` in the Combo at `index`.
:param int option:
The index of where to insert the option.
:param string option:
The option to insert into to the Combo.
"""
option = str(option)
self._options.insert(index, option)
# if this is the first option, set it.
if len(self._options) == 1:
self.value = option
self._refresh_options()
|
[
"def",
"insert",
"(",
"self",
",",
"index",
",",
"option",
")",
":",
"option",
"=",
"str",
"(",
"option",
")",
"self",
".",
"_options",
".",
"insert",
"(",
"index",
",",
"option",
")",
"# if this is the first option, set it.",
"if",
"len",
"(",
"self",
".",
"_options",
")",
"==",
"1",
":",
"self",
".",
"value",
"=",
"option",
"self",
".",
"_refresh_options",
"(",
")"
] |
Insert a new `option` in the Combo at `index`.
:param int option:
The index of where to insert the option.
:param string option:
The option to insert into to the Combo.
|
[
"Insert",
"a",
"new",
"option",
"in",
"the",
"Combo",
"at",
"index",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L204-L220
|
237,059
|
lawsie/guizero
|
guizero/Combo.py
|
Combo.remove
|
def remove(self, option):
"""
Removes the first `option` from the Combo.
Returns `True` if an item was removed.
:param string option:
The option to remove from the Combo.
"""
if option in self._options:
if len(self._options) == 1:
# this is the last option in the list so clear it
self.clear()
else:
self._options.remove(option)
self._refresh_options()
# have we just removed the selected option?
# if so set it to the first option
if option == self.value:
self._set_option(self._options[0])
return True
else:
return False
|
python
|
def remove(self, option):
"""
Removes the first `option` from the Combo.
Returns `True` if an item was removed.
:param string option:
The option to remove from the Combo.
"""
if option in self._options:
if len(self._options) == 1:
# this is the last option in the list so clear it
self.clear()
else:
self._options.remove(option)
self._refresh_options()
# have we just removed the selected option?
# if so set it to the first option
if option == self.value:
self._set_option(self._options[0])
return True
else:
return False
|
[
"def",
"remove",
"(",
"self",
",",
"option",
")",
":",
"if",
"option",
"in",
"self",
".",
"_options",
":",
"if",
"len",
"(",
"self",
".",
"_options",
")",
"==",
"1",
":",
"# this is the last option in the list so clear it",
"self",
".",
"clear",
"(",
")",
"else",
":",
"self",
".",
"_options",
".",
"remove",
"(",
"option",
")",
"self",
".",
"_refresh_options",
"(",
")",
"# have we just removed the selected option?",
"# if so set it to the first option",
"if",
"option",
"==",
"self",
".",
"value",
":",
"self",
".",
"_set_option",
"(",
"self",
".",
"_options",
"[",
"0",
"]",
")",
"return",
"True",
"else",
":",
"return",
"False"
] |
Removes the first `option` from the Combo.
Returns `True` if an item was removed.
:param string option:
The option to remove from the Combo.
|
[
"Removes",
"the",
"first",
"option",
"from",
"the",
"Combo",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L222-L244
|
237,060
|
lawsie/guizero
|
guizero/Combo.py
|
Combo.clear
|
def clear(self):
"""
Clears all the options in a Combo
"""
self._options = []
self._combo_menu.tk.delete(0, END)
self._selected.set("")
|
python
|
def clear(self):
"""
Clears all the options in a Combo
"""
self._options = []
self._combo_menu.tk.delete(0, END)
self._selected.set("")
|
[
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"_options",
"=",
"[",
"]",
"self",
".",
"_combo_menu",
".",
"tk",
".",
"delete",
"(",
"0",
",",
"END",
")",
"self",
".",
"_selected",
".",
"set",
"(",
"\"\"",
")"
] |
Clears all the options in a Combo
|
[
"Clears",
"all",
"the",
"options",
"in",
"a",
"Combo"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L247-L253
|
237,061
|
lawsie/guizero
|
guizero/Combo.py
|
Combo._set_option
|
def _set_option(self, value):
"""
Sets a single option in the Combo, returning True if it was able too.
"""
if len(self._options) > 0:
if value in self._options:
self._selected.set(value)
return True
else:
return False
else:
return False
|
python
|
def _set_option(self, value):
"""
Sets a single option in the Combo, returning True if it was able too.
"""
if len(self._options) > 0:
if value in self._options:
self._selected.set(value)
return True
else:
return False
else:
return False
|
[
"def",
"_set_option",
"(",
"self",
",",
"value",
")",
":",
"if",
"len",
"(",
"self",
".",
"_options",
")",
">",
"0",
":",
"if",
"value",
"in",
"self",
".",
"_options",
":",
"self",
".",
"_selected",
".",
"set",
"(",
"value",
")",
"return",
"True",
"else",
":",
"return",
"False",
"else",
":",
"return",
"False"
] |
Sets a single option in the Combo, returning True if it was able too.
|
[
"Sets",
"a",
"single",
"option",
"in",
"the",
"Combo",
"returning",
"True",
"if",
"it",
"was",
"able",
"too",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L271-L282
|
237,062
|
lawsie/guizero
|
guizero/Combo.py
|
Combo._set_option_by_index
|
def _set_option_by_index(self, index):
"""
Sets a single option in the Combo by its index, returning True if it was able too.
"""
if index < len(self._options):
self._selected.set(self._options[index])
return True
else:
return False
|
python
|
def _set_option_by_index(self, index):
"""
Sets a single option in the Combo by its index, returning True if it was able too.
"""
if index < len(self._options):
self._selected.set(self._options[index])
return True
else:
return False
|
[
"def",
"_set_option_by_index",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"<",
"len",
"(",
"self",
".",
"_options",
")",
":",
"self",
".",
"_selected",
".",
"set",
"(",
"self",
".",
"_options",
"[",
"index",
"]",
")",
"return",
"True",
"else",
":",
"return",
"False"
] |
Sets a single option in the Combo by its index, returning True if it was able too.
|
[
"Sets",
"a",
"single",
"option",
"in",
"the",
"Combo",
"by",
"its",
"index",
"returning",
"True",
"if",
"it",
"was",
"able",
"too",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Combo.py#L284-L292
|
237,063
|
lawsie/guizero
|
guizero/tkmixins.py
|
ScheduleMixin.after
|
def after(self, time, function, args = []):
"""Call `function` after `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, False]
|
python
|
def after(self, time, function, args = []):
"""Call `function` after `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, False]
|
[
"def",
"after",
"(",
"self",
",",
"time",
",",
"function",
",",
"args",
"=",
"[",
"]",
")",
":",
"callback_id",
"=",
"self",
".",
"tk",
".",
"after",
"(",
"time",
",",
"self",
".",
"_call_wrapper",
",",
"time",
",",
"function",
",",
"*",
"args",
")",
"self",
".",
"_callback",
"[",
"function",
"]",
"=",
"[",
"callback_id",
",",
"False",
"]"
] |
Call `function` after `time` milliseconds.
|
[
"Call",
"function",
"after",
"time",
"milliseconds",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L8-L11
|
237,064
|
lawsie/guizero
|
guizero/tkmixins.py
|
ScheduleMixin.repeat
|
def repeat(self, time, function, args = []):
"""Repeat `function` every `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, True]
|
python
|
def repeat(self, time, function, args = []):
"""Repeat `function` every `time` milliseconds."""
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function] = [callback_id, True]
|
[
"def",
"repeat",
"(",
"self",
",",
"time",
",",
"function",
",",
"args",
"=",
"[",
"]",
")",
":",
"callback_id",
"=",
"self",
".",
"tk",
".",
"after",
"(",
"time",
",",
"self",
".",
"_call_wrapper",
",",
"time",
",",
"function",
",",
"*",
"args",
")",
"self",
".",
"_callback",
"[",
"function",
"]",
"=",
"[",
"callback_id",
",",
"True",
"]"
] |
Repeat `function` every `time` milliseconds.
|
[
"Repeat",
"function",
"every",
"time",
"milliseconds",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L13-L16
|
237,065
|
lawsie/guizero
|
guizero/tkmixins.py
|
ScheduleMixin.cancel
|
def cancel(self, function):
"""Cancel the scheduled `function` calls."""
if function in self._callback.keys():
callback_id = self._callback[function][0]
self.tk.after_cancel(callback_id)
self._callback.pop(function)
else:
utils.error_format("Could not cancel function - it doesnt exist, it may have already run")
|
python
|
def cancel(self, function):
"""Cancel the scheduled `function` calls."""
if function in self._callback.keys():
callback_id = self._callback[function][0]
self.tk.after_cancel(callback_id)
self._callback.pop(function)
else:
utils.error_format("Could not cancel function - it doesnt exist, it may have already run")
|
[
"def",
"cancel",
"(",
"self",
",",
"function",
")",
":",
"if",
"function",
"in",
"self",
".",
"_callback",
".",
"keys",
"(",
")",
":",
"callback_id",
"=",
"self",
".",
"_callback",
"[",
"function",
"]",
"[",
"0",
"]",
"self",
".",
"tk",
".",
"after_cancel",
"(",
"callback_id",
")",
"self",
".",
"_callback",
".",
"pop",
"(",
"function",
")",
"else",
":",
"utils",
".",
"error_format",
"(",
"\"Could not cancel function - it doesnt exist, it may have already run\"",
")"
] |
Cancel the scheduled `function` calls.
|
[
"Cancel",
"the",
"scheduled",
"function",
"calls",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L18-L25
|
237,066
|
lawsie/guizero
|
guizero/tkmixins.py
|
ScheduleMixin._call_wrapper
|
def _call_wrapper(self, time, function, *args):
"""Fired by tk.after, gets the callback and either executes the function and cancels or repeats"""
# execute the function
function(*args)
if function in self._callback.keys():
repeat = self._callback[function][1]
if repeat:
# setup the call back again and update the id
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function][0] = callback_id
else:
# remove it from the call back dictionary
self._callback.pop(function)
|
python
|
def _call_wrapper(self, time, function, *args):
"""Fired by tk.after, gets the callback and either executes the function and cancels or repeats"""
# execute the function
function(*args)
if function in self._callback.keys():
repeat = self._callback[function][1]
if repeat:
# setup the call back again and update the id
callback_id = self.tk.after(time, self._call_wrapper, time, function, *args)
self._callback[function][0] = callback_id
else:
# remove it from the call back dictionary
self._callback.pop(function)
|
[
"def",
"_call_wrapper",
"(",
"self",
",",
"time",
",",
"function",
",",
"*",
"args",
")",
":",
"# execute the function",
"function",
"(",
"*",
"args",
")",
"if",
"function",
"in",
"self",
".",
"_callback",
".",
"keys",
"(",
")",
":",
"repeat",
"=",
"self",
".",
"_callback",
"[",
"function",
"]",
"[",
"1",
"]",
"if",
"repeat",
":",
"# setup the call back again and update the id",
"callback_id",
"=",
"self",
".",
"tk",
".",
"after",
"(",
"time",
",",
"self",
".",
"_call_wrapper",
",",
"time",
",",
"function",
",",
"*",
"args",
")",
"self",
".",
"_callback",
"[",
"function",
"]",
"[",
"0",
"]",
"=",
"callback_id",
"else",
":",
"# remove it from the call back dictionary",
"self",
".",
"_callback",
".",
"pop",
"(",
"function",
")"
] |
Fired by tk.after, gets the callback and either executes the function and cancels or repeats
|
[
"Fired",
"by",
"tk",
".",
"after",
"gets",
"the",
"callback",
"and",
"either",
"executes",
"the",
"function",
"and",
"cancels",
"or",
"repeats"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/tkmixins.py#L27-L39
|
237,067
|
lawsie/guizero
|
guizero/event.py
|
EventCallback.rebind
|
def rebind(self, tks):
"""
Rebinds the tk event, only used if a widget has been destroyed
and recreated.
"""
self._tks = tks
for tk in self._tks:
tk.unbind_all(self._tk_event)
func_id = tk.bind(self._tk_event, self._event_callback)
self._func_ids.append(func_id)
|
python
|
def rebind(self, tks):
"""
Rebinds the tk event, only used if a widget has been destroyed
and recreated.
"""
self._tks = tks
for tk in self._tks:
tk.unbind_all(self._tk_event)
func_id = tk.bind(self._tk_event, self._event_callback)
self._func_ids.append(func_id)
|
[
"def",
"rebind",
"(",
"self",
",",
"tks",
")",
":",
"self",
".",
"_tks",
"=",
"tks",
"for",
"tk",
"in",
"self",
".",
"_tks",
":",
"tk",
".",
"unbind_all",
"(",
"self",
".",
"_tk_event",
")",
"func_id",
"=",
"tk",
".",
"bind",
"(",
"self",
".",
"_tk_event",
",",
"self",
".",
"_event_callback",
")",
"self",
".",
"_func_ids",
".",
"append",
"(",
"func_id",
")"
] |
Rebinds the tk event, only used if a widget has been destroyed
and recreated.
|
[
"Rebinds",
"the",
"tk",
"event",
"only",
"used",
"if",
"a",
"widget",
"has",
"been",
"destroyed",
"and",
"recreated",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/event.py#L129-L138
|
237,068
|
lawsie/guizero
|
guizero/event.py
|
EventManager.rebind_events
|
def rebind_events(self, *tks):
"""
Rebinds all the tk events, only used if a tk widget has been destroyed
and recreated.
"""
for ref in self._refs:
self._refs[ref].rebind(tks)
|
python
|
def rebind_events(self, *tks):
"""
Rebinds all the tk events, only used if a tk widget has been destroyed
and recreated.
"""
for ref in self._refs:
self._refs[ref].rebind(tks)
|
[
"def",
"rebind_events",
"(",
"self",
",",
"*",
"tks",
")",
":",
"for",
"ref",
"in",
"self",
".",
"_refs",
":",
"self",
".",
"_refs",
"[",
"ref",
"]",
".",
"rebind",
"(",
"tks",
")"
] |
Rebinds all the tk events, only used if a tk widget has been destroyed
and recreated.
|
[
"Rebinds",
"all",
"the",
"tk",
"events",
"only",
"used",
"if",
"a",
"tk",
"widget",
"has",
"been",
"destroyed",
"and",
"recreated",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/event.py#L200-L206
|
237,069
|
lawsie/guizero
|
guizero/Box.py
|
Box.set_border
|
def set_border(self, thickness, color="black"):
"""
Sets the border thickness and color.
:param int thickness:
The thickenss of the border.
:param str color:
The color of the border.
"""
self._set_tk_config("highlightthickness", thickness)
self._set_tk_config("highlightbackground", utils.convert_color(color))
|
python
|
def set_border(self, thickness, color="black"):
"""
Sets the border thickness and color.
:param int thickness:
The thickenss of the border.
:param str color:
The color of the border.
"""
self._set_tk_config("highlightthickness", thickness)
self._set_tk_config("highlightbackground", utils.convert_color(color))
|
[
"def",
"set_border",
"(",
"self",
",",
"thickness",
",",
"color",
"=",
"\"black\"",
")",
":",
"self",
".",
"_set_tk_config",
"(",
"\"highlightthickness\"",
",",
"thickness",
")",
"self",
".",
"_set_tk_config",
"(",
"\"highlightbackground\"",
",",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] |
Sets the border thickness and color.
:param int thickness:
The thickenss of the border.
:param str color:
The color of the border.
|
[
"Sets",
"the",
"border",
"thickness",
"and",
"color",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Box.py#L87-L98
|
237,070
|
lawsie/guizero
|
guizero/Window.py
|
Window.hide
|
def hide(self):
"""Hide the window."""
self.tk.withdraw()
self._visible = False
if self._modal:
self.tk.grab_release()
|
python
|
def hide(self):
"""Hide the window."""
self.tk.withdraw()
self._visible = False
if self._modal:
self.tk.grab_release()
|
[
"def",
"hide",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"withdraw",
"(",
")",
"self",
".",
"_visible",
"=",
"False",
"if",
"self",
".",
"_modal",
":",
"self",
".",
"tk",
".",
"grab_release",
"(",
")"
] |
Hide the window.
|
[
"Hide",
"the",
"window",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Window.py#L32-L37
|
237,071
|
lawsie/guizero
|
guizero/Window.py
|
Window.show
|
def show(self, wait = False):
"""Show the window."""
self.tk.deiconify()
self._visible = True
self._modal = wait
if self._modal:
self.tk.grab_set()
|
python
|
def show(self, wait = False):
"""Show the window."""
self.tk.deiconify()
self._visible = True
self._modal = wait
if self._modal:
self.tk.grab_set()
|
[
"def",
"show",
"(",
"self",
",",
"wait",
"=",
"False",
")",
":",
"self",
".",
"tk",
".",
"deiconify",
"(",
")",
"self",
".",
"_visible",
"=",
"True",
"self",
".",
"_modal",
"=",
"wait",
"if",
"self",
".",
"_modal",
":",
"self",
".",
"tk",
".",
"grab_set",
"(",
")"
] |
Show the window.
|
[
"Show",
"the",
"window",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Window.py#L39-L45
|
237,072
|
lawsie/guizero
|
guizero/App.py
|
App.destroy
|
def destroy(self):
"""
Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used.
"""
# if this is the main_app - set the _main_app class variable to `None`.
if self == App._main_app:
App._main_app = None
self.tk.destroy()
|
python
|
def destroy(self):
"""
Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used.
"""
# if this is the main_app - set the _main_app class variable to `None`.
if self == App._main_app:
App._main_app = None
self.tk.destroy()
|
[
"def",
"destroy",
"(",
"self",
")",
":",
"# if this is the main_app - set the _main_app class variable to `None`.",
"if",
"self",
"==",
"App",
".",
"_main_app",
":",
"App",
".",
"_main_app",
"=",
"None",
"self",
".",
"tk",
".",
"destroy",
"(",
")"
] |
Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used.
|
[
"Destroy",
"and",
"close",
"the",
"App",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/App.py#L51-L64
|
237,073
|
lawsie/guizero
|
guizero/Drawing.py
|
Drawing.line
|
def line(self, x1, y1, x2, y2, color="black", width=1):
"""
Draws a line between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the line. Defaults to `"black"`.
:param int width:
The width of the line. Defaults to `1`.
:return:
The id of the line.
"""
return self.tk.create_line(
x1, y1, x2, y2,
width = width,
fill = "" if color is None else utils.convert_color(color)
)
|
python
|
def line(self, x1, y1, x2, y2, color="black", width=1):
"""
Draws a line between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the line. Defaults to `"black"`.
:param int width:
The width of the line. Defaults to `1`.
:return:
The id of the line.
"""
return self.tk.create_line(
x1, y1, x2, y2,
width = width,
fill = "" if color is None else utils.convert_color(color)
)
|
[
"def",
"line",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"color",
"=",
"\"black\"",
",",
"width",
"=",
"1",
")",
":",
"return",
"self",
".",
"tk",
".",
"create_line",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"width",
"=",
"width",
",",
"fill",
"=",
"\"\"",
"if",
"color",
"is",
"None",
"else",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] |
Draws a line between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the line. Defaults to `"black"`.
:param int width:
The width of the line. Defaults to `1`.
:return:
The id of the line.
|
[
"Draws",
"a",
"line",
"between",
"2",
"points"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L49-L78
|
237,074
|
lawsie/guizero
|
guizero/Drawing.py
|
Drawing.oval
|
def oval(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws an oval between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_oval(
x1, y1, x2, y2,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
)
|
python
|
def oval(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws an oval between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_oval(
x1, y1, x2, y2,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
)
|
[
"def",
"oval",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"color",
"=",
"\"black\"",
",",
"outline",
"=",
"False",
",",
"outline_color",
"=",
"\"black\"",
")",
":",
"return",
"self",
".",
"tk",
".",
"create_oval",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"outline",
"=",
"utils",
".",
"convert_color",
"(",
"outline_color",
")",
"if",
"outline",
"else",
"\"\"",
",",
"width",
"=",
"int",
"(",
"outline",
")",
",",
"fill",
"=",
"\"\"",
"if",
"color",
"is",
"None",
"else",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] |
Draws an oval between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
|
[
"Draws",
"an",
"oval",
"between",
"2",
"points"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L80-L113
|
237,075
|
lawsie/guizero
|
guizero/Drawing.py
|
Drawing.rectangle
|
def rectangle(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_rectangle(
x1, y1, x2, y2,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
)
|
python
|
def rectangle(self, x1, y1, x2, y2, color="black", outline=False, outline_color="black"):
"""
Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_rectangle(
x1, y1, x2, y2,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
)
|
[
"def",
"rectangle",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"color",
"=",
"\"black\"",
",",
"outline",
"=",
"False",
",",
"outline_color",
"=",
"\"black\"",
")",
":",
"return",
"self",
".",
"tk",
".",
"create_rectangle",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"outline",
"=",
"utils",
".",
"convert_color",
"(",
"outline_color",
")",
"if",
"outline",
"else",
"\"\"",
",",
"width",
"=",
"int",
"(",
"outline",
")",
",",
"fill",
"=",
"\"\"",
"if",
"color",
"is",
"None",
"else",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] |
Draws a rectangle between 2 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the end point.
:param int y2:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
|
[
"Draws",
"a",
"rectangle",
"between",
"2",
"points"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L115-L148
|
237,076
|
lawsie/guizero
|
guizero/Drawing.py
|
Drawing.polygon
|
def polygon(self, *coords, color="black", outline=False, outline_color="black"):
"""
Draws a polygon from an list of co-ordinates
:param int *coords:
Pairs of x and y positions which make up the polygon.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_polygon(
*coords,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
)
|
python
|
def polygon(self, *coords, color="black", outline=False, outline_color="black"):
"""
Draws a polygon from an list of co-ordinates
:param int *coords:
Pairs of x and y positions which make up the polygon.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.tk.create_polygon(
*coords,
outline = utils.convert_color(outline_color) if outline else "",
width = int(outline),
fill = "" if color is None else utils.convert_color(color)
)
|
[
"def",
"polygon",
"(",
"self",
",",
"*",
"coords",
",",
"color",
"=",
"\"black\"",
",",
"outline",
"=",
"False",
",",
"outline_color",
"=",
"\"black\"",
")",
":",
"return",
"self",
".",
"tk",
".",
"create_polygon",
"(",
"*",
"coords",
",",
"outline",
"=",
"utils",
".",
"convert_color",
"(",
"outline_color",
")",
"if",
"outline",
"else",
"\"\"",
",",
"width",
"=",
"int",
"(",
"outline",
")",
",",
"fill",
"=",
"\"\"",
"if",
"color",
"is",
"None",
"else",
"utils",
".",
"convert_color",
"(",
"color",
")",
")"
] |
Draws a polygon from an list of co-ordinates
:param int *coords:
Pairs of x and y positions which make up the polygon.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
|
[
"Draws",
"a",
"polygon",
"from",
"an",
"list",
"of",
"co",
"-",
"ordinates"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L150-L174
|
237,077
|
lawsie/guizero
|
guizero/Drawing.py
|
Drawing.triangle
|
def triangle(self, x1, y1, x2, y2, x3, y3, color="black", outline=False, outline_color="black"):
"""
Draws a triangle between 3 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the middle point.
:param int y2:
The y position of the middle point.
:param int x3:
The x position of the end point.
:param int y3:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.polygon(
x1, y1, x2, y2, x3, y3,
color=color,
outline=outline,
outline_color=outline_color)
|
python
|
def triangle(self, x1, y1, x2, y2, x3, y3, color="black", outline=False, outline_color="black"):
"""
Draws a triangle between 3 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the middle point.
:param int y2:
The y position of the middle point.
:param int x3:
The x position of the end point.
:param int y3:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
"""
return self.polygon(
x1, y1, x2, y2, x3, y3,
color=color,
outline=outline,
outline_color=outline_color)
|
[
"def",
"triangle",
"(",
"self",
",",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
",",
"color",
"=",
"\"black\"",
",",
"outline",
"=",
"False",
",",
"outline_color",
"=",
"\"black\"",
")",
":",
"return",
"self",
".",
"polygon",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
",",
"x3",
",",
"y3",
",",
"color",
"=",
"color",
",",
"outline",
"=",
"outline",
",",
"outline_color",
"=",
"outline_color",
")"
] |
Draws a triangle between 3 points
:param int x1:
The x position of the starting point.
:param int y1:
The y position of the starting point.
:param int x2:
The x position of the middle point.
:param int y2:
The y position of the middle point.
:param int x3:
The x position of the end point.
:param int y3:
The y position of the end point.
:param str color:
The color of the shape. Defaults to `"black"`.
:param int outline:
`0` or `False` is no outline. `True` or value > 1 sets an outline. Defaults to `False`.
:param str outline_color:
The color of the outline. Defaults to `"black"`.
:return:
The id of the shape.
|
[
"Draws",
"a",
"triangle",
"between",
"3",
"points"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/Drawing.py#L176-L214
|
237,078
|
lawsie/guizero
|
guizero/base.py
|
Base._get_tk_config
|
def _get_tk_config(self, key, default=False):
"""
Gets the config from the widget's tk object.
:param string key:
The tk config key.
:param bool default:
Returns the default value for this key. Defaults to `False`.
"""
if default:
return self._tk_defaults[key]
else:
return self.tk[key]
|
python
|
def _get_tk_config(self, key, default=False):
"""
Gets the config from the widget's tk object.
:param string key:
The tk config key.
:param bool default:
Returns the default value for this key. Defaults to `False`.
"""
if default:
return self._tk_defaults[key]
else:
return self.tk[key]
|
[
"def",
"_get_tk_config",
"(",
"self",
",",
"key",
",",
"default",
"=",
"False",
")",
":",
"if",
"default",
":",
"return",
"self",
".",
"_tk_defaults",
"[",
"key",
"]",
"else",
":",
"return",
"self",
".",
"tk",
"[",
"key",
"]"
] |
Gets the config from the widget's tk object.
:param string key:
The tk config key.
:param bool default:
Returns the default value for this key. Defaults to `False`.
|
[
"Gets",
"the",
"config",
"from",
"the",
"widget",
"s",
"tk",
"object",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L62-L75
|
237,079
|
lawsie/guizero
|
guizero/base.py
|
Base._set_tk_config
|
def _set_tk_config(self, keys, value):
"""
Gets the config from the widget's tk object
:param string/List keys:
The tk config key or a list of tk keys.
:param variable value:
The value to set. If the value is `None`, the config value will be
reset to its default.
"""
# if a single key is passed, convert to list
if isinstance(keys, str):
keys = [keys]
# loop through all the keys
for key in keys:
if key in self.tk.keys():
if value is None:
# reset to default
self.tk[key] = self._tk_defaults[key]
else:
self.tk[key] = value
|
python
|
def _set_tk_config(self, keys, value):
"""
Gets the config from the widget's tk object
:param string/List keys:
The tk config key or a list of tk keys.
:param variable value:
The value to set. If the value is `None`, the config value will be
reset to its default.
"""
# if a single key is passed, convert to list
if isinstance(keys, str):
keys = [keys]
# loop through all the keys
for key in keys:
if key in self.tk.keys():
if value is None:
# reset to default
self.tk[key] = self._tk_defaults[key]
else:
self.tk[key] = value
|
[
"def",
"_set_tk_config",
"(",
"self",
",",
"keys",
",",
"value",
")",
":",
"# if a single key is passed, convert to list",
"if",
"isinstance",
"(",
"keys",
",",
"str",
")",
":",
"keys",
"=",
"[",
"keys",
"]",
"# loop through all the keys",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"in",
"self",
".",
"tk",
".",
"keys",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"# reset to default",
"self",
".",
"tk",
"[",
"key",
"]",
"=",
"self",
".",
"_tk_defaults",
"[",
"key",
"]",
"else",
":",
"self",
".",
"tk",
"[",
"key",
"]",
"=",
"value"
] |
Gets the config from the widget's tk object
:param string/List keys:
The tk config key or a list of tk keys.
:param variable value:
The value to set. If the value is `None`, the config value will be
reset to its default.
|
[
"Gets",
"the",
"config",
"from",
"the",
"widget",
"s",
"tk",
"object"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L77-L100
|
237,080
|
lawsie/guizero
|
guizero/base.py
|
Component.destroy
|
def destroy(self):
"""
Destroy the tk widget.
"""
# if this widget has a master remove the it from the master
if self.master is not None:
self.master._remove_child(self)
self.tk.destroy()
|
python
|
def destroy(self):
"""
Destroy the tk widget.
"""
# if this widget has a master remove the it from the master
if self.master is not None:
self.master._remove_child(self)
self.tk.destroy()
|
[
"def",
"destroy",
"(",
"self",
")",
":",
"# if this widget has a master remove the it from the master",
"if",
"self",
".",
"master",
"is",
"not",
"None",
":",
"self",
".",
"master",
".",
"_remove_child",
"(",
"self",
")",
"self",
".",
"tk",
".",
"destroy",
"(",
")"
] |
Destroy the tk widget.
|
[
"Destroy",
"the",
"tk",
"widget",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L169-L177
|
237,081
|
lawsie/guizero
|
guizero/base.py
|
Container.add_tk_widget
|
def add_tk_widget(self, tk_widget, grid=None, align=None, visible=True, enabled=None, width=None, height=None):
"""
Adds a tk widget into a guizero container.
:param tkinter.Widget tk_widget:
The Container (App, Box, etc) the tk widget will belong too.
:param List grid:
Grid co-ordinates for the widget, required if the master layout
is 'grid', defaults to `None`.
:param string align:
How to align the widget within the grid, defaults to None.
:param bool visible:
If the widget should be visible, defaults to `True`.
:param bool enabled:
If the widget should be enabled, defaults to `None`. If `None`
the value is inherited from the master.
:param int width:
The starting width of the widget. Defaults to `None` and will auto
size.
:param int height:
The starting height of the widget. Defaults to `None` and will auto
size.
"""
return Widget(self, tk_widget, "tk widget", grid, align, visible, enabled, width, height)
|
python
|
def add_tk_widget(self, tk_widget, grid=None, align=None, visible=True, enabled=None, width=None, height=None):
"""
Adds a tk widget into a guizero container.
:param tkinter.Widget tk_widget:
The Container (App, Box, etc) the tk widget will belong too.
:param List grid:
Grid co-ordinates for the widget, required if the master layout
is 'grid', defaults to `None`.
:param string align:
How to align the widget within the grid, defaults to None.
:param bool visible:
If the widget should be visible, defaults to `True`.
:param bool enabled:
If the widget should be enabled, defaults to `None`. If `None`
the value is inherited from the master.
:param int width:
The starting width of the widget. Defaults to `None` and will auto
size.
:param int height:
The starting height of the widget. Defaults to `None` and will auto
size.
"""
return Widget(self, tk_widget, "tk widget", grid, align, visible, enabled, width, height)
|
[
"def",
"add_tk_widget",
"(",
"self",
",",
"tk_widget",
",",
"grid",
"=",
"None",
",",
"align",
"=",
"None",
",",
"visible",
"=",
"True",
",",
"enabled",
"=",
"None",
",",
"width",
"=",
"None",
",",
"height",
"=",
"None",
")",
":",
"return",
"Widget",
"(",
"self",
",",
"tk_widget",
",",
"\"tk widget\"",
",",
"grid",
",",
"align",
",",
"visible",
",",
"enabled",
",",
"width",
",",
"height",
")"
] |
Adds a tk widget into a guizero container.
:param tkinter.Widget tk_widget:
The Container (App, Box, etc) the tk widget will belong too.
:param List grid:
Grid co-ordinates for the widget, required if the master layout
is 'grid', defaults to `None`.
:param string align:
How to align the widget within the grid, defaults to None.
:param bool visible:
If the widget should be visible, defaults to `True`.
:param bool enabled:
If the widget should be enabled, defaults to `None`. If `None`
the value is inherited from the master.
:param int width:
The starting width of the widget. Defaults to `None` and will auto
size.
:param int height:
The starting height of the widget. Defaults to `None` and will auto
size.
|
[
"Adds",
"a",
"tk",
"widget",
"into",
"a",
"guizero",
"container",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L289-L318
|
237,082
|
lawsie/guizero
|
guizero/base.py
|
Container.display_widgets
|
def display_widgets(self):
"""
Displays all the widgets associated with this Container.
Should be called when the widgets need to be "re-packed/gridded".
"""
# All widgets are removed and then recreated to ensure the order they
# were created is the order they are displayed.
for child in self.children:
if child.displayable:
# forget the widget
if self.layout != "grid":
child.tk.pack_forget()
else:
child.tk.grid_forget()
# display the widget
if child.visible:
if self.layout != "grid":
self._pack_widget(child)
else:
self._grid_widget(child)
|
python
|
def display_widgets(self):
"""
Displays all the widgets associated with this Container.
Should be called when the widgets need to be "re-packed/gridded".
"""
# All widgets are removed and then recreated to ensure the order they
# were created is the order they are displayed.
for child in self.children:
if child.displayable:
# forget the widget
if self.layout != "grid":
child.tk.pack_forget()
else:
child.tk.grid_forget()
# display the widget
if child.visible:
if self.layout != "grid":
self._pack_widget(child)
else:
self._grid_widget(child)
|
[
"def",
"display_widgets",
"(",
"self",
")",
":",
"# All widgets are removed and then recreated to ensure the order they",
"# were created is the order they are displayed.",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"child",
".",
"displayable",
":",
"# forget the widget",
"if",
"self",
".",
"layout",
"!=",
"\"grid\"",
":",
"child",
".",
"tk",
".",
"pack_forget",
"(",
")",
"else",
":",
"child",
".",
"tk",
".",
"grid_forget",
"(",
")",
"# display the widget",
"if",
"child",
".",
"visible",
":",
"if",
"self",
".",
"layout",
"!=",
"\"grid\"",
":",
"self",
".",
"_pack_widget",
"(",
"child",
")",
"else",
":",
"self",
".",
"_grid_widget",
"(",
"child",
")"
] |
Displays all the widgets associated with this Container.
Should be called when the widgets need to be "re-packed/gridded".
|
[
"Displays",
"all",
"the",
"widgets",
"associated",
"with",
"this",
"Container",
"."
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L334-L358
|
237,083
|
lawsie/guizero
|
guizero/base.py
|
Container.disable
|
def disable(self):
"""
Disable all the widgets in this container
"""
self._enabled = False
for child in self.children:
if isinstance(child, (Container, Widget)):
child.disable()
|
python
|
def disable(self):
"""
Disable all the widgets in this container
"""
self._enabled = False
for child in self.children:
if isinstance(child, (Container, Widget)):
child.disable()
|
[
"def",
"disable",
"(",
"self",
")",
":",
"self",
".",
"_enabled",
"=",
"False",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"(",
"Container",
",",
"Widget",
")",
")",
":",
"child",
".",
"disable",
"(",
")"
] |
Disable all the widgets in this container
|
[
"Disable",
"all",
"the",
"widgets",
"in",
"this",
"container"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L442-L449
|
237,084
|
lawsie/guizero
|
guizero/base.py
|
Container.enable
|
def enable(self):
"""
Enable all the widgets in this container
"""
self._enabled = True
for child in self.children:
if isinstance(child, (Container, Widget)):
child.enable()
|
python
|
def enable(self):
"""
Enable all the widgets in this container
"""
self._enabled = True
for child in self.children:
if isinstance(child, (Container, Widget)):
child.enable()
|
[
"def",
"enable",
"(",
"self",
")",
":",
"self",
".",
"_enabled",
"=",
"True",
"for",
"child",
"in",
"self",
".",
"children",
":",
"if",
"isinstance",
"(",
"child",
",",
"(",
"Container",
",",
"Widget",
")",
")",
":",
"child",
".",
"enable",
"(",
")"
] |
Enable all the widgets in this container
|
[
"Enable",
"all",
"the",
"widgets",
"in",
"this",
"container"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L451-L458
|
237,085
|
lawsie/guizero
|
guizero/base.py
|
BaseWindow.exit_full_screen
|
def exit_full_screen(self):
"""Change from full screen to windowed mode and remove key binding"""
self.tk.attributes("-fullscreen", False)
self._full_screen = False
self.events.remove_event("<FullScreen.Escape>")
|
python
|
def exit_full_screen(self):
"""Change from full screen to windowed mode and remove key binding"""
self.tk.attributes("-fullscreen", False)
self._full_screen = False
self.events.remove_event("<FullScreen.Escape>")
|
[
"def",
"exit_full_screen",
"(",
"self",
")",
":",
"self",
".",
"tk",
".",
"attributes",
"(",
"\"-fullscreen\"",
",",
"False",
")",
"self",
".",
"_full_screen",
"=",
"False",
"self",
".",
"events",
".",
"remove_event",
"(",
"\"<FullScreen.Escape>\"",
")"
] |
Change from full screen to windowed mode and remove key binding
|
[
"Change",
"from",
"full",
"screen",
"to",
"windowed",
"mode",
"and",
"remove",
"key",
"binding"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L585-L589
|
237,086
|
lawsie/guizero
|
guizero/base.py
|
ContainerWidget._set_propagation
|
def _set_propagation(self, width, height):
"""
Set the propagation value of the tk widget dependent on the width and height
:param int width:
The width of the widget.
:param int height:
The height of the widget.
"""
if width is None:
width = 0
if height is None:
height = 0
# set the propagate value
propagate_function = self.tk.pack_propagate
if self.layout == "grid":
propagate_function = self.tk.grid_propagate
propagate_value = True
# if height or width > 0 need to stop propagation
if isinstance(width, int):
if width > 0:
propagate_value = False
if isinstance(height, int):
if height > 0:
propagate_value = False
# if you specify a height or width you must specify they other
# (unless its a fill)
if isinstance(width, int) and isinstance(height, int):
if (width == 0 and height > 0) or (height == 0 and width > 0):
utils.error_format("You must specify a width and a height for {}".format(self.description))
propagate_function(propagate_value)
|
python
|
def _set_propagation(self, width, height):
"""
Set the propagation value of the tk widget dependent on the width and height
:param int width:
The width of the widget.
:param int height:
The height of the widget.
"""
if width is None:
width = 0
if height is None:
height = 0
# set the propagate value
propagate_function = self.tk.pack_propagate
if self.layout == "grid":
propagate_function = self.tk.grid_propagate
propagate_value = True
# if height or width > 0 need to stop propagation
if isinstance(width, int):
if width > 0:
propagate_value = False
if isinstance(height, int):
if height > 0:
propagate_value = False
# if you specify a height or width you must specify they other
# (unless its a fill)
if isinstance(width, int) and isinstance(height, int):
if (width == 0 and height > 0) or (height == 0 and width > 0):
utils.error_format("You must specify a width and a height for {}".format(self.description))
propagate_function(propagate_value)
|
[
"def",
"_set_propagation",
"(",
"self",
",",
"width",
",",
"height",
")",
":",
"if",
"width",
"is",
"None",
":",
"width",
"=",
"0",
"if",
"height",
"is",
"None",
":",
"height",
"=",
"0",
"# set the propagate value",
"propagate_function",
"=",
"self",
".",
"tk",
".",
"pack_propagate",
"if",
"self",
".",
"layout",
"==",
"\"grid\"",
":",
"propagate_function",
"=",
"self",
".",
"tk",
".",
"grid_propagate",
"propagate_value",
"=",
"True",
"# if height or width > 0 need to stop propagation",
"if",
"isinstance",
"(",
"width",
",",
"int",
")",
":",
"if",
"width",
">",
"0",
":",
"propagate_value",
"=",
"False",
"if",
"isinstance",
"(",
"height",
",",
"int",
")",
":",
"if",
"height",
">",
"0",
":",
"propagate_value",
"=",
"False",
"# if you specify a height or width you must specify they other",
"# (unless its a fill)",
"if",
"isinstance",
"(",
"width",
",",
"int",
")",
"and",
"isinstance",
"(",
"height",
",",
"int",
")",
":",
"if",
"(",
"width",
"==",
"0",
"and",
"height",
">",
"0",
")",
"or",
"(",
"height",
"==",
"0",
"and",
"width",
">",
"0",
")",
":",
"utils",
".",
"error_format",
"(",
"\"You must specify a width and a height for {}\"",
".",
"format",
"(",
"self",
".",
"description",
")",
")",
"propagate_function",
"(",
"propagate_value",
")"
] |
Set the propagation value of the tk widget dependent on the width and height
:param int width:
The width of the widget.
:param int height:
The height of the widget.
|
[
"Set",
"the",
"propagation",
"value",
"of",
"the",
"tk",
"widget",
"dependent",
"on",
"the",
"width",
"and",
"height"
] |
84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2
|
https://github.com/lawsie/guizero/blob/84c7f0b314fa86f9fc88eb11c9a0f6c4b57155e2/guizero/base.py#L661-L698
|
237,087
|
angr/pyvex
|
pyvex/lifting/util/instr_helper.py
|
Instruction.load
|
def load(self, addr, ty):
"""
Load a value from memory into a VEX temporary register.
:param addr: The VexValue containing the addr to load from.
:param ty: The Type of the resulting data
:return: a VexValue
"""
rdt = self.irsb_c.load(addr.rdt, ty)
return VexValue(self.irsb_c, rdt)
|
python
|
def load(self, addr, ty):
"""
Load a value from memory into a VEX temporary register.
:param addr: The VexValue containing the addr to load from.
:param ty: The Type of the resulting data
:return: a VexValue
"""
rdt = self.irsb_c.load(addr.rdt, ty)
return VexValue(self.irsb_c, rdt)
|
[
"def",
"load",
"(",
"self",
",",
"addr",
",",
"ty",
")",
":",
"rdt",
"=",
"self",
".",
"irsb_c",
".",
"load",
"(",
"addr",
".",
"rdt",
",",
"ty",
")",
"return",
"VexValue",
"(",
"self",
".",
"irsb_c",
",",
"rdt",
")"
] |
Load a value from memory into a VEX temporary register.
:param addr: The VexValue containing the addr to load from.
:param ty: The Type of the resulting data
:return: a VexValue
|
[
"Load",
"a",
"value",
"from",
"memory",
"into",
"a",
"VEX",
"temporary",
"register",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L207-L216
|
237,088
|
angr/pyvex
|
pyvex/lifting/util/instr_helper.py
|
Instruction.constant
|
def constant(self, val, ty):
"""
Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue
"""
if isinstance(val, VexValue) and not isinstance(val, IRExpr):
raise Exception('Constant cannot be made from VexValue or IRExpr')
rdt = self.irsb_c.mkconst(val, ty)
return VexValue(self.irsb_c, rdt)
|
python
|
def constant(self, val, ty):
"""
Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue
"""
if isinstance(val, VexValue) and not isinstance(val, IRExpr):
raise Exception('Constant cannot be made from VexValue or IRExpr')
rdt = self.irsb_c.mkconst(val, ty)
return VexValue(self.irsb_c, rdt)
|
[
"def",
"constant",
"(",
"self",
",",
"val",
",",
"ty",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"VexValue",
")",
"and",
"not",
"isinstance",
"(",
"val",
",",
"IRExpr",
")",
":",
"raise",
"Exception",
"(",
"'Constant cannot be made from VexValue or IRExpr'",
")",
"rdt",
"=",
"self",
".",
"irsb_c",
".",
"mkconst",
"(",
"val",
",",
"ty",
")",
"return",
"VexValue",
"(",
"self",
".",
"irsb_c",
",",
"rdt",
")"
] |
Creates a constant as a VexValue
:param val: The value, as an integer
:param ty: The type of the resulting VexValue
:return: a VexValue
|
[
"Creates",
"a",
"constant",
"as",
"a",
"VexValue"
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L218-L229
|
237,089
|
angr/pyvex
|
pyvex/lifting/util/instr_helper.py
|
Instruction.put
|
def put(self, val, reg):
"""
Puts a value from a VEX temporary register into a machine register.
This is how the results of operations done to registers get committed to the machine's state.
:param val: The VexValue to store (Want to store a constant? See Constant() first)
:param reg: The integer register number to store into, or register name
:return: None
"""
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
self.irsb_c.put(val.rdt, offset)
|
python
|
def put(self, val, reg):
"""
Puts a value from a VEX temporary register into a machine register.
This is how the results of operations done to registers get committed to the machine's state.
:param val: The VexValue to store (Want to store a constant? See Constant() first)
:param reg: The integer register number to store into, or register name
:return: None
"""
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
self.irsb_c.put(val.rdt, offset)
|
[
"def",
"put",
"(",
"self",
",",
"val",
",",
"reg",
")",
":",
"offset",
"=",
"self",
".",
"lookup_register",
"(",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"arch",
",",
"reg",
")",
"self",
".",
"irsb_c",
".",
"put",
"(",
"val",
".",
"rdt",
",",
"offset",
")"
] |
Puts a value from a VEX temporary register into a machine register.
This is how the results of operations done to registers get committed to the machine's state.
:param val: The VexValue to store (Want to store a constant? See Constant() first)
:param reg: The integer register number to store into, or register name
:return: None
|
[
"Puts",
"a",
"value",
"from",
"a",
"VEX",
"temporary",
"register",
"into",
"a",
"machine",
"register",
".",
"This",
"is",
"how",
"the",
"results",
"of",
"operations",
"done",
"to",
"registers",
"get",
"committed",
"to",
"the",
"machine",
"s",
"state",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L255-L265
|
237,090
|
angr/pyvex
|
pyvex/lifting/util/instr_helper.py
|
Instruction.put_conditional
|
def put_conditional(self, cond, valiftrue, valiffalse, reg):
"""
Like put, except it checks a condition
to decide what to put in the destination register.
:param cond: The VexValue representing the logical expression for the condition
(if your expression only has constants, don't use this method!)
:param valiftrue: the VexValue to put in reg if cond evals as true
:param validfalse: the VexValue to put in reg if cond evals as false
:param reg: The integer register number to store into, or register name
:return: None
"""
val = self.irsb_c.ite(cond.rdt , valiftrue.rdt, valiffalse.rdt)
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
self.irsb_c.put(val, offset)
|
python
|
def put_conditional(self, cond, valiftrue, valiffalse, reg):
"""
Like put, except it checks a condition
to decide what to put in the destination register.
:param cond: The VexValue representing the logical expression for the condition
(if your expression only has constants, don't use this method!)
:param valiftrue: the VexValue to put in reg if cond evals as true
:param validfalse: the VexValue to put in reg if cond evals as false
:param reg: The integer register number to store into, or register name
:return: None
"""
val = self.irsb_c.ite(cond.rdt , valiftrue.rdt, valiffalse.rdt)
offset = self.lookup_register(self.irsb_c.irsb.arch, reg)
self.irsb_c.put(val, offset)
|
[
"def",
"put_conditional",
"(",
"self",
",",
"cond",
",",
"valiftrue",
",",
"valiffalse",
",",
"reg",
")",
":",
"val",
"=",
"self",
".",
"irsb_c",
".",
"ite",
"(",
"cond",
".",
"rdt",
",",
"valiftrue",
".",
"rdt",
",",
"valiffalse",
".",
"rdt",
")",
"offset",
"=",
"self",
".",
"lookup_register",
"(",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"arch",
",",
"reg",
")",
"self",
".",
"irsb_c",
".",
"put",
"(",
"val",
",",
"offset",
")"
] |
Like put, except it checks a condition
to decide what to put in the destination register.
:param cond: The VexValue representing the logical expression for the condition
(if your expression only has constants, don't use this method!)
:param valiftrue: the VexValue to put in reg if cond evals as true
:param validfalse: the VexValue to put in reg if cond evals as false
:param reg: The integer register number to store into, or register name
:return: None
|
[
"Like",
"put",
"except",
"it",
"checks",
"a",
"condition",
"to",
"decide",
"what",
"to",
"put",
"in",
"the",
"destination",
"register",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L268-L283
|
237,091
|
angr/pyvex
|
pyvex/lifting/util/instr_helper.py
|
Instruction.store
|
def store(self, val, addr):
"""
Store a VexValue in memory at the specified loaction.
:param val: The VexValue of the value to store
:param addr: The VexValue of the address to store into
:return: None
"""
self.irsb_c.store(addr.rdt, val.rdt)
|
python
|
def store(self, val, addr):
"""
Store a VexValue in memory at the specified loaction.
:param val: The VexValue of the value to store
:param addr: The VexValue of the address to store into
:return: None
"""
self.irsb_c.store(addr.rdt, val.rdt)
|
[
"def",
"store",
"(",
"self",
",",
"val",
",",
"addr",
")",
":",
"self",
".",
"irsb_c",
".",
"store",
"(",
"addr",
".",
"rdt",
",",
"val",
".",
"rdt",
")"
] |
Store a VexValue in memory at the specified loaction.
:param val: The VexValue of the value to store
:param addr: The VexValue of the address to store into
:return: None
|
[
"Store",
"a",
"VexValue",
"in",
"memory",
"at",
"the",
"specified",
"loaction",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L285-L293
|
237,092
|
angr/pyvex
|
pyvex/lifting/util/instr_helper.py
|
Instruction.jump
|
def jump(self, condition, to_addr, jumpkind=JumpKind.Boring, ip_offset=None):
"""
Jump to a specified destination, under the specified condition.
Used for branches, jumps, calls, returns, etc.
:param condition: The VexValue representing the expression for the guard, or None for an unconditional jump
:param to_addr: The address to jump to.
:param jumpkind: The JumpKind to use. See the VEX docs for what these are; you only need them for things
aren't normal jumps (e.g., calls, interrupts, program exits, etc etc)
:return: None
"""
to_addr_ty = None
if isinstance(to_addr, VexValue):
# Unpack a VV
to_addr_rdt = to_addr.rdt
to_addr_ty = to_addr.ty
elif isinstance(to_addr, int):
# Direct jump to an int, make an RdT and Ty
to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type
to_addr = self.constant(to_addr, to_addr_ty) # TODO archinfo may be changing
to_addr_rdt = to_addr.rdt
elif isinstance(to_addr, RdTmp):
# An RdT; just get the Ty of the arch's pointer type
to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type
to_addr_rdt = to_addr
else:
raise ValueError("Jump destination has unknown type: " + repr(type(to_addr)))
if not condition:
# This is the default exit.
self.irsb_c.irsb.jumpkind = jumpkind
self.irsb_c.irsb.next = to_addr_rdt
else:
# add another exit
# EDG says: We should make sure folks set ArchXYZ.ip_offset like they're supposed to
if ip_offset is None:
ip_offset = self.arch.ip_offset
assert ip_offset is not None
negated_condition_rdt = self.ite(condition, self.constant(0, condition.ty), self.constant(1, condition.ty))
direct_exit_target = self.constant(self.addr + (self.bitwidth // 8), to_addr_ty)
self.irsb_c.add_exit(negated_condition_rdt, direct_exit_target.rdt, jumpkind, ip_offset)
self.irsb_c.irsb.jumpkind = jumpkind
self.irsb_c.irsb.next = to_addr_rdt
|
python
|
def jump(self, condition, to_addr, jumpkind=JumpKind.Boring, ip_offset=None):
"""
Jump to a specified destination, under the specified condition.
Used for branches, jumps, calls, returns, etc.
:param condition: The VexValue representing the expression for the guard, or None for an unconditional jump
:param to_addr: The address to jump to.
:param jumpkind: The JumpKind to use. See the VEX docs for what these are; you only need them for things
aren't normal jumps (e.g., calls, interrupts, program exits, etc etc)
:return: None
"""
to_addr_ty = None
if isinstance(to_addr, VexValue):
# Unpack a VV
to_addr_rdt = to_addr.rdt
to_addr_ty = to_addr.ty
elif isinstance(to_addr, int):
# Direct jump to an int, make an RdT and Ty
to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type
to_addr = self.constant(to_addr, to_addr_ty) # TODO archinfo may be changing
to_addr_rdt = to_addr.rdt
elif isinstance(to_addr, RdTmp):
# An RdT; just get the Ty of the arch's pointer type
to_addr_ty = vex_int_class(self.irsb_c.irsb.arch.bits).type
to_addr_rdt = to_addr
else:
raise ValueError("Jump destination has unknown type: " + repr(type(to_addr)))
if not condition:
# This is the default exit.
self.irsb_c.irsb.jumpkind = jumpkind
self.irsb_c.irsb.next = to_addr_rdt
else:
# add another exit
# EDG says: We should make sure folks set ArchXYZ.ip_offset like they're supposed to
if ip_offset is None:
ip_offset = self.arch.ip_offset
assert ip_offset is not None
negated_condition_rdt = self.ite(condition, self.constant(0, condition.ty), self.constant(1, condition.ty))
direct_exit_target = self.constant(self.addr + (self.bitwidth // 8), to_addr_ty)
self.irsb_c.add_exit(negated_condition_rdt, direct_exit_target.rdt, jumpkind, ip_offset)
self.irsb_c.irsb.jumpkind = jumpkind
self.irsb_c.irsb.next = to_addr_rdt
|
[
"def",
"jump",
"(",
"self",
",",
"condition",
",",
"to_addr",
",",
"jumpkind",
"=",
"JumpKind",
".",
"Boring",
",",
"ip_offset",
"=",
"None",
")",
":",
"to_addr_ty",
"=",
"None",
"if",
"isinstance",
"(",
"to_addr",
",",
"VexValue",
")",
":",
"# Unpack a VV",
"to_addr_rdt",
"=",
"to_addr",
".",
"rdt",
"to_addr_ty",
"=",
"to_addr",
".",
"ty",
"elif",
"isinstance",
"(",
"to_addr",
",",
"int",
")",
":",
"# Direct jump to an int, make an RdT and Ty",
"to_addr_ty",
"=",
"vex_int_class",
"(",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"arch",
".",
"bits",
")",
".",
"type",
"to_addr",
"=",
"self",
".",
"constant",
"(",
"to_addr",
",",
"to_addr_ty",
")",
"# TODO archinfo may be changing",
"to_addr_rdt",
"=",
"to_addr",
".",
"rdt",
"elif",
"isinstance",
"(",
"to_addr",
",",
"RdTmp",
")",
":",
"# An RdT; just get the Ty of the arch's pointer type",
"to_addr_ty",
"=",
"vex_int_class",
"(",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"arch",
".",
"bits",
")",
".",
"type",
"to_addr_rdt",
"=",
"to_addr",
"else",
":",
"raise",
"ValueError",
"(",
"\"Jump destination has unknown type: \"",
"+",
"repr",
"(",
"type",
"(",
"to_addr",
")",
")",
")",
"if",
"not",
"condition",
":",
"# This is the default exit.",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"jumpkind",
"=",
"jumpkind",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"next",
"=",
"to_addr_rdt",
"else",
":",
"# add another exit",
"# EDG says: We should make sure folks set ArchXYZ.ip_offset like they're supposed to",
"if",
"ip_offset",
"is",
"None",
":",
"ip_offset",
"=",
"self",
".",
"arch",
".",
"ip_offset",
"assert",
"ip_offset",
"is",
"not",
"None",
"negated_condition_rdt",
"=",
"self",
".",
"ite",
"(",
"condition",
",",
"self",
".",
"constant",
"(",
"0",
",",
"condition",
".",
"ty",
")",
",",
"self",
".",
"constant",
"(",
"1",
",",
"condition",
".",
"ty",
")",
")",
"direct_exit_target",
"=",
"self",
".",
"constant",
"(",
"self",
".",
"addr",
"+",
"(",
"self",
".",
"bitwidth",
"//",
"8",
")",
",",
"to_addr_ty",
")",
"self",
".",
"irsb_c",
".",
"add_exit",
"(",
"negated_condition_rdt",
",",
"direct_exit_target",
".",
"rdt",
",",
"jumpkind",
",",
"ip_offset",
")",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"jumpkind",
"=",
"jumpkind",
"self",
".",
"irsb_c",
".",
"irsb",
".",
"next",
"=",
"to_addr_rdt"
] |
Jump to a specified destination, under the specified condition.
Used for branches, jumps, calls, returns, etc.
:param condition: The VexValue representing the expression for the guard, or None for an unconditional jump
:param to_addr: The address to jump to.
:param jumpkind: The JumpKind to use. See the VEX docs for what these are; you only need them for things
aren't normal jumps (e.g., calls, interrupts, program exits, etc etc)
:return: None
|
[
"Jump",
"to",
"a",
"specified",
"destination",
"under",
"the",
"specified",
"condition",
".",
"Used",
"for",
"branches",
"jumps",
"calls",
"returns",
"etc",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/util/instr_helper.py#L295-L337
|
237,093
|
angr/pyvex
|
pyvex/lifting/__init__.py
|
register
|
def register(lifter, arch_name):
"""
Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocessor`
"""
if issubclass(lifter, Lifter):
l.debug("Registering lifter %s for architecture %s.", lifter.__name__, arch_name)
lifters[arch_name].append(lifter)
if issubclass(lifter, Postprocessor):
l.debug("Registering postprocessor %s for architecture %s.", lifter.__name__, arch_name)
postprocessors[arch_name].append(lifter)
|
python
|
def register(lifter, arch_name):
"""
Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocessor`
"""
if issubclass(lifter, Lifter):
l.debug("Registering lifter %s for architecture %s.", lifter.__name__, arch_name)
lifters[arch_name].append(lifter)
if issubclass(lifter, Postprocessor):
l.debug("Registering postprocessor %s for architecture %s.", lifter.__name__, arch_name)
postprocessors[arch_name].append(lifter)
|
[
"def",
"register",
"(",
"lifter",
",",
"arch_name",
")",
":",
"if",
"issubclass",
"(",
"lifter",
",",
"Lifter",
")",
":",
"l",
".",
"debug",
"(",
"\"Registering lifter %s for architecture %s.\"",
",",
"lifter",
".",
"__name__",
",",
"arch_name",
")",
"lifters",
"[",
"arch_name",
"]",
".",
"append",
"(",
"lifter",
")",
"if",
"issubclass",
"(",
"lifter",
",",
"Postprocessor",
")",
":",
"l",
".",
"debug",
"(",
"\"Registering postprocessor %s for architecture %s.\"",
",",
"lifter",
".",
"__name__",
",",
"arch_name",
")",
"postprocessors",
"[",
"arch_name",
"]",
".",
"append",
"(",
"lifter",
")"
] |
Registers a Lifter or Postprocessor to be used by pyvex. Lifters are are given priority based on the order
in which they are registered. Postprocessors will be run in registration order.
:param lifter: The Lifter or Postprocessor to register
:vartype lifter: :class:`Lifter` or :class:`Postprocessor`
|
[
"Registers",
"a",
"Lifter",
"or",
"Postprocessor",
"to",
"be",
"used",
"by",
"pyvex",
".",
"Lifters",
"are",
"are",
"given",
"priority",
"based",
"on",
"the",
"order",
"in",
"which",
"they",
"are",
"registered",
".",
"Postprocessors",
"will",
"be",
"run",
"in",
"registration",
"order",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/lifting/__init__.py#L216-L229
|
237,094
|
angr/pyvex
|
pyvex/expr.py
|
IRExpr.child_expressions
|
def child_expressions(self):
"""
A list of all of the expressions that this expression ends up evaluating.
"""
expressions = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
expressions.append(v)
expressions.extend(v.child_expressions)
return expressions
|
python
|
def child_expressions(self):
"""
A list of all of the expressions that this expression ends up evaluating.
"""
expressions = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
expressions.append(v)
expressions.extend(v.child_expressions)
return expressions
|
[
"def",
"child_expressions",
"(",
"self",
")",
":",
"expressions",
"=",
"[",
"]",
"for",
"k",
"in",
"self",
".",
"__slots__",
":",
"v",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"if",
"isinstance",
"(",
"v",
",",
"IRExpr",
")",
":",
"expressions",
".",
"append",
"(",
"v",
")",
"expressions",
".",
"extend",
"(",
"v",
".",
"child_expressions",
")",
"return",
"expressions"
] |
A list of all of the expressions that this expression ends up evaluating.
|
[
"A",
"list",
"of",
"all",
"of",
"the",
"expressions",
"that",
"this",
"expression",
"ends",
"up",
"evaluating",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/expr.py#L26-L36
|
237,095
|
angr/pyvex
|
pyvex/expr.py
|
IRExpr.constants
|
def constants(self):
"""
A list of all of the constants that this expression ends up using.
"""
constants = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
constants.extend(v.constants)
elif isinstance(v, IRConst):
constants.append(v)
return constants
|
python
|
def constants(self):
"""
A list of all of the constants that this expression ends up using.
"""
constants = [ ]
for k in self.__slots__:
v = getattr(self, k)
if isinstance(v, IRExpr):
constants.extend(v.constants)
elif isinstance(v, IRConst):
constants.append(v)
return constants
|
[
"def",
"constants",
"(",
"self",
")",
":",
"constants",
"=",
"[",
"]",
"for",
"k",
"in",
"self",
".",
"__slots__",
":",
"v",
"=",
"getattr",
"(",
"self",
",",
"k",
")",
"if",
"isinstance",
"(",
"v",
",",
"IRExpr",
")",
":",
"constants",
".",
"extend",
"(",
"v",
".",
"constants",
")",
"elif",
"isinstance",
"(",
"v",
",",
"IRConst",
")",
":",
"constants",
".",
"append",
"(",
"v",
")",
"return",
"constants"
] |
A list of all of the constants that this expression ends up using.
|
[
"A",
"list",
"of",
"all",
"of",
"the",
"constants",
"that",
"this",
"expression",
"ends",
"up",
"using",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/expr.py#L39-L50
|
237,096
|
angr/pyvex
|
pyvex/block.py
|
IRSB.expressions
|
def expressions(self):
"""
Return an iterator of all expressions contained in the IRSB.
"""
for s in self.statements:
for expr_ in s.expressions:
yield expr_
yield self.next
|
python
|
def expressions(self):
"""
Return an iterator of all expressions contained in the IRSB.
"""
for s in self.statements:
for expr_ in s.expressions:
yield expr_
yield self.next
|
[
"def",
"expressions",
"(",
"self",
")",
":",
"for",
"s",
"in",
"self",
".",
"statements",
":",
"for",
"expr_",
"in",
"s",
".",
"expressions",
":",
"yield",
"expr_",
"yield",
"self",
".",
"next"
] |
Return an iterator of all expressions contained in the IRSB.
|
[
"Return",
"an",
"iterator",
"of",
"all",
"expressions",
"contained",
"in",
"the",
"IRSB",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L338-L345
|
237,097
|
angr/pyvex
|
pyvex/block.py
|
IRSB.instructions
|
def instructions(self):
"""
The number of instructions in this block
"""
if self._instructions is None:
if self.statements is None:
self._instructions = 0
else:
self._instructions = len([s for s in self.statements if type(s) is stmt.IMark])
return self._instructions
|
python
|
def instructions(self):
"""
The number of instructions in this block
"""
if self._instructions is None:
if self.statements is None:
self._instructions = 0
else:
self._instructions = len([s for s in self.statements if type(s) is stmt.IMark])
return self._instructions
|
[
"def",
"instructions",
"(",
"self",
")",
":",
"if",
"self",
".",
"_instructions",
"is",
"None",
":",
"if",
"self",
".",
"statements",
"is",
"None",
":",
"self",
".",
"_instructions",
"=",
"0",
"else",
":",
"self",
".",
"_instructions",
"=",
"len",
"(",
"[",
"s",
"for",
"s",
"in",
"self",
".",
"statements",
"if",
"type",
"(",
"s",
")",
"is",
"stmt",
".",
"IMark",
"]",
")",
"return",
"self",
".",
"_instructions"
] |
The number of instructions in this block
|
[
"The",
"number",
"of",
"instructions",
"in",
"this",
"block"
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L348-L357
|
237,098
|
angr/pyvex
|
pyvex/block.py
|
IRSB.instruction_addresses
|
def instruction_addresses(self):
"""
Addresses of instructions in this block.
"""
if self._instruction_addresses is None:
if self.statements is None:
self._instruction_addresses = [ ]
else:
self._instruction_addresses = [ (s.addr + s.delta) for s in self.statements if type(s) is stmt.IMark ]
return self._instruction_addresses
|
python
|
def instruction_addresses(self):
"""
Addresses of instructions in this block.
"""
if self._instruction_addresses is None:
if self.statements is None:
self._instruction_addresses = [ ]
else:
self._instruction_addresses = [ (s.addr + s.delta) for s in self.statements if type(s) is stmt.IMark ]
return self._instruction_addresses
|
[
"def",
"instruction_addresses",
"(",
"self",
")",
":",
"if",
"self",
".",
"_instruction_addresses",
"is",
"None",
":",
"if",
"self",
".",
"statements",
"is",
"None",
":",
"self",
".",
"_instruction_addresses",
"=",
"[",
"]",
"else",
":",
"self",
".",
"_instruction_addresses",
"=",
"[",
"(",
"s",
".",
"addr",
"+",
"s",
".",
"delta",
")",
"for",
"s",
"in",
"self",
".",
"statements",
"if",
"type",
"(",
"s",
")",
"is",
"stmt",
".",
"IMark",
"]",
"return",
"self",
".",
"_instruction_addresses"
] |
Addresses of instructions in this block.
|
[
"Addresses",
"of",
"instructions",
"in",
"this",
"block",
"."
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L360-L369
|
237,099
|
angr/pyvex
|
pyvex/block.py
|
IRSB.size
|
def size(self):
"""
The size of this block, in bytes
"""
if self._size is None:
self._size = sum(s.len for s in self.statements if type(s) is stmt.IMark)
return self._size
|
python
|
def size(self):
"""
The size of this block, in bytes
"""
if self._size is None:
self._size = sum(s.len for s in self.statements if type(s) is stmt.IMark)
return self._size
|
[
"def",
"size",
"(",
"self",
")",
":",
"if",
"self",
".",
"_size",
"is",
"None",
":",
"self",
".",
"_size",
"=",
"sum",
"(",
"s",
".",
"len",
"for",
"s",
"in",
"self",
".",
"statements",
"if",
"type",
"(",
"s",
")",
"is",
"stmt",
".",
"IMark",
")",
"return",
"self",
".",
"_size"
] |
The size of this block, in bytes
|
[
"The",
"size",
"of",
"this",
"block",
"in",
"bytes"
] |
c418edc1146982b2a0579bf56e5993c1c7046b19
|
https://github.com/angr/pyvex/blob/c418edc1146982b2a0579bf56e5993c1c7046b19/pyvex/block.py#L372-L378
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.