idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
249,400
def getManager ( self , force = False ) : manager = self . session . get ( self . getSessionKey ( ) ) if ( manager is not None and ( manager . forURL ( self . url ) or force ) ) : return manager else : return None
Extract the YadisServiceManager for this object s URL and suffix from the session .
249,401
def createManager ( self , services , yadis_url = None ) : key = self . getSessionKey ( ) if self . getManager ( ) : raise KeyError ( 'There is already a %r manager for %r' % ( key , self . url ) ) if not services : return None manager = YadisServiceManager ( self . url , yadis_url , services , key ) manager . store ( ...
Create a new YadisService Manager for this starting URL and suffix and store it in the session .
249,402
def destroyManager ( self , force = False ) : if self . getManager ( force = force ) is not None : key = self . getSessionKey ( ) del self . session [ key ]
Delete any YadisServiceManager with this starting URL and suffix from the session .
249,403
def _setPrivate ( self , private ) : self . private = private self . public = pow ( self . generator , self . private , self . modulus )
This is here to make testing easier
249,404
def answerUnsupported ( self , message , preferred_association_type = None , preferred_session_type = None ) : if self . message . isOpenID1 ( ) : raise ProtocolError ( self . message ) response = OpenIDResponse ( self ) response . fields . setArg ( OPENID_NS , 'error_code' , 'unsupported-type' ) response . fields . se...
Respond to this request indicating that the association type or association session type is not supported .
249,405
def fromMessage ( klass , message , op_endpoint ) : self = klass . __new__ ( klass ) self . message = message self . op_endpoint = op_endpoint mode = message . getArg ( OPENID_NS , 'mode' ) if mode == "checkid_immediate" : self . immediate = True self . mode = "checkid_immediate" else : self . immediate = False self . ...
Construct me from an OpenID message .
249,406
def trustRootValid ( self ) : if not self . trust_root : return True tr = TrustRoot . parse ( self . trust_root ) if tr is None : raise MalformedTrustRoot ( self . message , self . trust_root ) if self . return_to is not None : return tr . validateURL ( self . return_to ) else : return True
Is my return_to under my trust_root?
249,407
def encodeToURL ( self , server_url ) : if not self . return_to : raise NoReturnToError q = { 'mode' : self . mode , 'identity' : self . identity , 'claimed_id' : self . claimed_id , 'return_to' : self . return_to } if self . trust_root : if self . message . isOpenID1 ( ) : q [ 'trust_root' ] = self . trust_root else :...
Encode this request as a URL to GET .
249,408
def getCancelURL ( self ) : if not self . return_to : raise NoReturnToError if self . immediate : raise ValueError ( "Cancel is not an appropriate response to " "immediate mode requests." ) response = Message ( self . message . getOpenIDNamespace ( ) ) response . setArg ( OPENID_NS , 'mode' , 'cancel' ) return response...
Get the URL to cancel this request .
249,409
def toFormMarkup ( self , form_tag_attrs = None ) : return self . fields . toFormMarkup ( self . request . return_to , form_tag_attrs = form_tag_attrs )
Returns the form markup for this response .
249,410
def verify ( self , assoc_handle , message ) : assoc = self . getAssociation ( assoc_handle , dumb = True ) if not assoc : logging . error ( "failed to get assoc with handle %r to verify " "message %r" % ( assoc_handle , message ) ) return False try : valid = assoc . checkMessageSignature ( message ) except ValueError ...
Verify that the signature for some data is valid .
249,411
def sign ( self , response ) : signed_response = deepcopy ( response ) assoc_handle = response . request . assoc_handle if assoc_handle : assoc = self . getAssociation ( assoc_handle , dumb = False , checkExpiration = False ) if not assoc or assoc . expiresIn <= 0 : signed_response . fields . setArg ( OPENID_NS , 'inva...
Sign a response .
249,412
def createAssociation ( self , dumb = True , assoc_type = 'HMAC-SHA1' ) : secret = cryptutil . getBytes ( getSecretSize ( assoc_type ) ) uniq = oidutil . toBase64 ( cryptutil . getBytes ( 4 ) ) handle = '{%s}{%x}{%s}' % ( assoc_type , int ( time . time ( ) ) , uniq ) assoc = Association . fromExpiresIn ( self . SECRET_...
Make a new association .
249,413
def getAssociation ( self , assoc_handle , dumb , checkExpiration = True ) : if assoc_handle is None : raise ValueError ( "assoc_handle must not be None" ) if dumb : key = self . _dumb_key else : key = self . _normal_key assoc = self . store . getAssociation ( key , assoc_handle ) if assoc is not None and assoc . expir...
Get the association with the specified handle .
249,414
def invalidate ( self , assoc_handle , dumb ) : if dumb : key = self . _dumb_key else : key = self . _normal_key self . store . removeAssociation ( key , assoc_handle )
Invalidates the association with the given handle .
249,415
def defaultDecoder ( self , message , server ) : mode = message . getArg ( OPENID_NS , 'mode' ) fmt = "Unrecognized OpenID mode %r" raise ProtocolError ( message , text = fmt % ( mode , ) )
Called to decode queries when no handler for that mode is found .
249,416
def toMessage ( self ) : namespace = self . openid_message . getOpenIDNamespace ( ) reply = Message ( namespace ) reply . setArg ( OPENID_NS , 'mode' , 'error' ) reply . setArg ( OPENID_NS , 'error' , str ( self ) ) if self . contact is not None : reply . setArg ( OPENID_NS , 'contact' , str ( self . contact ) ) if sel...
Generate a Message object for sending to the relying party after encoding .
249,417
def rpXRDS ( request ) : return util . renderXRDS ( request , [ RP_RETURN_TO_URL_TYPE ] , [ util . getViewURL ( request , finishOpenID ) ] )
Return a relying party verification XRDS document
249,418
def getSession ( self ) : if self . session is not None : return self . session cookie_str = self . headers . get ( 'Cookie' ) if cookie_str : cookie_obj = SimpleCookie ( cookie_str ) sid_morsel = cookie_obj . get ( self . SESSION_COOKIE_NAME , None ) if sid_morsel is not None : sid = sid_morsel . value else : sid = No...
Return the existing session or a new session
249,419
def doProcess ( self ) : oidconsumer = self . getConsumer ( ) url = 'http://' + self . headers . get ( 'Host' ) + self . path info = oidconsumer . complete ( self . query , url ) sreg_resp = None pape_resp = None css_class = 'error' display_identifier = info . getDisplayIdentifier ( ) if info . status == consumer . FAI...
Handle the redirect from the OpenID server .
249,420
def notFound ( self ) : fmt = 'The path <q>%s</q> was not understood by this server.' msg = fmt % ( self . path , ) openid_url = self . query . get ( 'openid_identifier' ) self . render ( msg , 'error' , openid_url , status = 404 )
Render a page with a 404 return code and a message .
249,421
def render ( self , message = None , css_class = 'alert' , form_contents = None , status = 200 , title = "Python OpenID Consumer Example" , sreg_data = None , pape_data = None ) : self . send_response ( status ) self . pageHeader ( title ) if message : self . wfile . write ( "<div class='%s'>" % ( css_class , ) ) self ...
Render a page .
249,422
def _callInTransaction ( self , func , * args , ** kwargs ) : self . conn . rollback ( ) try : self . cur = self . conn . cursor ( ) try : ret = func ( * args , ** kwargs ) finally : self . cur . close ( ) self . cur = None except : self . conn . rollback ( ) raise else : self . conn . commit ( ) return ret
Execute the given function inside of a transaction with an open cursor . If no exception is raised the transaction is comitted otherwise it is rolled back .
249,423
def txn_storeAssociation ( self , server_url , association ) : a = association self . db_set_assoc ( server_url , a . handle , self . blobEncode ( a . secret ) , a . issued , a . lifetime , a . assoc_type )
Set the association for the server URL .
249,424
def txn_removeAssociation ( self , server_url , handle ) : self . db_remove_assoc ( server_url , handle ) return self . cur . rowcount > 0
Remove the association for the given server URL and handle returning whether the association existed at all .
249,425
def txn_useNonce ( self , server_url , timestamp , salt ) : if abs ( timestamp - time . time ( ) ) > nonce . SKEW : return False try : self . db_add_nonce ( server_url , timestamp , salt ) except self . exceptions . IntegrityError : return False else : return True
Return whether this nonce is present and if it is then remove it from the set .
249,426
def _escape_xref ( xref_match ) : xref = xref_match . group ( ) xref = xref . replace ( '/' , '%2F' ) xref = xref . replace ( '?' , '%3F' ) xref = xref . replace ( '#' , '%23' ) return xref
Escape things that need to be escaped if they re in a cross - reference .
249,427
def escapeForIRI ( xri ) : xri = xri . replace ( '%' , '%25' ) xri = _xref_re . sub ( _escape_xref , xri ) return xri
Escape things that need to be escaped when transforming to an IRI .
249,428
def providerIsAuthoritative ( providerID , canonicalID ) : lastbang = canonicalID . rindex ( '!' ) parent = canonicalID [ : lastbang ] return parent == providerID
Is this provider ID authoritative for this XRI?
249,429
def rootAuthority ( xri ) : if xri . startswith ( 'xri://' ) : xri = xri [ 6 : ] authority = xri . split ( '/' , 1 ) [ 0 ] if authority [ 0 ] == '(' : root = authority [ : authority . index ( ')' ) + 1 ] elif authority [ 0 ] in XRI_AUTHORITIES : root = authority [ 0 ] else : segments = authority . split ( '!' ) segment...
Return the root authority for an XRI .
249,430
def toMessage ( self , message = None ) : if message is None : warnings . warn ( 'Passing None to Extension.toMessage is deprecated. ' 'Creating a message assuming you want OpenID 2.' , DeprecationWarning , stacklevel = 2 ) message = message_module . Message ( message_module . OPENID2_NS ) implicit = message . isOpenID...
Add the arguments from this extension to the provided message or create a new message containing only those arguments .
249,431
def _ensureDir ( dir_name ) : try : os . makedirs ( dir_name ) except OSError , why : if why . errno != EEXIST or not os . path . isdir ( dir_name ) : raise
Create dir_name as a directory if it does not exist . If it exists make sure that it is in fact a directory .
249,432
def _setup ( self ) : _ensureDir ( self . nonce_dir ) _ensureDir ( self . association_dir ) _ensureDir ( self . temp_dir )
Make sure that the directories in which we store our data exist .
249,433
def _mktemp ( self ) : fd , name = mkstemp ( dir = self . temp_dir ) try : file_obj = os . fdopen ( fd , 'wb' ) return file_obj , name except : _removeIfPresent ( name ) raise
Create a temporary file on the same filesystem as self . association_dir .
249,434
def getAssociationFilename ( self , server_url , handle ) : if server_url . find ( '://' ) == - 1 : raise ValueError ( 'Bad server URL: %r' % server_url ) proto , rest = server_url . split ( '://' , 1 ) domain = _filenameEscape ( rest . split ( '/' , 1 ) [ 0 ] ) url_hash = _safe64 ( server_url ) if handle : handle_hash...
Create a unique filename for a given server url and handle . This implementation does not assume anything about the format of the handle . The filename that is returned will contain the domain name from the server URL for ease of human inspection of the data directory .
249,435
def getAssociation ( self , server_url , handle = None ) : if handle is None : handle = '' filename = self . getAssociationFilename ( server_url , handle ) if handle : return self . _getAssociation ( filename ) else : association_files = os . listdir ( self . association_dir ) matching_files = [ ] name = os . path . ba...
Retrieve an association . If no handle is specified return the association with the latest expiration .
249,436
def removeAssociation ( self , server_url , handle ) : assoc = self . getAssociation ( server_url , handle ) if assoc is None : return 0 else : filename = self . getAssociationFilename ( server_url , handle ) return _removeIfPresent ( filename )
Remove an association if it exists . Do nothing if it does not .
249,437
def useNonce ( self , server_url , timestamp , salt ) : if abs ( timestamp - time . time ( ) ) > nonce . SKEW : return False if server_url : proto , rest = server_url . split ( '://' , 1 ) else : proto , rest = '' , '' domain = _filenameEscape ( rest . split ( '/' , 1 ) [ 0 ] ) url_hash = _safe64 ( server_url ) salt_ha...
Return whether this nonce is valid .
249,438
def arrangeByType ( service_list , preferred_types ) : def enumerate ( elts ) : return zip ( range ( len ( elts ) ) , elts ) def bestMatchingService ( service ) : for i , t in enumerate ( preferred_types ) : if preferred_types [ i ] in service . type_uris : return i return len ( preferred_types ) prio_services = [ ( be...
Rearrange service_list in a new list so services are ordered by types listed in preferred_types . Return the new list .
249,439
def getOPOrUserServices ( openid_services ) : op_services = arrangeByType ( openid_services , [ OPENID_IDP_2_0_TYPE ] ) openid_services = arrangeByType ( openid_services , OpenIDServiceEndpoint . openid_type_uris ) return op_services or openid_services
Extract OP Identifier services . If none found return the rest sorted with most preferred first according to OpenIDServiceEndpoint . openid_type_uris .
249,440
def supportsType ( self , type_uri ) : return ( ( type_uri in self . type_uris ) or ( type_uri == OPENID_2_0_TYPE and self . isOPIdentifier ( ) ) )
Does this endpoint support this type?
249,441
def parseService ( self , yadis_url , uri , type_uris , service_element ) : self . type_uris = type_uris self . server_url = uri self . used_yadis = True if not self . isOPIdentifier ( ) : self . local_id = findOPLocalIdentifier ( service_element , self . type_uris ) self . claimed_id = yadis_url
Set the state of this object based on the contents of the service element .
249,442
def getLocalID ( self ) : if ( self . local_id is self . canonicalID is None ) : return self . claimed_id else : return self . local_id or self . canonicalID
Return the identifier that should be sent as the openid . identity parameter to the server .
249,443
def fromBasicServiceEndpoint ( cls , endpoint ) : type_uris = endpoint . matchTypes ( cls . openid_type_uris ) if type_uris and endpoint . uri is not None : openid_endpoint = cls ( ) openid_endpoint . parseService ( endpoint . yadis_url , endpoint . uri , endpoint . type_uris , endpoint . service_element ) else : openi...
Create a new instance of this class from the endpoint object passed in .
249,444
def fromDiscoveryResult ( cls , discoveryResult ) : if discoveryResult . isXRDS ( ) : method = cls . fromXRDS else : method = cls . fromHTML return method ( discoveryResult . normalized_uri , discoveryResult . response_text )
Create endpoints from a DiscoveryResult .
249,445
def fromOPEndpointURL ( cls , op_endpoint_url ) : service = cls ( ) service . server_url = op_endpoint_url service . type_uris = [ OPENID_IDP_2_0_TYPE ] return service
Construct an OP - Identifier OpenIDServiceEndpoint object for a given OP Endpoint URL
249,446
def setAllowedTypes ( self , allowed_types ) : for ( assoc_type , session_type ) in allowed_types : checkSessionType ( assoc_type , session_type ) self . allowed_types = allowed_types
Set the allowed association types checking to make sure each combination is valid .
249,447
def isAllowed ( self , assoc_type , session_type ) : assoc_good = ( assoc_type , session_type ) in self . allowed_types matches = session_type in getSessionTypes ( assoc_type ) return assoc_good and matches
Is this combination of association type and session type allowed?
249,448
def serialize ( self ) : data = { 'version' : '2' , 'handle' : self . handle , 'secret' : oidutil . toBase64 ( self . secret ) , 'issued' : str ( int ( self . issued ) ) , 'lifetime' : str ( int ( self . lifetime ) ) , 'assoc_type' : self . assoc_type } assert len ( data ) == len ( self . assoc_keys ) pairs = [ ] for f...
Convert an association to KV form .
249,449
def getMessageSignature ( self , message ) : pairs = self . _makePairs ( message ) return oidutil . toBase64 ( self . sign ( pairs ) )
Return the signature of a message .
249,450
def checkMessageSignature ( self , message ) : message_sig = message . getArg ( OPENID_NS , 'sig' ) if not message_sig : raise ValueError ( "%s has no sig." % ( message , ) ) calculated_sig = self . getMessageSignature ( message ) return cryptutil . const_eq ( calculated_sig , message_sig )
Given a message with a signature calculate a new signature and return whether it matches the signature in the message .
249,451
def addPolicyURI ( self , policy_uri ) : if policy_uri not in self . preferred_auth_policies : self . preferred_auth_policies . append ( policy_uri )
Add an acceptable authentication policy URI to this request
249,452
def _addAuthLevelAlias ( self , auth_level_uri , alias = None ) : if alias is None : try : alias = self . _getAlias ( auth_level_uri ) except KeyError : alias = self . _generateAlias ( ) else : existing_uri = self . auth_level_aliases . get ( alias ) if existing_uri is not None and existing_uri != auth_level_uri : rais...
Add an auth level URI alias to this request .
249,453
def setAuthLevel ( self , level_uri , level , alias = None ) : self . _addAuthLevelAlias ( level_uri , alias ) self . auth_levels [ level_uri ] = level
Set the value for the given auth level type .
249,454
def discover ( uri ) : result = DiscoveryResult ( uri ) resp = fetchers . fetch ( uri , headers = { 'Accept' : YADIS_ACCEPT_HEADER } ) if resp . status not in ( 200 , 206 ) : raise DiscoveryFailure ( 'HTTP Response status from identity URL host is not 200. ' 'Got status %r' % ( resp . status , ) , resp ) result . norma...
Discover services for a given URI .
249,455
def whereIsYadis ( resp ) : content_type = resp . headers . get ( 'content-type' ) if ( content_type and content_type . split ( ';' , 1 ) [ 0 ] . lower ( ) == YADIS_CONTENT_TYPE ) : return resp . final_url else : yadis_loc = resp . headers . get ( YADIS_HEADER_NAME . lower ( ) ) if not yadis_loc : content_type = conten...
Given a HTTPResponse return the location of the Yadis document .
249,456
def endpoint ( request ) : s = getServer ( request ) query = util . normalDict ( request . GET or request . POST ) try : openid_request = s . decodeRequest ( query ) except ProtocolError , why : return direct_to_template ( request , 'server/endpoint.html' , { 'error' : str ( why ) } ) if openid_request is None : return...
Respond to low - level OpenID protocol messages .
249,457
def showDecidePage ( request , openid_request ) : trust_root = openid_request . trust_root return_to = openid_request . return_to try : trust_root_valid = verifyReturnTo ( trust_root , return_to ) and "Valid" or "Invalid" except DiscoveryFailure , err : trust_root_valid = "DISCOVERY_FAILED" except HTTPFetchingError , e...
Render a page to the user so a trust decision can be made .
249,458
def processTrustResult ( request ) : openid_request = getRequest ( request ) response_identity = getViewURL ( request , idPage ) allowed = 'allow' in request . POST openid_response = openid_request . answer ( allowed , identity = response_identity ) if allowed : sreg_data = { 'fullname' : 'Example User' , 'nickname' : ...
Handle the result of a trust decision and respond to the RP accordingly .
249,459
def buildDiscover ( base_url , out_dir ) : test_data = discoverdata . readTests ( discoverdata . default_test_file ) def writeTestFile ( test_name ) : template = test_data [ test_name ] data = discoverdata . fillTemplate ( test_name , template , base_url , discoverdata . example_xrds ) out_file_name = os . path . join ...
Convert all files in a directory to apache mod_asis files in another directory .
249,460
def best ( self ) : best = None for assoc in self . assocs . values ( ) : if best is None or best . issued < assoc . issued : best = assoc return best
Returns association with the oldest issued date .
249,461
def split ( nonce_string ) : timestamp_str = nonce_string [ : time_str_len ] try : timestamp = timegm ( strptime ( timestamp_str , time_fmt ) ) except AssertionError : timestamp = - 1 if timestamp < 0 : raise ValueError ( 'time out of range' ) return timestamp , nonce_string [ time_str_len : ]
Extract a timestamp from the given nonce string
249,462
def checkTimestamp ( nonce_string , allowed_skew = SKEW , now = None ) : try : stamp , _ = split ( nonce_string ) except ValueError : return False else : if now is None : now = time ( ) past = now - allowed_skew future = now + allowed_skew return past <= stamp <= future
Is the timestamp that is part of the specified nonce string within the allowed clock - skew of the current time?
249,463
def mkNonce ( when = None ) : salt = cryptutil . randomString ( 6 , NONCE_CHARS ) if when is None : t = gmtime ( ) else : t = gmtime ( when ) time_str = strftime ( time_fmt , t ) return time_str + salt
Generate a nonce with the current timestamp
249,464
def fetch ( url , body = None , headers = None ) : fetcher = getDefaultFetcher ( ) return fetcher . fetch ( url , body , headers )
Invoke the fetch method on the default fetcher . Most users should need only this method .
249,465
def setDefaultFetcher ( fetcher , wrap_exceptions = True ) : global _default_fetcher if fetcher is None or not wrap_exceptions : _default_fetcher = fetcher else : _default_fetcher = ExceptionWrappingFetcher ( fetcher )
Set the default fetcher
249,466
def usingCurl ( ) : fetcher = getDefaultFetcher ( ) if isinstance ( fetcher , ExceptionWrappingFetcher ) : fetcher = fetcher . fetcher return isinstance ( fetcher , CurlHTTPFetcher )
Whether the currently set HTTP fetcher is a Curl HTTP fetcher .
249,467
def fetch ( self , url , body = None , headers = None ) : if body : method = 'POST' else : method = 'GET' if headers is None : headers = { } if not ( url . startswith ( 'http://' ) or url . startswith ( 'https://' ) ) : raise ValueError ( 'URL is not a HTTP URL: %r' % ( url , ) ) httplib2_response , content = self . ht...
Perform an HTTP request
249,468
def getServiceEndpoints ( input_url , flt = None ) : result = discover ( input_url ) try : endpoints = applyFilter ( result . normalized_uri , result . response_text , flt ) except XRDSError , err : raise DiscoveryFailure ( str ( err ) , None ) return ( result . normalized_uri , endpoints )
Perform the Yadis protocol on the input URL and return an iterable of resulting endpoint objects .
249,469
def applyFilter ( normalized_uri , xrd_data , flt = None ) : flt = mkFilter ( flt ) et = parseXRDS ( xrd_data ) endpoints = [ ] for service_element in iterServices ( et ) : endpoints . extend ( flt . getServiceEndpoints ( normalized_uri , service_element ) ) return endpoints
Generate an iterable of endpoint objects given this input data presumably from the result of performing the Yadis protocol .
249,470
def parseLinkAttrs ( html ) : stripped = removed_re . sub ( '' , html ) html_mo = html_find . search ( stripped ) if html_mo is None or html_mo . start ( 'contents' ) == - 1 : return [ ] start , end = html_mo . span ( 'contents' ) head_mo = head_find . search ( stripped , start , end ) if head_mo is None or head_mo . s...
Find all link tags in a string representing a HTML document and return a list of their attributes .
249,471
def relMatches ( rel_attr , target_rel ) : rels = rel_attr . strip ( ) . split ( ) for rel in rels : rel = rel . lower ( ) if rel == target_rel : return 1 return 0
Does this target_rel appear in the rel_str?
249,472
def linkHasRel ( link_attrs , target_rel ) : rel_attr = link_attrs . get ( 'rel' ) return rel_attr and relMatches ( rel_attr , target_rel )
Does this link have target_rel as a relationship?
249,473
def findFirstHref ( link_attrs_list , target_rel ) : matches = findLinksRel ( link_attrs_list , target_rel ) if not matches : return None first = matches [ 0 ] return first . get ( 'href' )
Return the value of the href attribute for the first link tag in the list that has target_rel as a relationship .
249,474
def importElementTree ( module_names = None ) : if module_names is None : module_names = elementtree_modules for mod_name in module_names : try : ElementTree = __import__ ( mod_name , None , None , [ 'unused' ] ) except ImportError : pass else : try : ElementTree . XML ( '<unused/>' ) except ( SystemExit , MemoryError ...
Find a working ElementTree implementation trying the standard places that such a thing might show up .
249,475
def getYadisXRD ( xrd_tree ) : xrd = None for xrd in xrd_tree . findall ( xrd_tag ) : pass if xrd is None : raise XRDSError ( 'No XRD present in tree' ) return xrd
Return the XRD element that should contain the Yadis services
249,476
def getXRDExpiration ( xrd_element , default = None ) : expires_element = xrd_element . find ( expires_tag ) if expires_element is None : return default else : expires_string = expires_element . text expires_time = strptime ( expires_string , "%Y-%m-%dT%H:%M:%SZ" ) return datetime ( * expires_time [ 0 : 6 ] )
Return the expiration date of this XRD element or None if no expiration was specified .
249,477
def getCanonicalID ( iname , xrd_tree ) : xrd_list = xrd_tree . findall ( xrd_tag ) xrd_list . reverse ( ) try : canonicalID = xri . XRI ( xrd_list [ 0 ] . findall ( canonicalID_tag ) [ 0 ] . text ) except IndexError : return None childID = canonicalID . lower ( ) for xrd in xrd_list [ 1 : ] : parent_sought = childID [...
Return the CanonicalID from this XRDS document .
249,478
def getPriorityStrict ( element ) : prio_str = element . get ( 'priority' ) if prio_str is not None : prio_val = int ( prio_str ) if prio_val >= 0 : return prio_val else : raise ValueError ( 'Priority values must be non-negative integers' ) return Max
Get the priority of this element .
249,479
def makeKVPost ( request_message , server_url ) : resp = fetchers . fetch ( server_url , body = request_message . toURLEncoded ( ) ) return _httpResponseToMessage ( resp , server_url )
Make a Direct Request to an OpenID Provider and return the result as a Message object .
249,480
def _httpResponseToMessage ( response , server_url ) : response_message = Message . fromKVForm ( response . body ) if response . status == 400 : raise ServerError . fromMessage ( response_message ) elif response . status not in ( 200 , 206 ) : fmt = 'bad status code from server %s: %s' error_message = fmt % ( server_ur...
Adapt a POST response to a Message .
249,481
def complete ( self , query , current_url ) : endpoint = self . session . get ( self . _token_key ) message = Message . fromPostArgs ( query ) response = self . consumer . complete ( message , endpoint , current_url ) try : del self . session [ self . _token_key ] except KeyError : pass if ( response . status in [ 'suc...
Called to interpret the server s response to an OpenID request . It is called in step 4 of the flow described in the consumer overview .
249,482
def fromMessage ( cls , message ) : error_text = message . getArg ( OPENID_NS , 'error' , '<no error message supplied>' ) error_code = message . getArg ( OPENID_NS , 'error_code' ) return cls ( error_text , error_code , message )
Generate a ServerError instance extracting the error text and the error code from the message .
249,483
def begin ( self , service_endpoint ) : if self . store is None : assoc = None else : assoc = self . _getAssociation ( service_endpoint ) request = AuthRequest ( service_endpoint , assoc ) request . return_to_args [ self . openid1_nonce_query_arg_name ] = mkNonce ( ) if request . message . isOpenID1 ( ) : request . ret...
Create an AuthRequest object for the specified service_endpoint . This method will create an association if necessary .
249,484
def complete ( self , message , endpoint , return_to ) : mode = message . getArg ( OPENID_NS , 'mode' , '<No mode set>' ) modeMethod = getattr ( self , '_complete_' + mode , self . _completeInvalid ) return modeMethod ( message , endpoint , return_to )
Process the OpenID message using the specified endpoint and return_to URL as context . This method will handle any OpenID message that is sent to the return_to URL .
249,485
def _checkSetupNeeded ( self , message ) : if message . isOpenID1 ( ) : user_setup_url = message . getArg ( OPENID1_NS , 'user_setup_url' ) if user_setup_url is not None : raise SetupNeededError ( user_setup_url )
Check an id_res message to see if it is a checkid_immediate cancel response .
249,486
def _doIdRes ( self , message , endpoint , return_to ) : self . _idResCheckForFields ( message ) if not self . _checkReturnTo ( message , return_to ) : raise ProtocolError ( "return_to does not match return URL. Expected %r, got %r" % ( return_to , message . getArg ( OPENID_NS , 'return_to' ) ) ) endpoint = self . _ver...
Handle id_res responses that are not cancellations of immediate mode requests .
249,487
def _verifyReturnToArgs ( query ) : message = Message . fromPostArgs ( query ) return_to = message . getArg ( OPENID_NS , 'return_to' ) if return_to is None : raise ProtocolError ( 'Response has no return_to' ) parsed_url = urlparse ( return_to ) rt_query = parsed_url [ 4 ] parsed_args = cgi . parse_qsl ( rt_query ) fo...
Verify that the arguments in the return_to URL are present in this response .
249,488
def _verifyDiscoveryResults ( self , resp_msg , endpoint = None ) : if resp_msg . getOpenIDNamespace ( ) == OPENID2_NS : return self . _verifyDiscoveryResultsOpenID2 ( resp_msg , endpoint ) else : return self . _verifyDiscoveryResultsOpenID1 ( resp_msg , endpoint )
Extract the information from an OpenID assertion message and verify it against the original
249,489
def _verifyDiscoverySingle ( self , endpoint , to_match ) : for type_uri in to_match . type_uris : if not endpoint . usesExtension ( type_uri ) : raise TypeURIMismatch ( type_uri , endpoint ) defragged_claimed_id , _ = urldefrag ( to_match . claimed_id ) if defragged_claimed_id != endpoint . claimed_id : raise Protocol...
Verify that the given endpoint matches the information extracted from the OpenID assertion and raise an exception if there is a mismatch .
249,490
def _discoverAndVerify ( self , claimed_id , to_match_endpoints ) : logging . info ( 'Performing discovery on %s' % ( claimed_id , ) ) _ , services = self . _discover ( claimed_id ) if not services : raise DiscoveryFailure ( 'No OpenID information found at %s' % ( claimed_id , ) , None ) return self . _verifyDiscovered...
Given an endpoint object created from the information in an OpenID response perform discovery and verify the discovery results returning the matching endpoint that is the result of doing that discovery .
249,491
def _processCheckAuthResponse ( self , response , server_url ) : is_valid = response . getArg ( OPENID_NS , 'is_valid' , 'false' ) invalidate_handle = response . getArg ( OPENID_NS , 'invalidate_handle' ) if invalidate_handle is not None : logging . info ( 'Received "invalidate_handle" from server %s' % ( server_url , ...
Process the response message from a check_authentication request invalidating associations if requested .
249,492
def _getAssociation ( self , endpoint ) : assoc = self . store . getAssociation ( endpoint . server_url ) if assoc is None or assoc . expiresIn <= 0 : assoc = self . _negotiateAssociation ( endpoint ) if assoc is not None : self . store . storeAssociation ( endpoint . server_url , assoc ) return assoc
Get an association for the endpoint s server_url .
249,493
def _extractSupportedAssociationType ( self , server_error , endpoint , assoc_type ) : if server_error . error_code != 'unsupported-type' or server_error . message . isOpenID1 ( ) : logging . error ( 'Server error when requesting an association from %r: %s' % ( endpoint . server_url , server_error . error_text ) ) retu...
Handle ServerErrors resulting from association requests .
249,494
def _requestAssociation ( self , endpoint , assoc_type , session_type ) : assoc_session , args = self . _createAssociateRequest ( endpoint , assoc_type , session_type ) try : response = self . _makeKVPost ( args , endpoint . server_url ) except fetchers . HTTPFetchingError , why : logging . exception ( 'openid.associat...
Make and process one association request to this endpoint s OP endpoint URL .
249,495
def _createAssociateRequest ( self , endpoint , assoc_type , session_type ) : session_type_class = self . session_types [ session_type ] assoc_session = session_type_class ( ) args = { 'mode' : 'associate' , 'assoc_type' : assoc_type , } if not endpoint . compatibilityMode ( ) : args [ 'ns' ] = OPENID2_NS if ( not endp...
Create an association request for the given assoc_type and session_type .
249,496
def _extractAssociation ( self , assoc_response , assoc_session ) : assoc_type = assoc_response . getArg ( OPENID_NS , 'assoc_type' , no_default ) assoc_handle = assoc_response . getArg ( OPENID_NS , 'assoc_handle' , no_default ) expires_in_str = assoc_response . getArg ( OPENID_NS , 'expires_in' , no_default ) try : e...
Attempt to extract an association from the response given the association response message and the established association session .
249,497
def setAnonymous ( self , is_anonymous ) : if is_anonymous and self . message . isOpenID1 ( ) : raise ValueError ( 'OpenID 1 requests MUST include the ' 'identifier in the request' ) else : self . _anonymous = is_anonymous
Set whether this request should be made anonymously . If a request is anonymous the identifier will not be sent in the request . This is only useful if you are making another kind of request with an extension in this request .
249,498
def addExtensionArg ( self , namespace , key , value ) : self . message . setArg ( namespace , key , value )
Add an extension argument to this OpenID authentication request .
249,499
def redirectURL ( self , realm , return_to = None , immediate = False ) : message = self . getMessage ( realm , return_to , immediate ) return message . toURL ( self . endpoint . server_url )
Returns a URL with an encoded OpenID request .