INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token:
def create_token(self, request, refresh_token=False, **kwargs): """ Create a BearerToken, by default without refresh token. :param request: OAuthlib request. :type request: oauthlib.common.Request :param refresh_token: """ if "save_token" in kwargs: w...
:param request: OAuthlib request. :type request: oauthlib.common.Request
def validate_request(self, request): """ :param request: OAuthlib request. :type request: oauthlib.common.Request """ token = get_token_from_header(request) return self.request_validator.validate_bearer_token( token, request.scopes, request)
Convert a list of scopes to a space separated string.
def list_to_scope(scope): """Convert a list of scopes to a space separated string.""" if isinstance(scope, unicode_type) or scope is None: return scope elif isinstance(scope, (set, tuple, list)): return " ".join([unicode_type(s) for s in scope]) else: raise ValueError("Invalid sc...
Convert a space separated string to a list of scopes.
def scope_to_list(scope): """Convert a space separated string to a list of scopes.""" if isinstance(scope, (tuple, list, set)): return [unicode_type(s) for s in scope] elif scope is None: return None else: return scope.strip().split(" ")
Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI.
def host_from_uri(uri): """Extract hostname and port from URI. Will use default port for HTTP and HTTPS if none is present in the URI. """ default_ports = { 'HTTP': '80', 'HTTPS': '443', } sch, netloc, path, par, query, fra = urlparse(uri) if ':' in netloc: netloc, ...
Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2
def escape(u): """Escape a string in an OAuth-compatible fashion. TODO: verify whether this can in fact be used for OAuth 2 """ if not isinstance(u, unicode_type): raise ValueError('Only unicode objects are escapable.') return quote(u.encode('utf-8'), safe=b'~')
Generate a age parameter for MAC authentication draft 00.
def generate_age(issue_time): """Generate a age parameter for MAC authentication draft 00.""" td = datetime.datetime.now() - issue_time age = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6 return unicode_type(age)
Create a request token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :pa...
def validate_protected_resource_request(self, uri, http_method='GET', body=None, headers=None, realms=None): """Create a request token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A va...
Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oauthlib.oauth2.BearerToken. If the resource owner grants the a...
def create_token_response(self, request, token_handler): """Return token or error embedded in the URI fragment. :param request: OAuthlib request. :type request: oauthlib.common.Request :param token_handler: A token handler instance, for example of type oaut...
Check the token request for normal and fatal errors. :param request: OAuthlib request. :type request: oauthlib.common.Request This method is very similar to validate_authorization_request in the AuthorizationCodeGrant but differ in a few subtle areas. A normal error could be a...
def validate_token_request(self, request): """Check the token request for normal and fatal errors. :param request: OAuthlib request. :type request: oauthlib.common.Request This method is very similar to validate_authorization_request in the AuthorizationCodeGrant but differ in ...
Validates the OpenID Connect authorization request parameters. :returns: (list of scopes, dict of request info)
def validate_authorization_request(self, request): """Validates the OpenID Connect authorization request parameters. :returns: (list of scopes, dict of request info) """ # If request.prompt is 'none' then no login/authorization form should # be presented to the user. Instead, a ...
Perform OpenID Connect specific authorization request validation. nonce OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed through unmodified from the Authentication Request to ...
def openid_authorization_validator(self, request): """Perform OpenID Connect specific authorization request validation. nonce OPTIONAL. String value used to associate a Client session with an ID Token, and to mitigate replay attacks. The value is passed t...
Additional validation when following the Authorization Code flow.
def openid_authorization_validator(self, request): """Additional validation when following the Authorization Code flow. """ request_info = super(HybridGrant, self).openid_authorization_validator(request) if not request_info: # returns immediately if OAuth2.0 return request_i...
Decorator which filters params to remove non-oauth_* parameters Assumes the decorated method takes a params dict or list of tuples as its first argument.
def filter_params(target): """Decorator which filters params to remove non-oauth_* parameters Assumes the decorated method takes a params dict or list of tuples as its first argument. """ def wrapper(params, *args, **kwargs): params = filter_oauth_params(params) return target(params...
Removes all non oauth parameters from a dict or a list of params.
def filter_oauth_params(params): """Removes all non oauth parameters from a dict or a list of params.""" is_oauth = lambda kv: kv[0].startswith("oauth_") if isinstance(params, dict): return list(filter(is_oauth, list(params.items()))) else: return list(filter(is_oauth, params))
Parse an OAuth authorization header into a list of 2-tuples
def parse_authorization_header(authorization_header): """Parse an OAuth authorization header into a list of 2-tuples""" auth_scheme = 'OAuth '.lower() if authorization_header[:len(auth_scheme)].lower().startswith(auth_scheme): items = parse_http_list(authorization_header[len(auth_scheme):]) ...
Additional validation when following the implicit flow.
def openid_authorization_validator(self, request): """Additional validation when following the implicit flow. """ request_info = super(ImplicitGrant, self).openid_authorization_validator(request) if not request_info: # returns immediately if OAuth2.0 return request_info ...
Create and save a new access token. Similar to OAuth 2, indication of granted scopes will be included as a space separated list in ``oauth_authorized_realms``. :param request: OAuthlib request. :type request: oauthlib.common.Request :returns: The token as an urlencoded string.
def create_access_token(self, request, credentials): """Create and save a new access token. Similar to OAuth 2, indication of granted scopes will be included as a space separated list in ``oauth_authorized_realms``. :param request: OAuthlib request. :type request: oauthlib.comm...
Create an access token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :pa...
def create_access_token_response(self, uri, http_method='GET', body=None, headers=None, credentials=None): """Create an access token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP ...
Validate client, code etc, return body + headers
def verify_request(self, uri, http_method='GET', body=None, headers=None, scopes=None): """Validate client, code etc, return body + headers""" request = Request(uri, http_method, body, headers) request.token_type = self.find_token_type(request) request.scopes = sco...
Token type identification. RFC 6749 does not provide a method for easily differentiating between different token types during protected resource access. We estimate the most likely token type (if any) by asking each known token type to give an estimation based on the request.
def find_token_type(self, request): """Token type identification. RFC 6749 does not provide a method for easily differentiating between different token types during protected resource access. We estimate the most likely token type (if any) by asking each known token type to give...
http://wiki.apache.org/spamassassin/TopSharedMemoryBug
def val_accuracy(show_swap): """http://wiki.apache.org/spamassassin/TopSharedMemoryBug""" kv = kernel_ver() pid = os.getpid() swap_accuracy = -1 if kv[:2] == (2,4): if proc.open('meminfo').read().find("Inact_") == -1: return 1, swap_accuracy return 0, swap_accuracy el...
Read the tfstate file and load its contents, parses then as JSON and put the result into the object
def load_file(file_path): """ Read the tfstate file and load its contents, parses then as JSON and put the result into the object """ log.debug('read data from {0}'.format(file_path)) if os.path.exists(file_path): with open(file_path) as f: json_data =...
refer to https://terraform.io/docs/commands/apply.html no-color is flagged by default :param no_color: disable color of stdout :param input: disable prompt for a missing variable :param dir_or_plan: folder relative to working folder :param skip_plan: force apply without plan (def...
def apply(self, dir_or_plan=None, input=False, skip_plan=False, no_color=IsFlagged, **kwargs): """ refer to https://terraform.io/docs/commands/apply.html no-color is flagged by default :param no_color: disable color of stdout :param input: disable prompt for a missi...
refer to https://www.terraform.io/docs/commands/destroy.html force/no-color option is flagged by default :return: ret_code, stdout, stderr
def destroy(self, dir_or_plan=None, force=IsFlagged, **kwargs): """ refer to https://www.terraform.io/docs/commands/destroy.html force/no-color option is flagged by default :return: ret_code, stdout, stderr """ default = kwargs default['force'] = force opt...
refer to https://www.terraform.io/docs/commands/plan.html :param detailed_exitcode: Return a detailed exit code when the command exits. :param dir_or_plan: relative path to plan/folder :param kwargs: options :return: ret_code, stdout, stderr
def plan(self, dir_or_plan=None, detailed_exitcode=IsFlagged, **kwargs): """ refer to https://www.terraform.io/docs/commands/plan.html :param detailed_exitcode: Return a detailed exit code when the command exits. :param dir_or_plan: relative path to plan/folder :param kwargs: opt...
refer to https://www.terraform.io/docs/commands/init.html By default, this assumes you want to use backend config, and tries to init fresh. The flags -reconfigure and -backend=true are default. :param dir_or_plan: relative path to the folder want to init :param backend_config: a dictio...
def init(self, dir_or_plan=None, backend_config=None, reconfigure=IsFlagged, backend=True, **kwargs): """ refer to https://www.terraform.io/docs/commands/init.html By default, this assumes you want to use backend config, and tries to init fresh. The flags -reconfigure and -...
for any generate_cmd_string doesn't written as public method of terraform examples: 1. call import command, ref to https://www.terraform.io/docs/commands/import.html --> generate_cmd_string call: terraform import -input=true aws_instance.foo i-abcd1234 --> python...
def generate_cmd_string(self, cmd, *args, **kwargs): """ for any generate_cmd_string doesn't written as public method of terraform examples: 1. call import command, ref to https://www.terraform.io/docs/commands/import.html --> generate_cmd_string call: te...
run a terraform command, if success, will try to read state file :param cmd: command and sub-command of terraform, seperated with space refer to https://www.terraform.io/docs/commands/index.html :param args: arguments of a command :param kwargs: any option flag with key valu...
def cmd(self, cmd, *args, **kwargs): """ run a terraform command, if success, will try to read state file :param cmd: command and sub-command of terraform, seperated with space refer to https://www.terraform.io/docs/commands/index.html :param args: arguments of a comm...
https://www.terraform.io/docs/commands/output.html Note that this method does not conform to the (ret_code, out, err) return convention. To use the "output" command with the standard convention, call "output_cmd" instead of "output". :param args: Positional arguments. There is one op...
def output(self, *args, **kwargs): """ https://www.terraform.io/docs/commands/output.html Note that this method does not conform to the (ret_code, out, err) return convention. To use the "output" command with the standard convention, call "output_cmd" instead of "output". ...
read .tfstate file :param file_path: relative path to working dir :return: states file in dict type
def read_state_file(self, file_path=None): """ read .tfstate file :param file_path: relative path to working dir :return: states file in dict type """ working_dir = self.working_dir or '' file_path = file_path or self.state or '' if not file_path: ...
Validates the response object. :param request_data: Request Data :type request_data: dict :param request_id: Optional argument. The ID of the AuthNRequest sent by this SP to the IdP :type request_id: string :param raise_exceptions: Whether to return false on failure or raise a...
def is_valid(self, request_data, request_id=None, raise_exceptions=False): """ Validates the response object. :param request_data: Request Data :type request_data: dict :param request_id: Optional argument. The ID of the AuthNRequest sent by this SP to the IdP :type req...
Gets the audiences :returns: The valid audiences for the SAML Response :rtype: list
def get_audiences(self): """ Gets the audiences :returns: The valid audiences for the SAML Response :rtype: list """ audience_nodes = self.__query_assertion('/saml:Conditions/saml:AudienceRestriction/saml:Audience') return [OneLogin_Saml2_Utils.element_text(node)...
Gets the authentication contexts :returns: The authentication classes for the SAML Response :rtype: list
def get_authn_contexts(self): """ Gets the authentication contexts :returns: The authentication classes for the SAML Response :rtype: list """ authn_context_nodes = self.__query_assertion('/saml:AuthnStatement/saml:AuthnContext/saml:AuthnContextClassRef') return ...
Gets the issuers (from message and from assertion) :returns: The issuers :rtype: list
def get_issuers(self): """ Gets the issuers (from message and from assertion) :returns: The issuers :rtype: list """ issuers = [] message_issuer_nodes = OneLogin_Saml2_Utils.query(self.document, '/samlp:Response/saml:Issuer') if len(message_issuer_nodes)...
Gets the NameID Data provided by the SAML Response from the IdP :returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier) :rtype: dict
def get_nameid_data(self): """ Gets the NameID Data provided by the SAML Response from the IdP :returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier) :rtype: dict """ nameid = None nameid_data = {} encrypted_id_data_nodes = self.__query_a...
Verifies that the document has the expected signed nodes. :param signed_elements: The signed elements to be checked :type signed_elements: list :param raise_exceptions: Whether to return false on failure or raise an exception :type raise_exceptions: Boolean
def validate_signed_elements(self, signed_elements): """ Verifies that the document has the expected signed nodes. :param signed_elements: The signed elements to be checked :type signed_elements: list :param raise_exceptions: Whether to return false on failure or raise an excep...
Extracts nodes that match the query from the Response :param query: Xpath Expresion :type query: String :param tagid: Tag ID :type query: String :returns: The queried nodes :rtype: list
def __query(self, query, tagid=None): """ Extracts nodes that match the query from the Response :param query: Xpath Expresion :type query: String :param tagid: Tag ID :type query: String :returns: The queried nodes :rtype: list """ if se...
Decrypts the Assertion :raises: Exception if no private key available :param dom: Encrypted Assertion :type dom: Element :returns: Decrypted Assertion :rtype: Element
def __decrypt_assertion(self, dom): """ Decrypts the Assertion :raises: Exception if no private key available :param dom: Encrypted Assertion :type dom: Element :returns: Decrypted Assertion :rtype: Element """ key = self.__settings.get_sp_key()...
Gets the Issuer of the Logout Response Message :return: The Issuer :rtype: string
def get_issuer(self): """ Gets the Issuer of the Logout Response Message :return: The Issuer :rtype: string """ issuer = None issuer_nodes = self.__query('/samlp:LogoutResponse/saml:Issuer') if len(issuer_nodes) == 1: issuer = OneLogin_Saml2_Ut...
Determines if the SAML LogoutResponse is valid :param request_id: The ID of the LogoutRequest sent by this SP to the IdP :type request_id: string :param raise_exceptions: Whether to return false on failure or raise an exception :type raise_exceptions: Boolean :return: Returns if ...
def is_valid(self, request_data, request_id=None, raise_exceptions=False): """ Determines if the SAML LogoutResponse is valid :param request_id: The ID of the LogoutRequest sent by this SP to the IdP :type request_id: string :param raise_exceptions: Whether to return false on fai...
Extracts a node from the DOMDocument (Logout Response Menssage) :param query: Xpath Expresion :type query: string :return: The queried node :rtype: DOMNodeList
def __query(self, query): """ Extracts a node from the DOMDocument (Logout Response Menssage) :param query: Xpath Expresion :type query: string :return: The queried node :rtype: DOMNodeList """ # Switch to lxml for querying xml = self.document.toxm...
Returns the Logout Response defated, base64encoded :param deflate: It makes the deflate process optional :type: bool :return: Logout Response maybe deflated and base64 encoded :rtype: string
def get_response(self, deflate=True): """ Returns the Logout Response defated, base64encoded :param deflate: It makes the deflate process optional :type: bool :return: Logout Response maybe deflated and base64 encoded :rtype: string """ if deflate: ...
Gets the metadata XML from the provided URL :param url: Url where the XML of the Identity Provider Metadata is published. :type url: string :param validate_cert: If the url uses https schema, that flag enables or not the verification of the associated certificate. :type validate_cert: ...
def get_metadata(url, validate_cert=True): """ Gets the metadata XML from the provided URL :param url: Url where the XML of the Identity Provider Metadata is published. :type url: string :param validate_cert: If the url uses https schema, that flag enables or not the verificati...
Parse the Identity Provider metadata and return a dict with extracted data. If there are multiple <IDPSSODescriptor> tags, parse only the first. Parse only those SSO endpoints with the same binding as given by the `required_sso_binding` parameter. Parse only those SLO endpoints with t...
def parse( idp_metadata, required_sso_binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT, required_slo_binding=OneLogin_Saml2_Constants.BINDING_HTTP_REDIRECT, entity_id=None): """ Parse the Identity Provider metadata and return a dict with extracted da...
Auxiliary method. It overrides the default xmlsec debug message.
def print_xmlsec_errors(filename, line, func, error_object, error_subject, reason, msg): """ Auxiliary method. It overrides the default xmlsec debug message. """ info = [] if error_object != "unknown": info.append("obj=" + error_object) if error_subject != "unknown": info.append...
base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :type value: string :returns: the string after decoding and inflating :rtype: string
def decode_base64_and_inflate(value): """ base64 decodes and then inflates according to RFC1951 :param value: a deflated and encoded string :type value: string :returns: the string after decoding and inflating :rtype: string """ decoded = base64.b64decode(...
Validates a xml against a schema :param xml: The xml that will be validated :type: string|DomDocument :param schema: The schema :type: string :param debug: If debug is active, the parse-errors will be showed :type: bool :returns: Error code or the DomDocument of t...
def validate_xml(xml, schema, debug=False): """ Validates a xml against a schema :param xml: The xml that will be validated :type: string|DomDocument :param schema: The schema :type: string :param debug: If debug is active, the parse-errors will be showed ...
Executes a redirection to the provided url (or return the target url). :param url: The target url :type: string :param parameters: Extra parameters to be passed as part of the url :type: dict :param request_data: The request as a dict :type: dict :returns: Url...
def redirect(url, parameters={}, request_data={}): """ Executes a redirection to the provided url (or return the target url). :param url: The target url :type: string :param parameters: Extra parameters to be passed as part of the url :type: dict :param request...
Returns the current host. :param request_data: The request as a dict :type: dict :return: The current host :rtype: string
def get_self_host(request_data): """ Returns the current host. :param request_data: The request as a dict :type: dict :return: The current host :rtype: string """ if 'http_host' in request_data: current_host = request_data['http_host'] ...
Interprets a ISO8601 duration value relative to a given timestamp. :param duration: The duration, as a string. :type: string :param timestamp: The unix timestamp we should apply the duration to. Optional, default to the current time. :type: string :re...
def parse_duration(duration, timestamp=None): """ Interprets a ISO8601 duration value relative to a given timestamp. :param duration: The duration, as a string. :type: string :param timestamp: The unix timestamp we should apply the duration to. Optiona...
Generates a nameID. :param value: fingerprint :type: string :param sp_nq: SP Name Qualifier :type: string :param sp_format: SP Format :type: string :param cert: IdP Public Cert to encrypt the nameID :type: string :param debug: Activate the xml...
def generate_name_id(value, sp_nq, sp_format=None, cert=None, debug=False, nq=None): """ Generates a nameID. :param value: fingerprint :type: string :param sp_nq: SP Name Qualifier :type: string :param sp_format: SP Format :type: string :param ...
Gets Status from a Response. :param dom: The Response as XML :type: Document :returns: The Status, an array with the code and a message. :rtype: dict
def get_status(dom): """ Gets Status from a Response. :param dom: The Response as XML :type: Document :returns: The Status, an array with the code and a message. :rtype: dict """ status = {} status_entry = OneLogin_Saml2_Utils.query(dom, '/samlp...
Decrypts an encrypted element. :param encrypted_data: The encrypted data. :type: lxml.etree.Element | DOMElement | basestring :param key: The key. :type: string :param debug: Activate the xmlsec debug :type: bool :param inplace: update passed data with decrypt...
def decrypt_element(encrypted_data, key, debug=False, inplace=False): """ Decrypts an encrypted element. :param encrypted_data: The encrypted data. :type: lxml.etree.Element | DOMElement | basestring :param key: The key. :type: string :param debug: Activate the...
Writes some content into a temporary file and returns it. :param content: The file content :type: string :returns: The temporary file :rtype: file-like object
def write_temp_file(content): """ Writes some content into a temporary file and returns it. :param content: The file content :type: string :returns: The temporary file :rtype: file-like object """ f_temp = NamedTemporaryFile(delete=True) f_temp.f...
Adds signature key and senders certificate to an element (Message or Assertion). :param xml: The element we should sign :type: string | Document :param key: The private key :type: string :param cert: The public :type: string :param debug: Activate the ...
def add_sign(xml, key, cert, debug=False, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1, digest_algorithm=OneLogin_Saml2_Constants.SHA1): """ Adds signature key and senders certificate to an element (Message or Assertion). :param xml: The element we should sign :type: string ...
Validates a signature (Message or Assertion). :param xml: The element we should validate :type: string | Document :param cert: The pubic cert :type: string :param fingerprint: The fingerprint of the public cert :type: string :param fingerprintalg: The algorith...
def validate_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False, xpath=None, multicerts=None): """ Validates a signature (Message or Assertion). :param xml: The element we should validate :type: string | Document :param cert: The pubic...
Validates a signature of a EntityDescriptor. :param xml: The element we should validate :type: string | Document :param cert: The pubic cert :type: string :param fingerprint: The fingerprint of the public cert :type: string :param fingerprintalg: The algorithm...
def validate_metadata_sign(xml, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False): """ Validates a signature of a EntityDescriptor. :param xml: The element we should validate :type: string | Document :param cert: The pubic cert :type: ...
Validates a signature node. :param signature_node: The signature node :type: Node :param xml: The element we should validate :type: Document :param cert: The public cert :type: string :param fingerprint: The fingerprint of the public cert :type: string...
def validate_node_sign(signature_node, elem, cert=None, fingerprint=None, fingerprintalg='sha1', validatecert=False, debug=False): """ Validates a signature node. :param signature_node: The signature node :type: Node :param xml: The element we should validate :type: Doc...
Validates signed binary data (Used to validate GET Signature). :param signed_query: The element we should validate :type: string :param signature: The signature that will be validate :type: string :param cert: The public cert :type: string :param algorithm: S...
def validate_binary_sign(signed_query, signature, cert=None, algorithm=OneLogin_Saml2_Constants.RSA_SHA1, debug=False): """ Validates signed binary data (Used to validate GET Signature). :param signed_query: The element we should validate :type: string :param signature: The si...
Return a URL encoded get parameter value Prefer to extract the original encoded value directly from query_string since URL encoding is not canonical. The encoding used by ADFS 3.0 is not compatible with python's quote_plus (ADFS produces lower case hex numbers and quote_plus produces upp...
def get_encoded_parameter(get_data, name, default=None, lowercase_urlencoding=False): """Return a URL encoded get parameter value Prefer to extract the original encoded value directly from query_string since URL encoding is not canonical. The encoding used by ADFS 3.0 is not compatible with ...
Loads settings info from the settings json file :returns: True if the settings info is valid :rtype: boolean
def __load_settings_from_file(self): """ Loads settings info from the settings json file :returns: True if the settings info is valid :rtype: boolean """ filename = self.get_base_path() + 'settings.json' if not exists(filename): raise OneLogin_Saml2_...
Add default values if the settings info is not complete
def __add_default_values(self): """ Add default values if the settings info is not complete """ self.__sp.setdefault('assertionConsumerService', {}) self.__sp['assertionConsumerService'].setdefault('binding', OneLogin_Saml2_Constants.BINDING_HTTP_POST) self.__sp.setdefau...
Checks the SP settings info. :param settings: Dict with settings data :type settings: dict :returns: Errors found on the SP settings data :rtype: list
def check_sp_settings(self, settings): """ Checks the SP settings info. :param settings: Dict with settings data :type settings: dict :returns: Errors found on the SP settings data :rtype: list """ assert isinstance(settings, dict) errors = [] ...
Validates an XML SP Metadata. :param xml: Metadata's XML that will be validate :type xml: string :returns: The list of found errors :rtype: list
def validate_metadata(self, xml): """ Validates an XML SP Metadata. :param xml: Metadata's XML that will be validate :type xml: string :returns: The list of found errors :rtype: list """ assert isinstance(xml, basestring) if len(xml) == 0: ...
Returns the requested SAML attribute. :param name: Name of the attribute :type name: string :returns: Attribute value if exists or [] :rtype: string
def get_attribute(self, name): """ Returns the requested SAML attribute. :param name: Name of the attribute :type name: string :returns: Attribute value if exists or [] :rtype: string """ assert isinstance(name, basestring) value = None i...
Initiates the SSO process. :param return_to: Optional argument. The target URL the user should be redirected to after login. :type return_to: string :param force_authn: Optional argument. When true the AuthNRequest will set the ForceAuthn='true'. :type force_authn: bool :param...
def login(self, return_to=None, force_authn=False, is_passive=False, set_nameid_policy=True, name_id_value_req=None): """ Initiates the SSO process. :param return_to: Optional argument. The target URL the user should be redirected to after login. :type return_to: string :param ...
Initiates the SLO process. :param return_to: Optional argument. The target URL the user should be redirected to after logout. :type return_to: string :param name_id: The NameID that will be set in the LogoutRequest. :type name_id: string :param session_index: SessionIndex that...
def logout(self, return_to=None, name_id=None, session_index=None, nq=None, name_id_format=None): """ Initiates the SLO process. :param return_to: Optional argument. The target URL the user should be redirected to after logout. :type return_to: string :param name_id: The NameID...
Gets the SLO URL. :returns: An URL, the SLO endpoint of the IdP :rtype: string
def get_slo_url(self): """ Gets the SLO URL. :returns: An URL, the SLO endpoint of the IdP :rtype: string """ url = None idp_data = self.__settings.get_idp_data() if 'singleLogoutService' in idp_data.keys() and 'url' in idp_data['singleLogoutService']: ...
Builds the Signature of the SAML Request. :param saml_request: The SAML Request :type saml_request: string :param relay_state: The target URL the user should be redirected to :type relay_state: string :param sign_algorithm: Signature algorithm method :type sign_algorit...
def build_request_signature(self, saml_request, relay_state, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1): """ Builds the Signature of the SAML Request. :param saml_request: The SAML Request :type saml_request: string :param relay_state: The target URL the user should be r...
Builds the Signature of the SAML Response. :param saml_request: The SAML Response :type saml_request: string :param relay_state: The target URL the user should be redirected to :type relay_state: string :param sign_algorithm: Signature algorithm method :type sign_algori...
def build_response_signature(self, saml_response, relay_state, sign_algorithm=OneLogin_Saml2_Constants.RSA_SHA1): """ Builds the Signature of the SAML Response. :param saml_request: The SAML Response :type saml_request: string :param relay_state: The target URL the user should b...
Retrieves the raw XML (decrypted) of the last SAML response, or the last Logout Response generated or processed :returns: SAML response XML :rtype: string|None
def get_last_response_xml(self, pretty_print_if_possible=False): """ Retrieves the raw XML (decrypted) of the last SAML response, or the last Logout Response generated or processed :returns: SAML response XML :rtype: string|None """ response = None if sel...
Builds the metadata of the SP :param sp: The SP data :type sp: string :param authnsign: authnRequestsSigned attribute :type authnsign: string :param wsign: wantAssertionsSigned attribute :type wsign: string :param valid_until: Metadata's expiry date :t...
def builder(sp, authnsign=False, wsign=False, valid_until=None, cache_duration=None, contacts=None, organization=None): """ Builds the metadata of the SP :param sp: The SP data :type sp: string :param authnsign: authnRequestsSigned attribute :type authnsign: string ...
Adds the x509 descriptors (sign/encryption) to the metadata The same cert will be used for sign/encrypt :param metadata: SAML Metadata XML :type metadata: string :param cert: x509 cert :type cert: string :param add_encryption: Determines if the KeyDescriptor[use="encry...
def add_x509_key_descriptors(metadata, cert=None, add_encryption=True): """ Adds the x509 descriptors (sign/encryption) to the metadata The same cert will be used for sign/encrypt :param metadata: SAML Metadata XML :type metadata: string :param cert: x509 cert :...
Returns the Logout Request deflated, base64encoded :param deflate: It makes the deflate process optional :type: bool :return: Logout Request maybe deflated and base64 encoded :rtype: str object
def get_request(self, deflate=True): """ Returns the Logout Request deflated, base64encoded :param deflate: It makes the deflate process optional :type: bool :return: Logout Request maybe deflated and base64 encoded :rtype: str object """ if deflate: ...
Returns the ID of the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: string ID :rtype: str object
def get_id(request): """ Returns the ID of the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: string ID :rtype: str object """ if isinstance(request, etree._Element): elem = request else...
Gets the NameID Data of the the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :param key: The SP key :type key: string :return: Name ID Data (Value, Format, NameQualifier, SPNameQualifier) :rtype: dict
def get_nameid_data(request, key=None): """ Gets the NameID Data of the the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :param key: The SP key :type key: string :return: Name ID Data (Value, Format, NameQualifier, SPName...
Gets the Issuer of the Logout Request Message :param request: Logout Request Message :type request: string|DOMDocument :return: The Issuer :rtype: string
def get_issuer(request): """ Gets the Issuer of the Logout Request Message :param request: Logout Request Message :type request: string|DOMDocument :return: The Issuer :rtype: string """ if isinstance(request, etree._Element): elem = request ...
Gets the SessionIndexes from the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: The SessionIndex value :rtype: list
def get_session_indexes(request): """ Gets the SessionIndexes from the Logout Request :param request: Logout Request Message :type request: string|DOMDocument :return: The SessionIndex value :rtype: list """ if isinstance(request, etree._Element): ...
Checks if the Logout Request received is valid :param request_data: Request Data :type request_data: dict :param raise_exceptions: Whether to return false on failure or raise an exception :type raise_exceptions: Boolean :return: If the Logout Request is or not valid :rtyp...
def is_valid(self, request_data, raise_exceptions=False): """ Checks if the Logout Request received is valid :param request_data: Request Data :type request_data: dict :param raise_exceptions: Whether to return false on failure or raise an exception :type raise_exceptions...
Fits an EWMA model to a time series. Uses the first point in the time series as a starting value. Uses sum squared error as an objective function to optimize to find smoothing parameter The model for EWMA is recursively defined as S_t = (1 - a) * X_t + a * S_{t-1}, where a is the smoothing parameter, X is t...
def fit_model(ts, sc=None): """ Fits an EWMA model to a time series. Uses the first point in the time series as a starting value. Uses sum squared error as an objective function to optimize to find smoothing parameter The model for EWMA is recursively defined as S_t = (1 - a) * X_t + a * S_{t-1}, where ...
Add PySpark to the library path based on the value of SPARK_HOME.
def add_pyspark_path(): """Add PySpark to the library path based on the value of SPARK_HOME. """ try: spark_home = os.environ['SPARK_HOME'] sys.path.append(os.path.join(spark_home, 'python')) py4j_src_zip = glob(os.path.join(spark_home, 'python', ...
Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch.
def datetime_to_nanos(dt): """ Accepts a string, Pandas Timestamp, or long, and returns nanos since the epoch. """ if isinstance(dt, pd.Timestamp): return dt.value elif isinstance(dt, str): return pd.Timestamp(dt).value elif isinstance(dt, long): return dt elif isinst...
Utility function to help in fitting an automatically selected ARIMA model based on approximate Akaike Information Criterion (AIC) values. The model search is based on the heuristic developed by Hyndman and Khandakar (2008) and described in [[http://www.jstatsoft .org/v27/i03/paper]]. In contrast to the algo...
def autofit(ts, maxp=5, maxd=2, maxq=5, sc=None): """ Utility function to help in fitting an automatically selected ARIMA model based on approximate Akaike Information Criterion (AIC) values. The model search is based on the heuristic developed by Hyndman and Khandakar (2008) and described in [[http://w...
Given a time series, fit a non-seasonal ARIMA model of order (p, d, q), where p represents the autoregression terms, d represents the order of differencing, and q moving average error terms. If includeIntercept is true, the model is fitted with an intercept. In order to select the appropriate order of the m...
def fit_model(p, d, q, ts, includeIntercept=True, method="css-cgd", userInitParams=None, sc=None): """ Given a time series, fit a non-seasonal ARIMA model of order (p, d, q), where p represents the autoregression terms, d represents the order of differencing, and q moving average error terms. If include...
log likelihood based on conditional sum of squares Source: http://www.nuffield.ox.ac.uk/economics/papers/1997/w6/ma.pdf Parameters ---------- y: time series as a DenseVector returns log likelihood as a double
def log_likelihood_css(self, y): """ log likelihood based on conditional sum of squares Source: http://www.nuffield.ox.ac.uk/economics/papers/1997/w6/ma.pdf Parameters ---------- y: time series as a DenseVector returns log likelihood as a do...
log likelihood based on conditional sum of squares. In contrast to logLikelihoodCSS the array provided should correspond to an already differenced array, so that the function below corresponds to the log likelihood for the ARMA rather than the ARIMA process Parameters ----------...
def log_likelihood_css_arma(self, diffedy): """ log likelihood based on conditional sum of squares. In contrast to logLikelihoodCSS the array provided should correspond to an already differenced array, so that the function below corresponds to the log likelihood for the ARMA rather than ...
Calculates the gradient for the log likelihood function using CSS Derivation: L(y | \theta) = -\frac{n}{2}log(2\pi\sigma^2) - \frac{1}{2\pi}\sum_{i=1}^n \epsilon_t^2 \\ \sigma^2 = \frac{\sum_{i = 1}^n \epsilon_t^2}{n} \\ \frac{\partial L}{\partial \theta} = -\frac{1}{\sigma^2...
def gradient_log_likelihood_css_arma(self, diffedy): """ Calculates the gradient for the log likelihood function using CSS Derivation: L(y | \theta) = -\frac{n}{2}log(2\pi\sigma^2) - \frac{1}{2\pi}\sum_{i=1}^n \epsilon_t^2 \\ \sigma^2 = \frac{\sum_{i = 1}^n \epsilon_t^2}{...
Sample a series of size n assuming an ARIMA(p, d, q) process. Parameters ---------- n: size of sample Returns a series reflecting ARIMA(p, d, q) process as a DenseVector
def sample(self, n): """ Sample a series of size n assuming an ARIMA(p, d, q) process. Parameters ---------- n: size of sample Returns a series reflecting ARIMA(p, d, q) process as a DenseVector """ rg = self._ctx._jvm.org...
Provided fitted values for timeseries ts as 1-step ahead forecasts, based on current model parameters, and then provide `nFuture` periods of forecast. We assume AR terms prior to the start of the series are equal to the model's intercept term (or 0.0, if fit without and intercept term).Meanwhile...
def forecast(self, ts, nfuture): """ Provided fitted values for timeseries ts as 1-step ahead forecasts, based on current model parameters, and then provide `nFuture` periods of forecast. We assume AR terms prior to the start of the series are equal to the model's intercept term (or 0.0,...
Parameters ---------- ts: time series to which to fit an ARIMA model as a Numpy array regressors: regression matrix as a Numpy array method: Regression method. Currently, only "cochrane-orcutt" is supported. optimizationArgs: sc: The SparkContext, require...
def fit_model(ts, regressors, method="cochrane-orcutt", optimizationArgs=None, sc=None): """ Parameters ---------- ts: time series to which to fit an ARIMA model as a Numpy array regressors: regression matrix as a Numpy array method: Regression method. Currently, only "co...
Fit linear regression model with AR(1) errors , for references on Cochrane Orcutt model: See [[https://onlinecourses.science.psu.edu/stat501/node/357]] See : Applied Linear Statistical Models - Fifth Edition - Michael H. Kutner , page 492 The method assumes the time series to have the following model ...
def fit_cochrane_orcutt(ts, regressors, maxIter=10, sc=None): """ Fit linear regression model with AR(1) errors , for references on Cochrane Orcutt model: See [[https://onlinecourses.science.psu.edu/stat501/node/357]] See : Applied Linear Statistical Models - Fifth Edition - Michael H. Kutner , page 492...
Fits an AR(1) model to the given time series Parameters ---------- ts: the time series to which we want to fit an autoregression model as a Numpy array Returns an ARModel
def fit_model(ts, maxLag=1, noIntercept=False, sc=None): """ Fits an AR(1) model to the given time series Parameters ---------- ts: the time series to which we want to fit an autoregression model as a Numpy array Returns an ARModel """ assert sc != None, "Missing Sp...
Given a timeseries, apply inverse operations to obtain the original series of underlying errors. Parameters ---------- ts: Time series of observations with this model's characteristics as a Numpy array returns the time series with removed time-dependent effects as a ...
def remove_time_dependent_effects(self, ts): """ Given a timeseries, apply inverse operations to obtain the original series of underlying errors. Parameters ---------- ts: Time series of observations with this model's characteristics as a Numpy array ...
Given a timeseries, apply a model to it. Parameters ---------- ts: Time series of i.i.d. observations as a Numpy array returns the time series with added time-dependent effects as a Numpy array.
def add_time_dependent_effects(self, ts): """ Given a timeseries, apply a model to it. Parameters ---------- ts: Time series of i.i.d. observations as a Numpy array returns the time series with added time-dependent effects as a Numpy array. ...
Fits an AR(1) + GARCH(1, 1) model to the given time series. Parameters ---------- ts: the time series to which we want to fit a AR+GARCH model as a Numpy array Returns an ARGARCH model
def fit_model(ts, sc=None): """ Fits an AR(1) + GARCH(1, 1) model to the given time series. Parameters ---------- ts: the time series to which we want to fit a AR+GARCH model as a Numpy array Returns an ARGARCH model """ assert sc != None, "Missing SparkContext" ...
Instantiates a uniform DateTimeIndex. Either end or periods must be specified. Parameters ---------- start : string, long (nanos from epoch), or Pandas Timestamp end : string, long (nanos from epoch), or Pandas Timestamp periods : int freq : a frequency object s...
def uniform(start, end=None, periods=None, freq=None, sc=None): """ Instantiates a uniform DateTimeIndex. Either end or periods must be specified. Parameters ---------- start : string, long (nanos from epoch), or Pandas Timestamp end : string, long (nanos from epoch), or Pandas...
Instantiates an irregular DateTimeIndex. Parameters ---------- timestamps : a Pandas DateTimeIndex, or an array of strings, longs (nanos from epoch), Pandas Timestamps sc : SparkContext
def irregular(timestamps, sc): """ Instantiates an irregular DateTimeIndex. Parameters ---------- timestamps : a Pandas DateTimeIndex, or an array of strings, longs (nanos from epoch), Pandas Timestamps sc : SparkContext """ dtmodule = sc._jvm.com.cloudera.sparkt...
Extracts nanoseconds from a ZonedDateTime
def _zdt_to_nanos(self, zdt): """Extracts nanoseconds from a ZonedDateTime""" instant = zdt.toInstant() return instant.getNano() + instant.getEpochSecond() * 1000000000
Returns the timestamp at the given integer location as a Pandas Timestamp.
def datetime_at_loc(self, loc): """Returns the timestamp at the given integer location as a Pandas Timestamp.""" return pd.Timestamp(self._zdt_to_nanos(self._jdt_index.dateTimeAtLoc(loc)))