INSTRUCTION
stringlengths 1
46.3k
| RESPONSE
stringlengths 75
80.2k
|
---|---|
:type data: dict[str, dict[str, str] | str]
:rtype: satosa.internal_data.InternalResponse
:param data: A dict representation of an InternalResponse object
:return: An InternalResponse object | def from_dict(cls, data):
"""
:type data: dict[str, dict[str, str] | str]
:rtype: satosa.internal_data.InternalResponse
:param data: A dict representation of an InternalResponse object
:return: An InternalResponse object
"""
auth_info = _AuthenticationInformation.from_dict(data.get("auth_info"))
instance = cls(auth_info=auth_info)
instance.user_id_hash_type = data.get("hash_type")
instance.attributes = data.get("attributes", {})
instance.user_id = data.get("user_id")
instance.requester = data.get("requester")
return instance |
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 | 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 |
Hashes a value together with a salt.
:type salt: str
:type value: str
:param salt: hash salt
:param value: value to hash together with the salt
:return: hash value (SHA512) | def hash_data(salt, value):
"""
Hashes a value together with a salt.
:type salt: str
:type value: str
:param salt: hash salt
:param value: value to hash together with the salt
:return: hash value (SHA512)
"""
msg = "UserIdHasher is deprecated; use satosa.util.hash_data instead."
_warnings.warn(msg, DeprecationWarning)
return util.hash_data(salt, value) |
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 | 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) |
Unpacks a post request query string.
:param environ: whiskey application environment.
:return: A dictionary with parameters. | def unpack_post(environ, content_length):
"""
Unpacks a post request query string.
:param environ: whiskey application environment.
:return: A dictionary with parameters.
"""
post_body = environ['wsgi.input'].read(content_length).decode("utf-8")
data = None
if "application/x-www-form-urlencoded" in environ["CONTENT_TYPE"]:
data = dict(parse_qsl(post_body))
elif "application/json" in environ["CONTENT_TYPE"]:
data = json.loads(post_body)
logger.debug("unpack_post:: %s", data)
return data |
Unpacks a get or post request query string.
:param environ: whiskey application environment.
:return: A dictionary with parameters. | def unpack_request(environ, content_length=0):
"""
Unpacks a get or post request query string.
:param environ: whiskey application environment.
:return: A dictionary with parameters.
"""
data = None
if environ["REQUEST_METHOD"] == "GET":
data = unpack_get(environ)
elif environ["REQUEST_METHOD"] == "POST":
data = unpack_post(environ, content_length)
logger.debug("read request data: %s", data)
return data |
Inserts a path to the context.
This path is striped by the base_url, so for example:
A path BASE_URL/ENDPOINT_URL, would be inserted as only ENDPOINT_URL
https://localhost:8092/sso/redirect -> sso/redirect
:type p: str
:param p: A path to an endpoint.
:return: None | def path(self, p):
"""
Inserts a path to the context.
This path is striped by the base_url, so for example:
A path BASE_URL/ENDPOINT_URL, would be inserted as only ENDPOINT_URL
https://localhost:8092/sso/redirect -> sso/redirect
:type p: str
:param p: A path to an endpoint.
:return: None
"""
if not p:
raise ValueError("path can't be set to None")
elif p.startswith('/'):
raise ValueError("path can't start with '/'")
self._path = p |
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 | 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 |
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 | 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 |
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 | 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 |
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 | 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 |
Loads request micro services (handling incoming requests).
:type plugin_path: list[str]
:type plugins: list[str]
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:type base_url: str
:rtype satosa.micro_service.service_base.RequestMicroService
:param plugin_path: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param: base_url: base url of the SATOSA server
:return: Request micro service | def load_request_microservices(plugin_path, plugins, internal_attributes, base_url):
"""
Loads request micro services (handling incoming requests).
:type plugin_path: list[str]
:type plugins: list[str]
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:type base_url: str
:rtype satosa.micro_service.service_base.RequestMicroService
:param plugin_path: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param: base_url: base url of the SATOSA server
:return: Request micro service
"""
request_services = _load_microservices(plugin_path, plugins, _request_micro_service_filter, internal_attributes,
base_url)
logger.info("Loaded request micro services: %s" % [type(k).__name__ for k in request_services])
return request_services |
Loads response micro services (handling outgoing responses).
:type plugin_path: list[str]
:type plugins: list[str]
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:type base_url: str
:rtype satosa.micro_service.service_base.ResponseMicroService
:param plugin_path: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param: base_url: base url of the SATOSA server
:return: Response micro service | def load_response_microservices(plugin_path, plugins, internal_attributes, base_url):
"""
Loads response micro services (handling outgoing responses).
:type plugin_path: list[str]
:type plugins: list[str]
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:type base_url: str
:rtype satosa.micro_service.service_base.ResponseMicroService
:param plugin_path: Path to the plugin directory
:param plugins: A list with the name of the plugin files
:param: base_url: base url of the SATOSA server
:return: Response micro service
"""
response_services = _load_microservices(plugin_path, plugins, _response_micro_service_filter, internal_attributes,
base_url)
logger.info("Loaded response micro services: %s" % [type(k).__name__ for k in response_services])
return response_services |
Generates SAML metadata for the given PROXY_CONF, signed with the given KEY and associated CERT. | 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) |
See super class satosa.frontends.base.FrontendModule
:type backend_names: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
:raise ValueError: if more than one backend is configured | def register_endpoints(self, backend_names):
"""
See super class satosa.frontends.base.FrontendModule
:type backend_names: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
:raise ValueError: if more than one backend is configured
"""
url_map = [("^{}".format(self.name), self.ping_endpoint)]
return url_map |
Create a pyoidc client instance.
:param provider_metadata: provider configuration information
:type provider_metadata: Mapping[str, Union[str, Sequence[str]]]
:param client_metadata: client metadata
:type client_metadata: Mapping[str, Union[str, Sequence[str]]]
:return: client instance to use for communicating with the configured provider
:rtype: oic.oic.Client | def _create_client(provider_metadata, client_metadata, verify_ssl=True):
"""
Create a pyoidc client instance.
:param provider_metadata: provider configuration information
:type provider_metadata: Mapping[str, Union[str, Sequence[str]]]
:param client_metadata: client metadata
:type client_metadata: Mapping[str, Union[str, Sequence[str]]]
:return: client instance to use for communicating with the configured provider
:rtype: oic.oic.Client
"""
client = oic.Client(
client_authn_method=CLIENT_AUTHN_METHOD, verify_ssl=verify_ssl
)
# Provider configuration information
if "authorization_endpoint" in provider_metadata:
# no dynamic discovery necessary
client.handle_provider_config(ProviderConfigurationResponse(**provider_metadata),
provider_metadata["issuer"])
else:
# do dynamic discovery
client.provider_config(provider_metadata["issuer"])
# Client information
if "client_id" in client_metadata:
# static client info provided
client.store_registration_info(RegistrationRequest(**client_metadata))
else:
# do dynamic registration
client.register(client.provider_info['registration_endpoint'],
**client_metadata)
client.subject_type = (client.registration_response.get("subject_type") or
client.provider_info["subject_types_supported"][0])
return client |
See super class method satosa.backends.base#start_auth
:type context: satosa.context.Context
:type request_info: satosa.internal.InternalData | def start_auth(self, context, request_info):
"""
See super class method satosa.backends.base#start_auth
:type context: satosa.context.Context
:type request_info: satosa.internal.InternalData
"""
oidc_nonce = rndstr()
oidc_state = rndstr()
state_data = {
NONCE_KEY: oidc_nonce,
STATE_KEY: oidc_state
}
context.state[self.name] = state_data
args = {
"scope": self.config["client"]["auth_req_params"]["scope"],
"response_type": self.config["client"]["auth_req_params"]["response_type"],
"client_id": self.client.client_id,
"redirect_uri": self.client.registration_response["redirect_uris"][0],
"state": oidc_state,
"nonce": oidc_nonce
}
args.update(self.config["client"]["auth_req_params"])
auth_req = self.client.construct_AuthorizationRequest(request_args=args)
login_url = auth_req.request(self.client.authorization_endpoint)
return Redirect(login_url) |
Creates a list of all the endpoints this backend module needs to listen to. In this case
it's the authentication response from the underlying OP that is redirected from the OP to
the proxy.
:rtype: Sequence[(str, Callable[[satosa.context.Context], satosa.response.Response]]
:return: A list that can be used to map the request to SATOSA to this endpoint. | def register_endpoints(self):
"""
Creates a list of all the endpoints this backend module needs to listen to. In this case
it's the authentication response from the underlying OP that is redirected from the OP to
the proxy.
:rtype: Sequence[(str, Callable[[satosa.context.Context], satosa.response.Response]]
:return: A list that can be used to map the request to SATOSA to this endpoint.
"""
url_map = []
redirect_path = urlparse(self.config["client"]["client_metadata"]["redirect_uris"][0]).path
if not redirect_path:
raise SATOSAError("Missing path in redirect uri")
url_map.append(("^%s$" % redirect_path.lstrip("/"), self.response_endpoint))
return url_map |
Verify the received OIDC 'nonce' from the ID Token.
:param nonce: OIDC nonce
:type nonce: str
:param context: current request context
:type context: satosa.context.Context
:raise SATOSAAuthenticationError: if the nonce is incorrect | def _verify_nonce(self, nonce, context):
"""
Verify the received OIDC 'nonce' from the ID Token.
:param nonce: OIDC nonce
:type nonce: str
:param context: current request context
:type context: satosa.context.Context
:raise SATOSAAuthenticationError: if the nonce is incorrect
"""
backend_state = context.state[self.name]
if nonce != backend_state[NONCE_KEY]:
satosa_logging(logger, logging.DEBUG,
"Missing or invalid nonce in authn response for state: %s" %
backend_state,
context.state)
raise SATOSAAuthenticationError(context.state, "Missing or invalid nonce in authn response") |
:param authn_response: authentication response from OP
:type authn_response: oic.oic.message.AuthorizationResponse
:return: access token and ID Token claims
:rtype: Tuple[Optional[str], Optional[Mapping[str, str]]] | def _get_tokens(self, authn_response, context):
"""
:param authn_response: authentication response from OP
:type authn_response: oic.oic.message.AuthorizationResponse
:return: access token and ID Token claims
:rtype: Tuple[Optional[str], Optional[Mapping[str, str]]]
"""
if "code" in authn_response:
# make token request
args = {
"code": authn_response["code"],
"redirect_uri": self.client.registration_response['redirect_uris'][0],
}
token_resp = self.client.do_access_token_request(scope="openid", state=authn_response["state"],
request_args=args,
authn_method=self.client.registration_response[
"token_endpoint_auth_method"])
self._check_error_response(token_resp, context)
return token_resp["access_token"], token_resp["id_token"]
return authn_response.get("access_token"), authn_response.get("id_token") |
Check if the response is an OAuth error response.
:param response: the OIDC response
:type response: oic.oic.message
:raise SATOSAAuthenticationError: if the response is an OAuth error response | def _check_error_response(self, response, context):
"""
Check if the response is an OAuth error response.
:param response: the OIDC response
:type response: oic.oic.message
:raise SATOSAAuthenticationError: if the response is an OAuth error response
"""
if "error" in response:
satosa_logging(logger, logging.DEBUG, "%s error: %s %s" %
(type(response).__name__, response["error"], response.get("error_description", "")),
context.state)
raise SATOSAAuthenticationError(context.state, "Access denied") |
Handles the authentication response from the OP.
:type context: satosa.context.Context
:type args: Any
:rtype: satosa.response.Response
:param context: SATOSA context
:param args: None
:return: | def response_endpoint(self, context, *args):
"""
Handles the authentication response from the OP.
:type context: satosa.context.Context
:type args: Any
:rtype: satosa.response.Response
:param context: SATOSA context
:param args: None
:return:
"""
backend_state = context.state[self.name]
authn_resp = self.client.parse_response(AuthorizationResponse, info=context.request, sformat="dict")
if backend_state[STATE_KEY] != authn_resp["state"]:
satosa_logging(logger, logging.DEBUG,
"Missing or invalid state in authn response for state: %s" %
backend_state,
context.state)
raise SATOSAAuthenticationError(context.state, "Missing or invalid state in authn response")
self._check_error_response(authn_resp, context)
access_token, id_token_claims = self._get_tokens(authn_resp, context)
if id_token_claims:
self._verify_nonce(id_token_claims["nonce"], context)
else:
id_token_claims = {}
userinfo = {}
if access_token:
# make userinfo request
userinfo = self._get_userinfo(authn_resp["state"], context)
if not id_token_claims and not userinfo:
satosa_logging(logger, logging.ERROR, "No id_token or userinfo, nothing to do..", context.state)
raise SATOSAAuthenticationError(context.state, "No user info available.")
all_user_claims = dict(list(userinfo.items()) + list(id_token_claims.items()))
satosa_logging(logger, logging.DEBUG, "UserInfo: %s" % all_user_claims, context.state)
del context.state[self.name]
internal_resp = self._translate_response(all_user_claims, self.client.authorization_endpoint)
return self.auth_callback_func(context, internal_resp) |
Translates oidc response to SATOSA internal response.
:type response: dict[str, str]
:type issuer: str
:type subject_type: str
:rtype: InternalData
:param response: Dictioary with attribute name as key.
:param issuer: The oidc op that gave the repsonse.
:param subject_type: public or pairwise according to oidc standard.
:return: A SATOSA internal response. | def _translate_response(self, response, issuer):
"""
Translates oidc response to SATOSA internal response.
:type response: dict[str, str]
:type issuer: str
:type subject_type: str
:rtype: InternalData
:param response: Dictioary with attribute name as key.
:param issuer: The oidc op that gave the repsonse.
:param subject_type: public or pairwise according to oidc standard.
:return: A SATOSA internal response.
"""
auth_info = AuthenticationInformation(UNSPECIFIED, str(datetime.now()), issuer)
internal_resp = InternalData(auth_info=auth_info)
internal_resp.attributes = self.converter.to_internal("openid", response)
internal_resp.subject_id = response["sub"]
return internal_resp |
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 | 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) |
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
: | 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)) |
Ask the account linking service for a uuid.
If the given issuer/id pair is not linked, then the function will return a ticket.
This ticket should be used for linking the issuer/id pair to the user account
:type context: satosa.context.Context
:type issuer: str
:type id: str
:rtype: (int, str)
:param context: The current context
:param issuer: the issuer used for authentication
:param id: the given id
:return: response status code and message
(200, uuid) or (404, ticket) | def _get_uuid(self, context, issuer, id):
"""
Ask the account linking service for a uuid.
If the given issuer/id pair is not linked, then the function will return a ticket.
This ticket should be used for linking the issuer/id pair to the user account
:type context: satosa.context.Context
:type issuer: str
:type id: str
:rtype: (int, str)
:param context: The current context
:param issuer: the issuer used for authentication
:param id: the given id
:return: response status code and message
(200, uuid) or (404, ticket)
"""
data = {
"idp": issuer,
"id": id,
"redirect_endpoint": "%s/account_linking%s" % (self.base_url, self.endpoint)
}
jws = JWS(json.dumps(data), alg=self.signing_key.alg).sign_compact([self.signing_key])
try:
request = "{}/get_id?jwt={}".format(self.api_url, jws)
response = requests.get(request)
except Exception as con_exc:
msg = "Could not connect to account linking service"
satosa_logging(logger, logging.CRITICAL, msg, context.state, exc_info=True)
raise SATOSAAuthenticationError(context.state, msg) from con_exc
if response.status_code not in [200, 404]:
msg = "Got status code '%s' from account linking service" % (response.status_code)
satosa_logging(logger, logging.CRITICAL, msg, context.state)
raise SATOSAAuthenticationError(context.state, msg)
return response.status_code, response.text |
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 | 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 |
Returns the targeted frontend and original state
:type context: satosa.context.Context
:rtype satosa.frontends.base.FrontendModule
:param context: The response context
:return: frontend | 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 |
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 | 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)) |
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 | 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) |
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 | 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) |
Sends a response to the requester about the error
:type error: satosa.exception.SATOSAAuthenticationError
:rtype: satosa.response.Response
:param error: The exception
:return: response | 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) |
Load state from cookie to the context
:type context: satosa.context.Context
:param context: Session context | 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 |
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 | 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))) |
Runs the satosa proxy with the given context.
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The request context
:return: response | 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 |
Creates SAML metadata strings for the configured front- and backends.
:param satosa_config: configuration of the proxy
:return: a tuple of the frontend metadata (containing IdP entities) and the backend metadata (containing SP
entities).
:type satosa_config: satosa.satosa_config.SATOSAConfig
:rtype: Tuple[str, str] | def create_entity_descriptors(satosa_config):
"""
Creates SAML metadata strings for the configured front- and backends.
:param satosa_config: configuration of the proxy
:return: a tuple of the frontend metadata (containing IdP entities) and the backend metadata (containing SP
entities).
:type satosa_config: satosa.satosa_config.SATOSAConfig
:rtype: Tuple[str, str]
"""
frontend_modules = load_frontends(satosa_config, None, satosa_config["INTERNAL_ATTRIBUTES"])
backend_modules = load_backends(satosa_config, None, satosa_config["INTERNAL_ATTRIBUTES"])
logger.info("Loaded frontend plugins: {}".format([frontend.name for frontend in frontend_modules]))
logger.info("Loaded backend plugins: {}".format([backend.name for backend in backend_modules]))
backend_metadata = _create_backend_metadata(backend_modules)
frontend_metadata = _create_frontend_metadata(frontend_modules, backend_modules)
return frontend_metadata, backend_metadata |
:param entity_descriptors: the entity descriptors to put in in an EntitiesDescriptor tag and sign
:param security_context: security context for the signature
:param valid_for: number of hours the metadata should be valid
:return: the signed XML document
:type entity_descriptors: Sequence[saml2.md.EntityDescriptor]]
:type security_context: saml2.sigver.SecurityContext
:type valid_for: Optional[int] | def create_signed_entities_descriptor(entity_descriptors, security_context, valid_for=None):
"""
:param entity_descriptors: the entity descriptors to put in in an EntitiesDescriptor tag and sign
:param security_context: security context for the signature
:param valid_for: number of hours the metadata should be valid
:return: the signed XML document
:type entity_descriptors: Sequence[saml2.md.EntityDescriptor]]
:type security_context: saml2.sigver.SecurityContext
:type valid_for: Optional[int]
"""
entities_desc, xmldoc = entities_descriptor(entity_descriptors, valid_for=valid_for, name=None, ident=None,
sign=True, secc=security_context)
if not valid_instance(entities_desc):
raise ValueError("Could not construct valid EntitiesDescriptor tag")
return xmldoc |
:param entity_descriptor: the entity descriptor to sign
:param security_context: security context for the signature
:param valid_for: number of hours the metadata should be valid
:return: the signed XML document
:type entity_descriptor: saml2.md.EntityDescriptor]
:type security_context: saml2.sigver.SecurityContext
:type valid_for: Optional[int] | def create_signed_entity_descriptor(entity_descriptor, security_context, valid_for=None):
"""
:param entity_descriptor: the entity descriptor to sign
:param security_context: security context for the signature
:param valid_for: number of hours the metadata should be valid
:return: the signed XML document
:type entity_descriptor: saml2.md.EntityDescriptor]
:type security_context: saml2.sigver.SecurityContext
:type valid_for: Optional[int]
"""
if valid_for:
entity_descriptor.valid_until = in_a_while(hours=valid_for)
entity_desc, xmldoc = sign_entity_descriptor(entity_descriptor, None, security_context)
if not valid_instance(entity_desc):
raise ValueError("Could not construct valid EntityDescriptor tag")
return xmldoc |
See super class method satosa.backends.base.BackendModule#start_auth
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.Response | def start_auth(self, context, internal_req):
"""
See super class method satosa.backends.base.BackendModule#start_auth
:type context: satosa.context.Context
:type internal_req: satosa.internal.InternalData
:rtype: satosa.response.Response
"""
target_entity_id = context.get_decoration(Context.KEY_TARGET_ENTITYID)
if target_entity_id:
entity_id = target_entity_id
return self.authn_request(context, entity_id)
# if there is only one IdP in the metadata, bypass the discovery service
idps = self.sp.metadata.identity_providers()
if len(idps) == 1 and "mdq" not in self.config["sp_config"]["metadata"]:
entity_id = idps[0]
return self.authn_request(context, entity_id)
return self.disco_query() |
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 | 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) |
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 | 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) |
Endpoint for the idp response
:type context: satosa.context,Context
:type binding: str
:rtype: satosa.response.Response
:param context: The current context
:param binding: The saml binding type
:return: response | def authn_response(self, context, binding):
"""
Endpoint for the idp response
:type context: satosa.context,Context
:type binding: str
:rtype: satosa.response.Response
:param context: The current context
:param binding: The saml binding type
:return: response
"""
if not context.request["SAMLResponse"]:
satosa_logging(logger, logging.DEBUG, "Missing Response for state", context.state)
raise SATOSAAuthenticationError(context.state, "Missing Response")
try:
authn_response = self.sp.parse_authn_request_response(
context.request["SAMLResponse"],
binding, outstanding=self.outstanding_queries)
except Exception as err:
satosa_logging(logger, logging.DEBUG, "Failed to parse authn request for state", context.state,
exc_info=True)
raise SATOSAAuthenticationError(context.state, "Failed to parse authn request") from err
if self.sp.config.getattr('allow_unsolicited', 'sp') is False:
req_id = authn_response.in_response_to
if req_id not in self.outstanding_queries:
errmsg = "No request with id: {}".format(req_id),
satosa_logging(logger, logging.DEBUG, errmsg, context.state)
raise SATOSAAuthenticationError(context.state, errmsg)
del self.outstanding_queries[req_id]
# check if the relay_state matches the cookie state
if context.state[self.name]["relay_state"] != context.request["RelayState"]:
satosa_logging(logger, logging.DEBUG,
"State did not match relay state for state", context.state)
raise SATOSAAuthenticationError(context.state, "State did not match relay state")
context.decorate(Context.KEY_BACKEND_METADATA_STORE, self.sp.metadata)
del context.state[self.name]
return self.auth_callback_func(context, self._translate_response(authn_response, context.state)) |
Endpoint for the discovery server response
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: 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) |
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 | 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 |
Endpoint for retrieving the backend metadata
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response with metadata | def _metadata_endpoint(self, context):
"""
Endpoint for retrieving the backend metadata
:type context: satosa.context.Context
:rtype: satosa.response.Response
:param context: The current context
:return: response with metadata
"""
satosa_logging(logger, logging.DEBUG, "Sending metadata response", context.state)
metadata_string = create_metadata_string(None, self.sp.config, 4, None, None, None, None,
None).decode("utf-8")
return Response(metadata_string, content="text/xml") |
See super class method satosa.backends.base.BackendModule#register_endpoints
:rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))] | def register_endpoints(self):
"""
See super class method satosa.backends.base.BackendModule#register_endpoints
:rtype list[(str, ((satosa.context.Context, Any) -> Any, Any))]
"""
url_map = []
sp_endpoints = self.sp.config.getattr("endpoints", "sp")
for endp, binding in sp_endpoints["assertion_consumer_service"]:
parsed_endp = urlparse(endp)
url_map.append(("^%s$" % parsed_endp.path[1:], functools.partial(self.authn_response, binding=binding)))
if self.discosrv:
for endp, binding in sp_endpoints["discovery_response"]:
parsed_endp = urlparse(endp)
url_map.append(
("^%s$" % parsed_endp.path[1:], self.disco_response))
if self.expose_entityid_endpoint():
parsed_entity_id = urlparse(self.sp.config.entityid)
url_map.append(("^{0}".format(parsed_entity_id.path[1:]),
self._metadata_endpoint))
return url_map |
See super class satosa.backends.backend_base.BackendModule#get_metadata_desc
:rtype: satosa.metadata_creation.description.MetadataDescription | def get_metadata_desc(self):
"""
See super class satosa.backends.backend_base.BackendModule#get_metadata_desc
:rtype: satosa.metadata_creation.description.MetadataDescription
"""
entity_descriptions = []
idp_entities = self.sp.metadata.with_descriptor("idpsso")
for entity_id, entity in idp_entities.items():
description = MetadataDescription(urlsafe_b64encode(entity_id.encode("utf-8")).decode("utf-8"))
# Add organization info
try:
organization_info = entity["organization"]
except KeyError:
pass
else:
organization = OrganizationDesc()
for name_info in organization_info.get("organization_name", []):
organization.add_name(name_info["text"], name_info["lang"])
for display_name_info in organization_info.get("organization_display_name", []):
organization.add_display_name(display_name_info["text"], display_name_info["lang"])
for url_info in organization_info.get("organization_url", []):
organization.add_url(url_info["text"], url_info["lang"])
description.organization = organization
# Add contact person info
try:
contact_persons = entity["contact_person"]
except KeyError:
pass
else:
for person in contact_persons:
person_desc = ContactPersonDesc()
person_desc.contact_type = person.get("contact_type")
for address in person.get('email_address', []):
person_desc.add_email_address(address["text"])
if "given_name" in person:
person_desc.given_name = person["given_name"]["text"]
if "sur_name" in person:
person_desc.sur_name = person["sur_name"]["text"]
description.add_contact_person(person_desc)
# Add UI info
ui_info = self.sp.metadata.extension(entity_id, "idpsso_descriptor", "{}&UIInfo".format(UI_NAMESPACE))
if ui_info:
ui_info = ui_info[0]
ui_info_desc = UIInfoDesc()
for desc in ui_info.get("description", []):
ui_info_desc.add_description(desc["text"], desc["lang"])
for name in ui_info.get("display_name", []):
ui_info_desc.add_display_name(name["text"], name["lang"])
for logo in ui_info.get("logo", []):
ui_info_desc.add_logo(logo["text"], logo["width"], logo["height"], logo.get("lang"))
description.ui_info = ui_info_desc
entity_descriptions.append(description)
return entity_descriptions |
Returns a dictionary representation of the ContactPersonDesc.
The format is the same as a pysaml2 configuration for a contact person.
:rtype: dict[str, str]
:return: A dictionary representation | def to_dict(self):
"""
Returns a dictionary representation of the ContactPersonDesc.
The format is the same as a pysaml2 configuration for a contact person.
:rtype: dict[str, str]
:return: A dictionary representation
"""
person = {}
if self.contact_type:
person["contact_type"] = self.contact_type
if self._email_address:
person["email_address"] = self._email_address
if self.given_name:
person["given_name"] = self.given_name
if self.sur_name:
person["sur_name"] = self.sur_name
return person |
Binds a logo to the given language
:type text: str
:type width: str
:type height: str
:type lang: Optional[str]
:param text: Path to logo
:param width: width of logo
:param height: height of logo
:param lang: language | def add_logo(self, text, width, height, lang=None):
"""
Binds a logo to the given language
:type text: str
:type width: str
:type height: str
:type lang: Optional[str]
:param text: Path to logo
:param width: width of logo
:param height: height of logo
:param lang: language
"""
logo_entry ={"text": text, "width": width, "height": height}
if lang:
logo_entry["lang"] = lang
self._logos.append(logo_entry) |
Returns a dictionary representation of the UIInfoDesc object.
The format is the same as a pysaml2 configuration for ui info.
:rtype: dict[str, str]
:return: A dictionary representation | def to_dict(self):
"""
Returns a dictionary representation of the UIInfoDesc object.
The format is the same as a pysaml2 configuration for ui info.
:rtype: dict[str, str]
:return: A dictionary representation
"""
ui_info = {}
if self._description:
ui_info["description"] = self._description
if self._display_name:
ui_info["display_name"] = self._display_name
if self._logos:
ui_info["logo"] = self._logos
return {"service": {"idp": {"ui_info": ui_info}}} if ui_info else {} |
Returns a dictionary representation of the OrganizationDesc object.
The format is the same as a pysaml2 configuration for organization.
:rtype: dict[str, str]
:return: A dictionary representation | def to_dict(self):
"""
Returns a dictionary representation of the OrganizationDesc object.
The format is the same as a pysaml2 configuration for organization.
:rtype: dict[str, str]
:return: A dictionary representation
"""
org = {}
if self._display_name:
org["display_name"] = self._display_name
if self._name:
org["name"] = self._name
if self._url:
org["url"] = self._url
return {"organization": org} if org else {} |
Set an organization to the description
:type organization: satosa.metadata_creation.description.OrganizationDesc
:param organization: Organization description | def organization(self, organization):
"""
Set an organization to the description
:type organization: satosa.metadata_creation.description.OrganizationDesc
:param organization: Organization description
"""
if not isinstance(organization, OrganizationDesc):
raise TypeError("organization must be of type OrganizationDesc")
self._organization = organization |
Adds a contact person to the description
:type person: satosa.metadata_creation.description.ContactPersonDesc
:param person: The contact person to be added | def add_contact_person(self, person):
"""
Adds a contact person to the description
:type person: satosa.metadata_creation.description.ContactPersonDesc
:param person: The contact person to be added
"""
if not isinstance(person, ContactPersonDesc):
raise TypeError("person must be of type ContactPersonDesc")
self._contact_person.append(person) |
Set an ui info to the description
:type ui_info: satosa.metadata_creation.description.UIInfoDesc
:param ui_info: The ui info to be set | def ui_info(self, ui_info):
"""
Set an ui info to the description
:type ui_info: satosa.metadata_creation.description.UIInfoDesc
:param ui_info: The ui info to be set
"""
if not isinstance(ui_info, UIInfoDesc):
raise TypeError("ui_info must be of type UIInfoDesc")
self._ui_info = ui_info |
Returns a dictionary representation of the MetadataDescription object.
The format is the same as a pysaml2 configuration
:rtype: dict[str, Any]
:return: A dictionary representation | def to_dict(self):
"""
Returns a dictionary representation of the MetadataDescription object.
The format is the same as a pysaml2 configuration
:rtype: dict[str, Any]
:return: A dictionary representation
"""
description = {}
description["entityid"] = self.entity_id
if self._organization:
description.update(self._organization.to_dict())
if self._contact_person:
description['contact_person'] = []
for person in self._contact_person:
description['contact_person'].append(person.to_dict())
if self._ui_info:
description.update(self._ui_info.to_dict())
return description |
See super class method satosa.frontends.base.FrontendModule#handle_authn_response
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype oic.utils.http_util.Response | def handle_authn_response(self, context, internal_resp, extra_id_token_claims=None):
"""
See super class method satosa.frontends.base.FrontendModule#handle_authn_response
:type context: satosa.context.Context
:type internal_response: satosa.internal.InternalData
:rtype oic.utils.http_util.Response
"""
auth_req = self._get_authn_request_from_state(context.state)
attributes = self.converter.from_internal("openid", internal_resp.attributes)
self.user_db[internal_resp.subject_id] = {k: v[0] for k, v in attributes.items()}
auth_resp = self.provider.authorize(
auth_req,
internal_resp.subject_id,
extra_id_token_claims=extra_id_token_claims,
)
del context.state[self.name]
http_response = auth_resp.request(auth_req["redirect_uri"], should_fragment_encode(auth_req))
return SeeOther(http_response) |
See super class satosa.frontends.base.FrontendModule
:type exception: satosa.exception.SATOSAError
:rtype: oic.utils.http_util.Response | def handle_backend_error(self, exception):
"""
See super class satosa.frontends.base.FrontendModule
:type exception: satosa.exception.SATOSAError
:rtype: oic.utils.http_util.Response
"""
auth_req = self._get_authn_request_from_state(exception.state)
# If the client sent us a state parameter, we should reflect it back according to the spec
if 'state' in auth_req:
error_resp = AuthorizationErrorResponse(error="access_denied",
error_description=exception.message,
state=auth_req['state'])
else:
error_resp = AuthorizationErrorResponse(error="access_denied",
error_description=exception.message)
satosa_logging(logger, logging.DEBUG, exception.message, exception.state)
return SeeOther(error_resp.request(auth_req["redirect_uri"], should_fragment_encode(auth_req))) |
See super class satosa.frontends.base.FrontendModule
:type backend_names: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
:raise ValueError: if more than one backend is configured | def register_endpoints(self, backend_names):
"""
See super class satosa.frontends.base.FrontendModule
:type backend_names: list[str]
:rtype: list[(str, ((satosa.context.Context, Any) -> satosa.response.Response, Any))]
:raise ValueError: if more than one backend is configured
"""
backend_name = None
if len(backend_names) != 1:
# only supports one backend since there currently is no way to publish multiple authorization endpoints
# in configuration information and there is no other standard way of authorization_endpoint discovery
# similar to SAML entity discovery
# this can be circumvented with a custom RequestMicroService which handles the routing based on something
# in the authentication request
logger.warn("More than one backend is configured, make sure to provide a custom routing micro service to "
"determine which backend should be used per request.")
else:
backend_name = backend_names[0]
endpoint_baseurl = "{}/{}".format(self.base_url, self.name)
self._create_provider(endpoint_baseurl)
provider_config = ("^.well-known/openid-configuration$", self.provider_config)
jwks_uri = ("^{}/jwks$".format(self.name), self.jwks)
if backend_name:
# if there is only one backend, include its name in the path so the default routing can work
auth_endpoint = "{}/{}/{}/{}".format(self.base_url, backend_name, self.name, AuthorizationEndpoint.url)
self.provider.configuration_information["authorization_endpoint"] = auth_endpoint
auth_path = urlparse(auth_endpoint).path.lstrip("/")
else:
auth_path = "{}/{}".format(self.name, AuthorizationEndpoint.url)
authentication = ("^{}$".format(auth_path), self.handle_authn_request)
url_map = [provider_config, jwks_uri, authentication]
if any("code" in v for v in self.provider.configuration_information["response_types_supported"]):
self.provider.configuration_information["token_endpoint"] = "{}/{}".format(endpoint_baseurl,
TokenEndpoint.url)
token_endpoint = ("^{}/{}".format(self.name, TokenEndpoint.url), self.token_endpoint)
url_map.append(token_endpoint)
self.provider.configuration_information["userinfo_endpoint"] = "{}/{}".format(endpoint_baseurl,
UserinfoEndpoint.url)
userinfo_endpoint = ("^{}/{}".format(self.name, UserinfoEndpoint.url), self.userinfo_endpoint)
url_map.append(userinfo_endpoint)
if "registration_endpoint" in self.provider.configuration_information:
client_registration = ("^{}/{}".format(self.name, RegistrationEndpoint.url), self.client_registration)
url_map.append(client_registration)
return url_map |
Validates that all necessary config parameters are specified.
:type config: dict[str, dict[str, Any] | str]
:param config: the module config | def _validate_config(self, config):
"""
Validates that all necessary config parameters are specified.
:type config: dict[str, dict[str, Any] | str]
:param config: the module config
"""
if config is None:
raise ValueError("OIDCFrontend conf can't be 'None'.")
for k in {"signing_key_path", "provider"}:
if k not in config:
raise ValueError("Missing configuration parameter '{}' for OpenID Connect frontend.".format(k)) |
Handle the OIDC dynamic client registration.
:type context: satosa.context.Context
:rtype: oic.utils.http_util.Response
:param context: the current context
:return: HTTP response to the client | def client_registration(self, context):
"""
Handle the OIDC dynamic client registration.
:type context: satosa.context.Context
:rtype: oic.utils.http_util.Response
:param context: the current context
:return: HTTP response to the client
"""
try:
resp = self.provider.handle_client_registration_request(json.dumps(context.request))
return Created(resp.to_json(), content="application/json")
except InvalidClientRegistrationRequest as e:
return BadRequest(e.to_json(), content="application/json") |
Handle an authentication request and pass it on to the backend.
:type context: satosa.context.Context
:rtype: oic.utils.http_util.Response
:param context: the current context
:return: HTTP response to the client | def handle_authn_request(self, context):
"""
Handle an authentication request and pass it on to the backend.
:type context: satosa.context.Context
:rtype: oic.utils.http_util.Response
:param context: the current context
:return: HTTP response to the client
"""
internal_req = self._handle_authn_request(context)
if not isinstance(internal_req, InternalData):
return internal_req
return self.auth_req_callback_func(context, internal_req) |
Parse and verify the authentication request into an internal request.
:type context: satosa.context.Context
:rtype: satosa.internal.InternalData
:param context: the current context
:return: the internal request | def _handle_authn_request(self, context):
"""
Parse and verify the authentication request into an internal request.
:type context: satosa.context.Context
:rtype: satosa.internal.InternalData
:param context: the current context
:return: the internal request
"""
request = urlencode(context.request)
satosa_logging(logger, logging.DEBUG, "Authn req from client: {}".format(request),
context.state)
try:
authn_req = self.provider.parse_authentication_request(request)
except InvalidAuthenticationRequest as e:
satosa_logging(logger, logging.ERROR, "Error in authn req: {}".format(str(e)),
context.state)
error_url = e.to_error_url()
if error_url:
return SeeOther(error_url)
else:
return BadRequest("Something went wrong: {}".format(str(e)))
client_id = authn_req["client_id"]
context.state[self.name] = {"oidc_request": request}
subject_type = self.provider.clients[client_id].get("subject_type", "pairwise")
client_name = self.provider.clients[client_id].get("client_name")
if client_name:
# TODO should process client names for all languages, see OIDC Registration, Section 2.1
requester_name = [{"lang": "en", "text": client_name}]
else:
requester_name = None
internal_req = InternalData(
subject_type=subject_type,
requester=client_id,
requester_name=requester_name,
)
internal_req.attributes = self.converter.to_internal_filter(
"openid", self._get_approved_attributes(self.provider.configuration_information["claims_supported"],
authn_req))
return internal_req |
Construct the JWKS document (served at /jwks).
:type context: satosa.context.Context
:rtype: oic.utils.http_util.Response
:param context: the current context
:return: HTTP response to the client | def jwks(self, context):
"""
Construct the JWKS document (served at /jwks).
:type context: satosa.context.Context
:rtype: oic.utils.http_util.Response
:param context: the current context
:return: HTTP response to the client
"""
return Response(json.dumps(self.provider.jwks), content="application/json") |
Handle token requests (served at /token).
:type context: satosa.context.Context
:rtype: oic.utils.http_util.Response
:param context: the current context
:return: HTTP response to the client | def token_endpoint(self, context):
"""
Handle token requests (served at /token).
:type context: satosa.context.Context
:rtype: oic.utils.http_util.Response
:param context: the current context
:return: HTTP response to the client
"""
headers = {"Authorization": context.request_authorization}
try:
response = self.provider.handle_token_request(urlencode(context.request), headers)
return Response(response.to_json(), content="application/json")
except InvalidClientAuthentication as e:
logger.debug('invalid client authentication at token endpoint', exc_info=True)
error_resp = TokenErrorResponse(error='invalid_client', error_description=str(e))
response = Unauthorized(error_resp.to_json(), headers=[("WWW-Authenticate", "Basic")],
content="application/json")
return response
except OAuthError as e:
logger.debug('invalid request: %s', str(e), exc_info=True)
error_resp = TokenErrorResponse(error=e.oauth_error, error_description=str(e))
return BadRequest(error_resp.to_json(), content="application/json") |
Mako filter: used to extract scope from attribute
:param s: string to extract scope from (filtered string in mako template)
:return: the scope | def scope(s):
"""
Mako filter: used to extract scope from attribute
:param s: string to extract scope from (filtered string in mako template)
:return: the scope
"""
if '@' not in s:
raise ValueError("Unscoped string")
(local_part, _, domain_part) = s.partition('@')
return domain_part |
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 | 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) |
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 | 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 |
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" | 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 |
Attempts to serialize a version with the given serialization format.
Raises MissingValueForSerializationException if not serializable | 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 |
Sets or returns the option selected in a ButtonGroup by its text value. | 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 "" |
Resizes the widget.
:param int width:
The width of the widget.
:param int height:
The height of the widget. | def resize(self, width, height):
"""
Resizes the widget.
:param int width:
The width of the widget.
:param int height:
The height of the widget.
"""
self._width = width
self._height = height
# update radio buttons width
for item in self._rbuttons:
item.width = width
# update radio buttons height
if len(self._rbuttons) > 0:
# work out the height of a button
button_height = height
if isinstance(height, int):
if height % len(self._rbuttons) != 0:
# if the height doesnt divide by the number of radio buttons give a warning
button_height = int(round(height / len(self._rbuttons)))
new_height = button_height * len(self._rbuttons)
utils.error_format("ButtonGroup height '{}' doesn't divide by the number of buttons '{}' setting height to '{}'.".format(height, len(self._rbuttons), new_height))
else:
button_height = int(height / len(self._rbuttons))
for item in self._rbuttons:
item.height = button_height
super(ButtonGroup, self).resize(width, 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. | 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) |
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. | 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) |
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. | 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 |
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`. | 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) |
Resets the combo box to the original "selected" value from the
constructor (or the first value if no selected value was specified). | def select_default(self):
"""
Resets the combo box to the original "selected" value from the
constructor (or the first value if no selected value was specified).
"""
if self._default is None:
if not self._set_option_by_index(0):
utils.error_format(self.description + "\n" +
"Unable to select default option as the Combo is empty")
else:
if not self._set_option(self._default):
utils.error_format( self.description + "\n" +
"Unable to select default option as it doesnt exist in the Combo") |
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. | 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() |
Removes the first `option` from the Combo.
Returns `True` if an item was removed.
:param string option:
The option to remove from the Combo. | 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 |
Clears all the options in a Combo | def clear(self):
"""
Clears all the options in a Combo
"""
self._options = []
self._combo_menu.tk.delete(0, END)
self._selected.set("") |
Sets a single option in the Combo, returning True if it was able too. | 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 |
Sets a single option in the Combo by its index, returning True if it was able too. | 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 |
Call `function` after `time` milliseconds. | 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] |
Repeat `function` every `time` milliseconds. | 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] |
Cancel the scheduled `function` calls. | 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") |
Fired by tk.after, gets the callback and either executes the function and cancels or repeats | 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) |
Resizes the widget.
:param int width:
The width of the widget.
:param int height:
The height of the widget. | def resize(self, width, height):
"""
Resizes the widget.
:param int width:
The width of the widget.
:param int height:
The height of the widget.
"""
self._width = width
self._height = height
if width != "fill":
self._set_tk_config("width", width)
if height != "fill":
self._set_tk_config("height", height)
if width == "fill" or height == "fill":
self.master.display_widgets() |
Converts a color from "color", (255, 255, 255) or "#ffffff" into a color tk
should understand. | def convert_color(color):
"""
Converts a color from "color", (255, 255, 255) or "#ffffff" into a color tk
should understand.
"""
if color is not None:
# is the color a string
if isinstance(color, str):
# strip the color of white space
color = color.strip()
# if it starts with a # check it is a valid color
if color[0] == "#":
# check its format
if len(color) != 7:
raise ValueError("{} is not a valid # color, it must be in the format #ffffff.".format(color))
else:
# split the color into its hex values
hex_colors = (color[1:3], color[3:5], color[5:7])
# check hex values are between 00 and ff
for hex_color in hex_colors:
try:
int_color = int(hex_color, 16)
except:
raise ValueError("{} is not a valid value, it must be hex 00 - ff".format(hex_color))
if not (0 <= int_color <= 255):
raise ValueError("{} is not a valid color value, it must be 00 - ff".format(hex_color))
# if the color is not a string, try and convert it
else:
# get the number of colors and check it is iterable
try:
no_of_colors = len(color)
except:
raise ValueError("A color must be a list or tuple of 3 values (red, green, blue)")
if no_of_colors != 3:
raise ValueError("A color must contain 3 values (red, green, blue)")
# check the color values are between 0 and 255
for c in color:
if not (0 <= c <= 255):
raise ValueError("{} is not a valid color value, it must be 0 - 255")
# convert to #ffffff format
color = "#{:02x}{:02x}{:02x}".format(color[0], color[1], color[2])
return color |
Sets a callback for a ref (reference), setting to None will remove it | def set_callback(self, ref, callback):
"""
Sets a callback for a ref (reference), setting to None will remove it
"""
# if the callback already exists, remove it
self.remove_callback(ref)
# add it to the callbacks
if callback is not None:
self._callbacks[ref] = callback |
Rebinds the tk event, only used if a widget has been destroyed
and recreated. | 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) |
Returns the event callback for a ref (reference) | def get_event(self, ref):
"""
Returns the event callback for a ref (reference)
"""
# is this reference one which has been setup?
if ref in self._refs:
return self._refs[ref].get_callback(ref)
else:
return None |
Sets a callback for this widget against a ref (reference) for a
tk_event, setting the callback to None will remove it. | def set_event(self, ref, tk_event, callback):
"""
Sets a callback for this widget against a ref (reference) for a
tk_event, setting the callback to None will remove it.
"""
# has an EventCallback been created for this tk event
if tk_event not in self._event_callbacks:
self._event_callbacks[tk_event] = EventCallback(self._widget, self._tks, tk_event)
# assign this ref to this event callback
self._refs[ref] = self._event_callbacks[tk_event]
# set up the callback
self._refs[ref].set_callback(ref, callback) |
Removes an event for a ref (reference), | def remove_event(self, ref):
"""
Removes an event for a ref (reference),
"""
# is this reference one which has been setup?
if ref in self._refs:
self._refs[ref].remove_callback(ref) |
Rebinds all the tk events, only used if a tk widget has been destroyed
and recreated. | 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) |
Sets the border thickness and color.
:param int thickness:
The thickenss of the border.
:param str color:
The color of the 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)) |
Resizes the widget.
:param int width:
The width of the widget.
:param int height:
The height of the widget. | def resize(self, width, height):
"""
Resizes the widget.
:param int width:
The width of the widget.
:param int height:
The height of the widget.
"""
self._set_propagation(width, height)
super(Box, self).resize(width, height) |
Hide the window. | def hide(self):
"""Hide the window."""
self.tk.withdraw()
self._visible = False
if self._modal:
self.tk.grab_release() |
Show the window. | def show(self, wait = False):
"""Show the window."""
self.tk.deiconify()
self._visible = True
self._modal = wait
if self._modal:
self.tk.grab_set() |
Destroy and close the App.
:return:
None.
:note:
Once destroyed an App can no longer be used. | 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() |
Resizes the widget.
:param int width:
The width of the widget.
:param int height:
The height of the widget. | def resize(self, width, height):
"""
Resizes the widget.
:param int width:
The width of the widget.
:param int height:
The height of the widget.
"""
# set the internal listbox width to be 0 as otherwise it maintains a default
# size and you cant make the control smaller than that.
self._listbox._set_tk_config("width", None if width is None else 0)
self._set_propagation(width, height)
super(ListBox, self).resize(width, height) |
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. | 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)
) |