idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
231,800 | def phase2radians ( phasedata , v0 ) : fi = [ 2 * np . pi * v0 * xx for xx in phasedata ] return fi | Convert phase in seconds to phase in radians |
231,801 | def frequency2fractional ( frequency , mean_frequency = - 1 ) : if mean_frequency == - 1 : mu = np . mean ( frequency ) else : mu = mean_frequency y = [ ( x - mu ) / mu for x in frequency ] return y | Convert frequency in Hz to fractional frequency |
231,802 | def set_input ( self , data , rate = 1.0 , data_type = "phase" , taus = None ) : self . inp [ "data" ] = data self . inp [ "rate" ] = rate self . inp [ "data_type" ] = data_type self . inp [ "taus" ] = taus | Optionnal method if you chose not to set inputs on init |
231,803 | def compute ( self , function ) : try : func = getattr ( allantools , function ) except AttributeError : raise AttributeError ( "function must be defined in allantools" ) whitelisted = [ "theo1" , "mtie" , "tierms" ] if function [ - 3 : ] != "dev" and function not in whitelisted : raise RuntimeError ( "function must be... | Evaluate the passed function with the supplied data . |
231,804 | def many_psds ( k = 2 , fs = 1.0 , b0 = 1.0 , N = 1024 ) : psd = [ ] for j in range ( k ) : print j x = noise . white ( N = 2 * 4096 , b0 = b0 , fs = fs ) f , tmp = noise . numpy_psd ( x , fs ) if j == 0 : psd = tmp else : psd = psd + tmp return f , psd / k | compute average of many PSDs |
231,805 | def list_my ( self ) : org_list = self . call_contract_command ( "Registry" , "listOrganizations" , [ ] ) rez_owner = [ ] rez_member = [ ] for idx , org_id in enumerate ( org_list ) : ( found , org_id , org_name , owner , members , serviceNames , repositoryNames ) = self . call_contract_command ( "Registry" , "getOrgan... | Find organization that has the current identity as the owner or as the member |
231,806 | def add_group ( self , group_name , payment_address ) : if ( self . is_group_name_exists ( group_name ) ) : raise Exception ( "the group \"%s\" is already present" % str ( group_name ) ) group_id_base64 = base64 . b64encode ( secrets . token_bytes ( 32 ) ) self . m [ "groups" ] += [ { "group_name" : group_name , "group... | Return new group_id in base64 |
231,807 | def is_group_name_exists ( self , group_name ) : groups = self . m [ "groups" ] for g in groups : if ( g [ "group_name" ] == group_name ) : return True return False | check if group with given name is already exists |
231,808 | def get_group_name_nonetrick ( self , group_name = None ) : groups = self . m [ "groups" ] if ( len ( groups ) == 0 ) : raise Exception ( "Cannot find any groups in metadata" ) if ( not group_name ) : if ( len ( groups ) > 1 ) : raise Exception ( "We have more than one payment group in metadata, so group_name should be... | In all getter function in case of single payment group group_name can be None |
231,809 | def get_from_ipfs_and_checkhash ( ipfs_client , ipfs_hash_base58 , validate = True ) : if validate : from snet_cli . resources . proto . unixfs_pb2 import Data from snet_cli . resources . proto . merckledag_pb2 import MerkleNode block_data = ipfs_client . block_get ( ipfs_hash_base58 ) mn = MerkleNode ( ) mn . ParseFro... | Get file from ipfs We must check the hash becasue we cannot believe that ipfs_client wasn t been compromise |
231,810 | def hash_to_bytesuri ( s ) : s = "ipfs://" + s return s . encode ( "ascii" ) . ljust ( 32 * ( len ( s ) // 32 + 1 ) , b"\0" ) | Convert in and from bytes uri format used in Registry contract |
231,811 | def _get_stub_and_request_classes ( self , service_name ) : codegen_dir = Path . home ( ) . joinpath ( ".snet" , "mpe_client" , "control_service" ) proto_dir = Path ( __file__ ) . absolute ( ) . parent . joinpath ( "resources" , "proto" ) if ( not codegen_dir . joinpath ( "control_service_pb2.py" ) . is_file ( ) ) : co... | import protobuf and return stub and request class |
231,812 | def _start_claim_channels ( self , grpc_channel , channels_ids ) : unclaimed_payments = self . _call_GetListUnclaimed ( grpc_channel ) unclaimed_payments_dict = { p [ "channel_id" ] : p for p in unclaimed_payments } to_claim = [ ] for channel_id in channels_ids : if ( channel_id not in unclaimed_payments_dict or unclai... | Safely run StartClaim for given channels |
231,813 | def _claim_in_progress_and_claim_channels ( self , grpc_channel , channels ) : payments = self . _call_GetListInProgress ( grpc_channel ) if ( len ( payments ) > 0 ) : self . _printout ( "There are %i payments in 'progress' (they haven't been claimed in blockchain). We will claim them." % len ( payments ) ) self . _blo... | Claim all pending payments in progress and after we claim given channels |
231,814 | def create_default_config ( self ) : self . _config_file . parent . mkdir ( mode = 0o700 , exist_ok = True ) self [ "network.kovan" ] = { "default_eth_rpc_endpoint" : "https://kovan.infura.io" , "default_gas_price" : "medium" } self [ "network.mainnet" ] = { "default_eth_rpc_endpoint" : "https://mainnet.infura.io" , "d... | Create default configuration if config file does not exist |
231,815 | def switch_to_json_payload_encoding ( call_fn , response_class ) : def json_serializer ( * args , ** kwargs ) : return bytes ( json_format . MessageToJson ( args [ 0 ] , True , preserving_proto_field_name = True ) , "utf-8" ) def json_deserializer ( * args , ** kwargs ) : resp = response_class ( ) json_format . Parse (... | Switch payload encoding to JSON for GRPC call |
231,816 | def print_agi_and_mpe_balances ( self ) : if ( self . args . account ) : account = self . args . account else : account = self . ident . address eth_wei = self . w3 . eth . getBalance ( account ) agi_cogs = self . call_contract_command ( "SingularityNetToken" , "balanceOf" , [ account ] ) mpe_cogs = self . call_contrac... | Print balance of ETH AGI and MPE wallet |
231,817 | def publish_proto_in_ipfs ( self ) : ipfs_hash_base58 = utils_ipfs . publish_proto_in_ipfs ( self . _get_ipfs_client ( ) , self . args . protodir ) self . _printout ( ipfs_hash_base58 ) | Publish proto files in ipfs and print hash |
231,818 | def publish_proto_metadata_update ( self ) : metadata = load_mpe_service_metadata ( self . args . metadata_file ) ipfs_hash_base58 = utils_ipfs . publish_proto_in_ipfs ( self . _get_ipfs_client ( ) , self . args . protodir ) metadata . set_simple_field ( "model_ipfs_hash" , ipfs_hash_base58 ) metadata . save_pretty ( s... | Publish protobuf model in ipfs and update existing metadata file |
231,819 | def _get_persistent_mpe_dir ( self ) : mpe_address = self . get_mpe_address ( ) . lower ( ) registry_address = self . get_registry_address ( ) . lower ( ) return Path . home ( ) . joinpath ( ".snet" , "mpe_client" , "%s_%s" % ( mpe_address , registry_address ) ) | get persistent storage for mpe |
231,820 | def _check_mpe_address_metadata ( self , metadata ) : mpe_address = self . get_mpe_address ( ) if ( str ( mpe_address ) . lower ( ) != str ( metadata [ "mpe_address" ] ) . lower ( ) ) : raise Exception ( "MultiPartyEscrow contract address from metadata %s do not correspond to current MultiPartyEscrow address %s" % ( me... | we make sure that MultiPartyEscrow address from metadata is correct |
231,821 | def _init_or_update_registered_service_if_needed ( self ) : if ( self . is_service_initialized ( ) ) : old_reg = self . _read_service_info ( self . args . org_id , self . args . service_id ) if ( "metadataURI" not in old_reg ) : return service_registration = self . _get_service_registration ( ) if ( not self . is_metad... | similar to _init_or_update_service_if_needed but we get service_registraion from registry so we can update only registered services |
231,822 | def _smart_get_initialized_channel_for_service ( self , metadata , filter_by , is_try_initailize = True ) : channels = self . _get_initialized_channels_for_service ( self . args . org_id , self . args . service_id ) group_id = metadata . get_group_id ( self . args . group_name ) channels = [ c for c in channels if c [ ... | - filter_by can be sender or signer |
231,823 | def _get_all_filtered_channels ( self , topics_without_signature ) : mpe_address = self . get_mpe_address ( ) event_signature = self . ident . w3 . sha3 ( text = "ChannelOpen(uint256,uint256,address,address,address,bytes32,uint256,uint256)" ) . hex ( ) topics = [ event_signature ] + topics_without_signature logs = self... | get all filtered chanels from blockchain logs |
231,824 | def list_repo ( self ) : req = proto . ListRepoRequest ( ) res = self . stub . ListRepo ( req , metadata = self . metadata ) if hasattr ( res , 'repo_info' ) : return res . repo_info return [ ] | Returns info about all Repos . |
231,825 | def delete_repo ( self , repo_name = None , force = False , all = False ) : if not all : if repo_name : req = proto . DeleteRepoRequest ( repo = proto . Repo ( name = repo_name ) , force = force ) self . stub . DeleteRepo ( req , metadata = self . metadata ) else : raise ValueError ( "Either a repo_name or all=True nee... | Deletes a repo and reclaims the storage space it was using . |
231,826 | def start_commit ( self , repo_name , branch = None , parent = None , description = None ) : req = proto . StartCommitRequest ( parent = proto . Commit ( repo = proto . Repo ( name = repo_name ) , id = parent ) , branch = branch , description = description ) res = self . stub . StartCommit ( req , metadata = self . met... | Begins the process of committing data to a Repo . Once started you can write to the Commit with PutFile and when all the data has been written you must finish the Commit with FinishCommit . NOTE data is not persisted until FinishCommit is called . A Commit object is returned . |
231,827 | def finish_commit ( self , commit ) : req = proto . FinishCommitRequest ( commit = commit_from ( commit ) ) res = self . stub . FinishCommit ( req , metadata = self . metadata ) return res | Ends the process of committing data to a Repo and persists the Commit . Once a Commit is finished the data becomes immutable and future attempts to write to it with PutFile will error . |
231,828 | def commit ( self , repo_name , branch = None , parent = None , description = None ) : commit = self . start_commit ( repo_name , branch , parent , description ) try : yield commit except Exception as e : print ( "An exception occurred during an open commit. " "Trying to finish it (Currently a commit can't be cancelled... | A context manager for doing stuff inside a commit . |
231,829 | def inspect_commit ( self , commit ) : req = proto . InspectCommitRequest ( commit = commit_from ( commit ) ) return self . stub . InspectCommit ( req , metadata = self . metadata ) | Returns info about a specific Commit . |
231,830 | def list_commit ( self , repo_name , to_commit = None , from_commit = None , number = 0 ) : req = proto . ListCommitRequest ( repo = proto . Repo ( name = repo_name ) , number = number ) if to_commit is not None : req . to . CopyFrom ( commit_from ( to_commit ) ) if from_commit is not None : getattr ( req , 'from' ) . ... | Gets a list of CommitInfo objects . |
231,831 | def delete_commit ( self , commit ) : req = proto . DeleteCommitRequest ( commit = commit_from ( commit ) ) self . stub . DeleteCommit ( req , metadata = self . metadata ) | Deletes a commit . |
231,832 | def flush_commit ( self , commits , repos = tuple ( ) ) : req = proto . FlushCommitRequest ( commit = [ commit_from ( c ) for c in commits ] , to_repo = [ proto . Repo ( name = r ) for r in repos ] ) res = self . stub . FlushCommit ( req , metadata = self . metadata ) return res | Blocks until all of the commits which have a set of commits as provenance have finished . For commits to be considered they must have all of the specified commits as provenance . This in effect waits for all of the jobs that are triggered by a set of commits to complete . It returns an error if any of the commits it s ... |
231,833 | def subscribe_commit ( self , repo_name , branch , from_commit_id = None ) : repo = proto . Repo ( name = repo_name ) req = proto . SubscribeCommitRequest ( repo = repo , branch = branch ) if from_commit_id is not None : getattr ( req , 'from' ) . CopyFrom ( proto . Commit ( repo = repo , id = from_commit_id ) ) res = ... | SubscribeCommit is like ListCommit but it keeps listening for commits as they come in . This returns an iterator Commit objects . |
231,834 | def list_branch ( self , repo_name ) : req = proto . ListBranchRequest ( repo = proto . Repo ( name = repo_name ) ) res = self . stub . ListBranch ( req , metadata = self . metadata ) if hasattr ( res , 'branch_info' ) : return res . branch_info return [ ] | Lists the active Branch objects on a Repo . |
231,835 | def set_branch ( self , commit , branch_name ) : res = proto . SetBranchRequest ( commit = commit_from ( commit ) , branch = branch_name ) self . stub . SetBranch ( res , metadata = self . metadata ) | Sets a commit and its ancestors as a branch . |
231,836 | def delete_branch ( self , repo_name , branch_name ) : res = proto . DeleteBranchRequest ( repo = Repo ( name = repo_name ) , branch = branch_name ) self . stub . DeleteBranch ( res , metadata = self . metadata ) | Deletes a branch but leaves the commits themselves intact . In other words those commits can still be accessed via commit IDs and other branches they happen to be on . |
231,837 | def put_file_url ( self , commit , path , url , recursive = False ) : req = iter ( [ proto . PutFileRequest ( file = proto . File ( commit = commit_from ( commit ) , path = path ) , url = url , recursive = recursive ) ] ) self . stub . PutFile ( req , metadata = self . metadata ) | Puts a file using the content found at a URL . The URL is sent to the server which performs the request . |
231,838 | def get_file ( self , commit , path , offset_bytes = 0 , size_bytes = 0 , extract_value = True ) : req = proto . GetFileRequest ( file = proto . File ( commit = commit_from ( commit ) , path = path ) , offset_bytes = offset_bytes , size_bytes = size_bytes ) res = self . stub . GetFile ( req , metadata = self . metadata... | Returns an iterator of the contents contents of a file at a specific Commit . |
231,839 | def get_files ( self , commit , paths , recursive = False ) : filtered_file_infos = [ ] for path in paths : fi = self . inspect_file ( commit , path ) if fi . file_type == proto . FILE : filtered_file_infos . append ( fi ) else : filtered_file_infos += self . list_file ( commit , path , recursive = recursive ) filtered... | Returns the contents of a list of files at a specific Commit as a dictionary of file paths to data . |
231,840 | def inspect_file ( self , commit , path ) : req = proto . InspectFileRequest ( file = proto . File ( commit = commit_from ( commit ) , path = path ) ) res = self . stub . InspectFile ( req , metadata = self . metadata ) return res | Returns info about a specific file . |
231,841 | def list_file ( self , commit , path , recursive = False ) : req = proto . ListFileRequest ( file = proto . File ( commit = commit_from ( commit ) , path = path ) ) res = self . stub . ListFile ( req , metadata = self . metadata ) file_infos = res . file_info if recursive : dirs = [ f for f in file_infos if f . file_ty... | Lists the files in a directory . |
231,842 | def delete_file ( self , commit , path ) : req = proto . DeleteFileRequest ( file = proto . File ( commit = commit_from ( commit ) , path = path ) ) self . stub . DeleteFile ( req , metadata = self . metadata ) | Deletes a file from a Commit . DeleteFile leaves a tombstone in the Commit assuming the file isn t written to later attempting to get the file from the finished commit will result in not found error . The file will of course remain intact in the Commit s parent . |
231,843 | def handle_authn_request ( self , context , binding_in ) : return self . _handle_authn_request ( context , binding_in , self . idp ) | This method is bound to the starting endpoint of the authentication . |
231,844 | def _create_state_data ( self , context , resp_args , relay_state ) : if "name_id_policy" in resp_args and resp_args [ "name_id_policy" ] is not None : resp_args [ "name_id_policy" ] = resp_args [ "name_id_policy" ] . to_string ( ) . decode ( "utf-8" ) return { "resp_args" : resp_args , "relay_state" : relay_state } | Returns a dict containing the state needed in the response flow . |
231,845 | def _handle_authn_request ( self , context , binding_in , idp ) : req_info = idp . parse_authn_request ( context . request [ "SAMLRequest" ] , binding_in ) authn_req = req_info . message satosa_logging ( logger , logging . DEBUG , "%s" % authn_req , context . state ) try : resp_args = idp . response_args ( authn_req ) ... | See doc for handle_authn_request method . |
231,846 | def _get_approved_attributes ( self , idp , idp_policy , sp_entity_id , state ) : name_format = idp_policy . get_name_form ( sp_entity_id ) attrconvs = idp . config . attribute_converters idp_policy . acs = attrconvs attribute_filter = [ ] for aconv in attrconvs : if aconv . name_format == name_format : all_attributes ... | Returns a list of approved attributes |
231,847 | def _build_idp_config_endpoints ( self , config , providers ) : idp_endpoints = [ ] for endp_category in self . endpoints : for func , endpoint in self . endpoints [ endp_category ] . items ( ) : for provider in providers : _endpoint = "{base}/{provider}/{endpoint}" . format ( base = self . base_url , provider = provid... | Builds the final frontend module config |
231,848 | def _load_endpoints_to_config ( self , provider , target_entity_id , config = None ) : idp_conf = copy . deepcopy ( config or self . idp_config ) for service , endpoint in self . endpoints . items ( ) : idp_endpoints = [ ] for binding , path in endpoint . items ( ) : url = "{base}/{provider}/{target_id}/{path}" . forma... | Loads approved endpoints to the config . |
231,849 | def _load_idp_dynamic_entity_id ( self , state ) : idp_config_file = copy . deepcopy ( self . idp_config ) idp_config_file [ "entityid" ] = "{}/{}" . format ( self . idp_config [ "entityid" ] , state [ self . name ] [ "target_entity_id" ] ) idp_config = IdPConfig ( ) . load ( idp_config_file , metadata_construction = F... | Loads an idp server with the entity id saved in state |
231,850 | def _get_co_name_from_path ( self , context ) : url_encoded_co_name = context . path . split ( "/" ) [ 1 ] co_name = unquote_plus ( url_encoded_co_name ) return co_name | The CO name is URL encoded and obtained from the request path for a request coming into one of the standard binding endpoints . For example the HTTP - Redirect binding request path will have the format |
231,851 | def _get_co_name ( self , context ) : try : co_name = context . state [ self . name ] [ self . KEY_CO_NAME ] logger . debug ( "Found CO {} from state" . format ( co_name ) ) except KeyError : co_name = self . _get_co_name_from_path ( context ) logger . debug ( "Found CO {} from request path" . format ( co_name ) ) retu... | Obtain the CO name previously saved in the request state or if not set use the request path obtained from the current context to determine the target CO . |
231,852 | def _add_endpoints_to_config ( self , config , co_name , backend_name ) : for service , endpoint in self . endpoints . items ( ) : idp_endpoints = [ ] for binding , path in endpoint . items ( ) : url = "{base}/{backend}/{co_name}/{path}" . format ( base = self . base_url , backend = backend_name , co_name = quote_plus ... | Use the request path from the context to determine the target backend then construct mappings from bindings to endpoints for the virtual IdP for the CO . |
231,853 | def _add_entity_id ( self , config , co_name ) : base_entity_id = config [ 'entityid' ] co_entity_id = "{}/{}" . format ( base_entity_id , quote_plus ( co_name ) ) config [ 'entityid' ] = co_entity_id return config | Use the CO name to construct the entity ID for the virtual IdP for the CO . |
231,854 | def _overlay_for_saml_metadata ( self , config , co_name ) : for co in self . config [ self . KEY_CO ] : if co [ self . KEY_ENCODEABLE_NAME ] == co_name : break key = self . KEY_ORGANIZATION if key in co : if key not in config : config [ key ] = { } for org_key in self . KEY_ORGANIZATION_KEYS : if org_key in co [ key ]... | Overlay configuration details like organization and contact person from the front end configuration onto the IdP configuration to support SAML metadata generation . |
231,855 | def _co_names_from_config ( self ) : co_names = [ co [ self . KEY_ENCODEABLE_NAME ] for co in self . config [ self . KEY_CO ] ] return co_names | Parse the configuration for the names of the COs for which to construct virtual IdPs . |
231,856 | def _create_co_virtual_idp ( self , context ) : co_name = self . _get_co_name ( context ) context . decorate ( self . KEY_CO_NAME , co_name ) co_names = self . _co_names_from_config ( ) if co_name not in co_names : msg = "CO {} not in configured list of COs {}" . format ( co_name , co_names ) satosa_logging ( logger , ... | Create a virtual IdP to represent the CO . |
231,857 | def _authn_response ( self , context ) : state_data = context . state [ self . name ] aresp = self . consumer . parse_response ( AuthorizationResponse , info = json . dumps ( context . request ) ) self . _verify_state ( aresp , state_data , context . state ) rargs = { "code" : aresp [ "code" ] , "redirect_uri" : self .... | Handles the authentication response from the AS . |
231,858 | def hash_data ( salt , value , hash_alg = None ) : hash_alg = hash_alg or 'sha512' hasher = hashlib . new ( hash_alg ) hasher . update ( value . encode ( 'utf-8' ) ) hasher . update ( salt . encode ( 'utf-8' ) ) value_hashed = hasher . hexdigest ( ) return value_hashed | Hashes a value together with a salt with the given hash algorithm . |
231,859 | def _construct_filter_value ( self , candidate , data ) : context = self . context attributes = data . attributes satosa_logging ( logger , logging . DEBUG , "Input attributes {}" . format ( attributes ) , context . state ) values = [ ] for identifier_name in candidate [ 'attribute_names' ] : v = attributes . get ( ide... | Construct and return a LDAP directory search filter value from the candidate identifier . |
231,860 | def _filter_config ( self , config , fields = None ) : filter_fields_default = [ 'bind_password' , 'connection' ] filter_fields = fields or filter_fields_default return dict ( map ( lambda key : ( key , '<hidden>' if key in filter_fields else config [ key ] ) , config . keys ( ) ) ) | Filter sensitive details like passwords from a configuration dictionary . |
231,861 | def _ldap_connection_factory ( self , config ) : ldap_url = config [ 'ldap_url' ] bind_dn = config [ 'bind_dn' ] bind_password = config [ 'bind_password' ] if not ldap_url : raise LdapAttributeStoreError ( "ldap_url is not configured" ) if not bind_dn : raise LdapAttributeStoreError ( "bind_dn is not configured" ) if n... | Use the input configuration to instantiate and return a ldap3 Connection object . |
231,862 | def _populate_attributes ( self , config , record , context , data ) : search_return_attributes = config [ 'search_return_attributes' ] for attr in search_return_attributes . keys ( ) : if attr in record [ "attributes" ] : if record [ "attributes" ] [ attr ] : data . attributes [ search_return_attributes [ attr ] ] = r... | Use a record found in LDAP to populate attributes . |
231,863 | def _populate_input_for_name_id ( self , config , record , context , data ) : user_id = "" user_id_from_attrs = config [ 'user_id_from_attrs' ] for attr in user_id_from_attrs : if attr in record [ "attributes" ] : value = record [ "attributes" ] [ attr ] if isinstance ( value , list ) : value . sort ( ) user_id += "" .... | Use a record found in LDAP to populate input for NameID generation . |
231,864 | def _verify_dict ( self , conf ) : if not conf : raise SATOSAConfigurationError ( "Missing configuration or unknown format" ) for key in SATOSAConfig . mandatory_dict_keys : if key not in conf : raise SATOSAConfigurationError ( "Missing key '%s' in config" % key ) for key in SATOSAConfig . sensitive_dict_keys : if key ... | Check that the configuration contains all necessary keys . |
231,865 | def _load_yaml ( self , config_file ) : try : with open ( config_file ) as f : return yaml . safe_load ( f . read ( ) ) except yaml . YAMLError as exc : logger . error ( "Could not parse config as YAML: {}" , str ( exc ) ) if hasattr ( exc , 'problem_mark' ) : mark = exc . problem_mark logger . error ( "Error position:... | Load config from yaml file or string |
231,866 | def satosa_logging ( logger , level , message , state , ** kwargs ) : if state is None : session_id = "UNKNOWN" else : try : session_id = state [ LOGGER_STATE_KEY ] except KeyError : session_id = uuid4 ( ) . urn state [ LOGGER_STATE_KEY ] = session_id logger . log ( level , "[{id}] {msg}" . format ( id = session_id , m... | Adds a session ID to the message . |
231,867 | def process ( self , context , internal_response ) : consent_state = context . state [ STATE_KEY ] internal_response . attributes = self . _filter_attributes ( internal_response . attributes , consent_state [ "filter" ] ) id_hash = self . _get_consent_id ( internal_response . requester , internal_response . subject_id ... | Manage consent and attribute filtering |
231,868 | def _get_consent_id ( self , requester , user_id , filtered_attr ) : filtered_attr_key_list = sorted ( filtered_attr . keys ( ) ) hash_str = "" for key in filtered_attr_key_list : _hash_value = "" . join ( sorted ( filtered_attr [ key ] ) ) hash_str += key + _hash_value id_string = "%s%s%s" % ( requester , user_id , ha... | Get a hashed id based on requester user id and filtered attributes |
231,869 | def _consent_registration ( self , consent_args ) : jws = JWS ( json . dumps ( consent_args ) , alg = self . signing_key . alg ) . sign_compact ( [ self . signing_key ] ) request = "{}/creq/{}" . format ( self . api_url , jws ) res = requests . get ( request ) if res . status_code != 200 : raise UnexpectedResponseError... | Register a request at the consent service |
231,870 | def _verify_consent ( self , consent_id ) : request = "{}/verify/{}" . format ( self . api_url , consent_id ) res = requests . get ( request ) if res . status_code == 200 : return json . loads ( res . text ) return None | Connects to the consent service using the REST api and checks if the user has given consent |
231,871 | def _end_consent ( self , context , internal_response ) : del context . state [ STATE_KEY ] return super ( ) . process ( context , internal_response ) | Clear the state for consent and end the consent step |
231,872 | def constructPrimaryIdentifier ( self , data , ordered_identifier_candidates ) : logprefix = PrimaryIdentifier . logprefix context = self . context attributes = data . attributes satosa_logging ( logger , logging . DEBUG , "{} Input attributes {}" . format ( logprefix , attributes ) , context . state ) value = None for... | Construct and return a primary identifier value from the data asserted by the IdP using the ordered list of candidates from the configuration . |
231,873 | def state_to_cookie ( state , name , path , encryption_key ) : cookie_data = "" if state . delete else state . urlstate ( encryption_key ) max_age = 0 if state . delete else STATE_COOKIE_MAX_AGE satosa_logging ( logger , logging . DEBUG , "Saving state as cookie, secure: %s, max-age: %s, path: %s" % ( STATE_COOKIE_SECU... | Saves a state to a cookie |
231,874 | def cookie_to_state ( cookie_str , name , encryption_key ) : try : cookie = SimpleCookie ( cookie_str ) state = State ( cookie [ name ] . value , encryption_key ) except KeyError as e : msg_tmpl = 'No cookie named {name} in {data}' msg = msg_tmpl . format ( name = name , data = cookie_str ) logger . exception ( msg ) r... | Loads a state from a cookie |
231,875 | def encrypt ( self , raw ) : raw = self . _pad ( raw ) iv = Random . new ( ) . read ( AES . block_size ) cipher = AES . new ( self . key , AES . MODE_CBC , iv ) return base64 . urlsafe_b64encode ( iv + cipher . encrypt ( raw ) ) | Encryptes the parameter raw . |
231,876 | def _pad ( self , b ) : return b + ( self . bs - len ( b ) % self . bs ) * chr ( self . bs - len ( b ) % self . bs ) . encode ( "UTF-8" ) | Will padd the param to be of the correct length for the encryption alg . |
231,877 | def urlstate ( self , encryption_key ) : lzma = LZMACompressor ( ) urlstate_data = json . dumps ( self . _state_dict ) urlstate_data = lzma . compress ( urlstate_data . encode ( "UTF-8" ) ) urlstate_data += lzma . flush ( ) urlstate_data = _AESCipher ( encryption_key ) . encrypt ( urlstate_data ) lzma = LZMACompressor ... | Will return a url safe representation of the state . |
231,878 | def copy ( self ) : state_copy = State ( ) state_copy . _state_dict = copy . deepcopy ( self . _state_dict ) return state_copy | Returns a deepcopy of the state |
231,879 | def saml_name_id_format_to_hash_type ( name_format ) : msg = "saml_name_id_format_to_hash_type is deprecated and will be removed." _warnings . warn ( msg , DeprecationWarning ) name_id_format_to_hash_type = { NAMEID_FORMAT_TRANSIENT : UserIdHashType . transient , NAMEID_FORMAT_PERSISTENT : UserIdHashType . persistent ,... | Translate pySAML2 name format to satosa format |
231,880 | def hash_type_to_saml_name_id_format ( hash_type ) : msg = "hash_type_to_saml_name_id_format is deprecated and will be removed." _warnings . warn ( msg , DeprecationWarning ) hash_type_to_name_id_format = { UserIdHashType . transient : NAMEID_FORMAT_TRANSIENT , UserIdHashType . persistent : NAMEID_FORMAT_PERSISTENT , U... | Translate satosa format to pySAML2 name format |
231,881 | def save_state ( internal_request , state ) : state_data = { "hash_type" : internal_request . user_id_hash_type } state [ UserIdHasher . STATE_KEY ] = state_data | Saves all necessary information needed by the UserIdHasher |
231,882 | def hash_id ( salt , user_id , requester , state ) : hash_type_to_format = { NAMEID_FORMAT_TRANSIENT : "{id}{req}{time}" , NAMEID_FORMAT_PERSISTENT : "{id}{req}" , "pairwise" : "{id}{req}" , "public" : "{id}" , NAMEID_FORMAT_EMAILADDRESS : "{id}" , NAMEID_FORMAT_UNSPECIFIED : "{id}" , } format_args = { "id" : user_id ,... | Sets a user id to the internal_response in the format specified by the internal response |
231,883 | def load_backends ( config , callback , internal_attributes ) : backend_modules = _load_plugins ( config . get ( "CUSTOM_PLUGIN_MODULE_PATHS" ) , config [ "BACKEND_MODULES" ] , backend_filter , config [ "BASE" ] , internal_attributes , callback ) logger . info ( "Setup backends: %s" % [ backend . name for backend in ba... | Load all backend modules specified in the config |
231,884 | def load_frontends ( config , callback , internal_attributes ) : frontend_modules = _load_plugins ( config . get ( "CUSTOM_PLUGIN_MODULE_PATHS" ) , config [ "FRONTEND_MODULES" ] , frontend_filter , config [ "BASE" ] , internal_attributes , callback ) logger . info ( "Setup frontends: %s" % [ frontend . name for fronten... | Load all frontend modules specified in the config |
231,885 | def _micro_service_filter ( cls ) : is_microservice_module = issubclass ( cls , MicroService ) is_correct_subclass = cls != MicroService and cls != ResponseMicroService and cls != RequestMicroService return is_microservice_module and is_correct_subclass | Will only give a find on classes that is a subclass of MicroService with the exception that the class is not allowed to be a direct ResponseMicroService or RequestMicroService . |
231,886 | def _load_plugins ( plugin_paths , plugins , plugin_filter , base_url , internal_attributes , callback ) : loaded_plugin_modules = [ ] with prepend_to_import_path ( plugin_paths ) : for plugin_config in plugins : try : module_class = _load_endpoint_module ( plugin_config , plugin_filter ) except SATOSAConfigurationErro... | Loads endpoint plugins |
231,887 | def create_and_write_saml_metadata ( proxy_conf , key , cert , dir , valid , split_frontend_metadata = False , split_backend_metadata = False ) : satosa_config = SATOSAConfig ( proxy_conf ) secc = _get_security_context ( key , cert ) frontend_entities , backend_entities = create_entity_descriptors ( satosa_config ) out... | Generates SAML metadata for the given PROXY_CONF signed with the given KEY and associated CERT . |
231,888 | def _handle_al_response ( self , context ) : saved_state = context . state [ self . name ] internal_response = InternalData . from_dict ( saved_state ) status_code , message = self . _get_uuid ( context , internal_response . auth_info . issuer , internal_response . attributes [ 'issuer_user_id' ] ) if status_code == 20... | Endpoint for handling account linking service response . When getting here user might have approved or rejected linking their account |
231,889 | def process ( self , context , internal_response ) : status_code , message = self . _get_uuid ( context , internal_response . auth_info . issuer , internal_response . subject_id ) data = { "issuer" : internal_response . auth_info . issuer , "redirect_endpoint" : "%s/account_linking%s" % ( self . base_url , self . endpo... | Manage account linking and recovery |
231,890 | def backend_routing ( self , context ) : satosa_logging ( logger , logging . DEBUG , "Routing to backend: %s " % context . target_backend , context . state ) backend = self . backends [ context . target_backend ] [ "instance" ] context . state [ STATE_KEY ] = context . target_frontend return backend | Returns the targeted backend and an updated state |
231,891 | def frontend_routing ( self , context ) : target_frontend = context . state [ STATE_KEY ] satosa_logging ( logger , logging . DEBUG , "Routing to frontend: %s " % target_frontend , context . state ) context . target_frontend = target_frontend frontend = self . frontends [ context . target_frontend ] [ "instance" ] retu... | Returns the targeted frontend and original state |
231,892 | def endpoint_routing ( self , context ) : if context . path is None : satosa_logging ( logger , logging . DEBUG , "Context did not contain a path!" , context . state ) raise SATOSABadContextError ( "Context did not contain any path" ) satosa_logging ( logger , logging . DEBUG , "Routing path: %s" % context . path , con... | Finds and returns the endpoint function bound to the path |
231,893 | def _auth_req_callback_func ( self , context , internal_request ) : state = context . state state [ STATE_KEY ] = { "requester" : internal_request . requester } try : state_dict = context . state [ consent . STATE_KEY ] except KeyError : state_dict = context . state [ consent . STATE_KEY ] = { } finally : state_dict . ... | This function is called by a frontend module when an authorization request has been processed . |
231,894 | def _auth_resp_callback_func ( self , context , internal_response ) : context . request = None internal_response . requester = context . state [ STATE_KEY ] [ "requester" ] if "user_id_from_attrs" in self . config [ "INTERNAL_ATTRIBUTES" ] : subject_id = [ "" . join ( internal_response . attributes [ attr ] ) for attr ... | This function is called by a backend module when the authorization is complete . |
231,895 | def _handle_satosa_authentication_error ( self , error ) : context = Context ( ) context . state = error . state frontend = self . module_router . frontend_routing ( context ) return frontend . handle_backend_error ( error ) | Sends a response to the requester about the error |
231,896 | def _load_state ( self , context ) : try : state = cookie_to_state ( context . cookie , self . config [ "COOKIE_STATE_NAME" ] , self . config [ "STATE_ENCRYPTION_KEY" ] ) except SATOSAStateError as e : msg_tmpl = 'Failed to decrypt state {state} with {error}' msg = msg_tmpl . format ( state = context . cookie , error =... | Load state from cookie to the context |
231,897 | def _save_state ( self , resp , context ) : cookie = state_to_cookie ( context . state , self . config [ "COOKIE_STATE_NAME" ] , "/" , self . config [ "STATE_ENCRYPTION_KEY" ] ) resp . headers . append ( tuple ( cookie . output ( ) . split ( ": " , 1 ) ) ) | Saves a state from context to cookie |
231,898 | def run ( self , context ) : try : self . _load_state ( context ) spec = self . module_router . endpoint_routing ( context ) resp = self . _run_bound_endpoint ( context , spec ) self . _save_state ( resp , context ) except SATOSANoBoundEndpointError : raise except SATOSAError : satosa_logging ( logger , logging . ERROR... | Runs the satosa proxy with the given context . |
231,899 | def disco_query ( self ) : return_url = self . sp . config . getattr ( "endpoints" , "sp" ) [ "discovery_response" ] [ 0 ] [ 0 ] loc = self . sp . create_discovery_service_request ( self . discosrv , self . sp . config . entityid , ** { "return" : return_url } ) return SeeOther ( loc ) | Makes a request to the discovery server |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.