idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
248,400
def cleanup ( self , force = False ) : manager = self . getManager ( force = force ) if manager is not None : service = manager . current ( ) self . destroyManager ( force = force ) else : service = None return service
Clean up Yadis - related services in the session and return the most - recently - attempted service from the manager if one exists .
50
26
248,401
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 .
55
18
248,402
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 .
96
20
248,403
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 .
41
16
248,404
def _setPrivate ( self , private ) : self . private = private self . public = pow ( self . generator , self . private , self . modulus )
This is here to make testing easier
34
7
248,405
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 .
165
18
248,406
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 .
793
8
248,407
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?
78
11
248,408
def encodeToURL ( self , server_url ) : if not self . return_to : raise NoReturnToError # Imported from the alternate reality where these classes are used # in both the client and server code, so Requests are Encodable too. # That's right, code imported from alternate realities all for the # love of you, id_res/user_se...
Encode this request as a URL to GET .
237
10
248,409
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 .
95
8
248,410
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 .
50
8
248,411
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 .
121
11
248,412
def sign ( self , response ) : signed_response = deepcopy ( response ) assoc_handle = response . request . assoc_handle if assoc_handle : # normal mode # disabling expiration check because even if the association # is expired, we still need to know some properties of the # association so that we may preserve those prop...
Sign a response .
310
4
248,413
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 .
163
5
248,414
def getAssociation ( self , assoc_handle , dumb , checkExpiration = True ) : # Hmm. We've created an interface that deals almost entirely with # assoc_handles. The only place outside the Signatory that uses this # (and thus the only place that ever sees Association objects) is # when creating a response to an associati...
Get the association with the specified handle .
236
8
248,415
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 .
51
9
248,416
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 .
55
14
248,417
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 .
126
14
248,418
def rpXRDS ( request ) : return util . renderXRDS ( request , [ RP_RETURN_TO_URL_TYPE ] , [ util . getViewURL ( request , finishOpenID ) ] )
Return a relying party verification XRDS document
48
9
248,419
def getSession ( self ) : if self . session is not None : return self . session # Get value of cookie header that was sent 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...
Return the existing session or a new session
208
8
248,420
def doProcess ( self ) : oidconsumer = self . getConsumer ( ) # Ask the library to check the response that the server sent # us. Status is a code indicating the response type. info is # either None or a string containing more information about # the return type. url = 'http://' + self . headers . get ( 'Host' ) + self ...
Handle the redirect from the OpenID server .
634
9
248,421
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 .
75
12
248,422
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 .
168
4
248,423
def _callInTransaction ( self , func , * args , * * kwargs ) : # No nesting of transactions 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 . co...
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 .
97
30
248,424
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 .
63
8
248,425
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 .
41
18
248,426
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 : # The key uniqueness check failed return False else : # The nonce was successfully adde...
Return whether this nonce is present and if it is then remove it from the set .
85
18
248,427
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 .
78
17
248,428
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 .
50
15
248,429
def providerIsAuthoritative ( providerID , canonicalID ) : # XXX: can't use rsplit until we require python >= 2.4. lastbang = canonicalID . rindex ( '!' ) parent = canonicalID [ : lastbang ] return parent == providerID
Is this provider ID authoritative for this XRI?
56
10
248,430
def rootAuthority ( xri ) : if xri . startswith ( 'xri://' ) : xri = xri [ 6 : ] authority = xri . split ( '/' , 1 ) [ 0 ] if authority [ 0 ] == '(' : # Cross-reference. # XXX: This is incorrect if someone nests cross-references so there # is another close-paren in there. Hopefully nobody does that # before we have a r...
Return the root authority for an XRI .
215
9
248,431
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 .
158
20
248,432
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 .
55
26
248,433
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 .
41
13
248,434
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 .
60
15
248,435
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 .
159
49
248,436
def getAssociation ( self , server_url , handle = None ) : if handle is None : handle = '' # The filename with the empty handle is a prefix of all other # associations for the given server URL. filename = self . getAssociationFilename ( server_url , handle ) if handle : return self . _getAssociation ( filename ) else :...
Retrieve an association . If no handle is specified return the association with the latest expiration .
272
18
248,437
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 .
62
14
248,438
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 : # Create empty proto / rest values for empty server_url, # which is part of a consumer-generated nonce. proto , rest = '' , ...
Return whether this nonce is valid .
255
8
248,439
def arrangeByType ( service_list , preferred_types ) : def enumerate ( elts ) : """Return an iterable that pairs the index of an element with that element. For Python 2.2 compatibility""" return zip ( range ( len ( elts ) ) , elts ) def bestMatchingService ( service ) : """Return the index of the first matching type, o...
Rearrange service_list in a new list so services are ordered by types listed in preferred_types . Return the new list .
294
27
248,440
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 .
77
34
248,441
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?
50
7
248,442
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 ( ) : # XXX: This has crappy implications for Service elements # that contain both 'server' and 'signon' Types. But # that's a pathologic...
Set the state of this object based on the contents of the service element .
140
15
248,443
def getLocalID ( self ) : # I looked at this conditional and thought "ah-hah! there's the bug!" # but Python actually makes that one big expression somehow, i.e. # "x is x is x" is not the same thing as "(x is x) is x". # That's pretty weird, dude. -- kmt, 1/07 if ( self . local_id is self . canonicalID is None ) : ret...
Return the identifier that should be sent as the openid . identity parameter to the server .
114
18
248,444
def fromBasicServiceEndpoint ( cls , endpoint ) : type_uris = endpoint . matchTypes ( cls . openid_type_uris ) # If any Type URIs match and there is an endpoint URI # specified, then this is an OpenID endpoint if type_uris and endpoint . uri is not None : openid_endpoint = cls ( ) openid_endpoint . parseService ( endpo...
Create a new instance of this class from the endpoint object passed in .
131
14
248,445
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 .
59
8
248,446
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
58
19
248,447
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 .
51
14
248,448
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?
60
11
248,449
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 .
150
9
248,450
def getMessageSignature ( self , message ) : pairs = self . _makePairs ( message ) return oidutil . toBase64 ( self . sign ( pairs ) )
Return the signature of a message .
38
7
248,451
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 .
86
21
248,452
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
44
9
248,453
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 .
142
10
248,454
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 .
44
10
248,455
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 ) # Note the URL...
Discover services for a given URI .
282
7
248,456
def whereIsYadis ( resp ) : # Attempt to find out where to go to discover the document # or if we already have it content_type = resp . headers . get ( 'content-type' ) # According to the spec, the content-type header must be an exact # match, or else we have to look for an indirection. if ( content_type and content_ty...
Given a HTTPResponse return the location of the Yadis document .
396
16
248,457
def endpoint ( request ) : s = getServer ( request ) query = util . normalDict ( request . GET or request . POST ) # First, decode the incoming request into something the OpenID # library can use. try : openid_request = s . decodeRequest ( query ) except ProtocolError , why : # This means the incoming request was inval...
Respond to low - level OpenID protocol messages .
269
11
248,458
def showDecidePage ( request , openid_request ) : trust_root = openid_request . trust_root return_to = openid_request . return_to try : # Stringify because template's ifequal can only compare to strings. trust_root_valid = verifyReturnTo ( trust_root , return_to ) and "Valid" or "Invalid" except DiscoveryFailure , err ...
Render a page to the user so a trust decision can be made .
217
14
248,459
def processTrustResult ( request ) : # Get the request from the session so we can construct the # appropriate response. openid_request = getRequest ( request ) # The identifier that this server can vouch for response_identity = getViewURL ( request , idPage ) # If the decision was to allow the verification, respond # a...
Handle the result of a trust decision and respond to the RP accordingly .
343
14
248,460
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 .
313
18
248,461
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 .
43
8
248,462
def split ( nonce_string ) : timestamp_str = nonce_string [ : time_str_len ] try : timestamp = timegm ( strptime ( timestamp_str , time_fmt ) ) except AssertionError : # Python 2.2 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
92
10
248,463
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 ( ) # Time after which we should not use the nonce past = now - allowed_skew # Time that is too far in the future for us to allow future =...
Is the timestamp that is part of the specified nonce string within the allowed clock - skew of the current time?
122
23
248,464
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
68
9
248,465
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 .
36
19
248,466
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
62
5
248,467
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 .
54
15
248,468
def fetch ( self , url , body = None , headers = None ) : if body : method = 'POST' else : method = 'GET' if headers is None : headers = { } # httplib2 doesn't check to make sure that the URL's scheme is # 'http' so we do it here. if not ( url . startswith ( 'http://' ) or url . startswith ( 'https://' ) ) : raise Valu...
Perform an HTTP request
335
5
248,469
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 .
78
20
248,470
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 .
81
23
248,471
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 .
348
19
248,472
def relMatches ( rel_attr , target_rel ) : # XXX: TESTME 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?
57
12
248,473
def linkHasRel ( link_attrs , target_rel ) : # XXX: TESTME rel_attr = link_attrs . get ( 'rel' ) return rel_attr and relMatches ( rel_attr , target_rel )
Does this link have target_rel as a relationship?
52
11
248,474
def findFirstHref ( link_attrs_list , target_rel ) : # XXX: TESTME 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 .
61
24
248,475
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 : # Make sure it can actually parse XML try : ElementTree . XML ( '<unused/>...
Find a working ElementTree implementation trying the standard places that such a thing might show up .
180
18
248,476
def getYadisXRD ( xrd_tree ) : xrd = None # for the side-effect of assigning the last one in the list to the # xrd variable for xrd in xrd_tree . findall ( xrd_tag ) : pass # There were no elements found, or else xrd would be set to the # last one if xrd is None : raise XRDSError ( 'No XRD present in tree' ) return xrd
Return the XRD element that should contain the Yadis services
101
12
248,477
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 # Will raise ValueError if the string is not the expected format expires_time = strptime ( expires_string , "%Y-%m-%dT%H...
Return the expiration date of this XRD element or None if no expiration was specified .
111
17
248,478
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 : ] : # XXX: can't use rsplit u...
Return the CanonicalID from this XRDS document .
258
12
248,479
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' ) # Any errors in parsing the priority fall through to here return Max
Get the priority of this element .
88
7
248,480
def makeKVPost ( request_message , server_url ) : # XXX: TESTME resp = fetchers . fetch ( server_url , body = request_message . toURLEncoded ( ) ) # Process response in separate function that can be shared by async code. return _httpResponseToMessage ( resp , server_url )
Make a Direct Request to an OpenID Provider and return the result as a Message object .
72
18
248,481
def _httpResponseToMessage ( response , server_url ) : # Should this function be named Message.fromHTTPResponse instead? response_message = Message . fromKVForm ( response . body ) if response . status == 400 : raise ServerError . fromMessage ( response_message ) elif response . status not in ( 200 , 206 ) : fmt = 'bad...
Adapt a POST response to a Message .
123
8
248,482
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 .
150
29
248,483
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 .
71
18
248,484
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 .
126
22
248,485
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 .
72
35
248,486
def _checkSetupNeeded ( self , message ) : # In OpenID 1, we check to see if this is a cancel from # immediate mode by the presence of the user_setup_url # parameter. if message . isOpenID1 ( ) : user_setup_url = message . getArg ( OPENID1_NS , 'user_setup_url' ) if user_setup_url is not None : raise SetupNeededError (...
Check an id_res message to see if it is a checkid_immediate cancel response .
101
20
248,487
def _doIdRes ( self , message , endpoint , return_to ) : # Checks for presence of appropriate fields (and checks # signed list fields) self . _idResCheckForFields ( message ) if not self . _checkReturnTo ( message , return_to ) : raise ProtocolError ( "return_to does not match return URL. Expected %r, got %r" % ( retur...
Handle id_res responses that are not cancellations of immediate mode requests .
284
15
248,488
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 .
293
17
248,489
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
78
16
248,490
def _verifyDiscoverySingle ( self , endpoint , to_match ) : # Every type URI that's in the to_match endpoint has to be # present in the discovered endpoint. for type_uri in to_match . type_uris : if not endpoint . usesExtension ( type_uri ) : raise TypeURIMismatch ( type_uri , endpoint ) # Fragments do not influence di...
Verify that the given endpoint matches the information extracted from the OpenID assertion and raise an exception if there is a mismatch .
442
25
248,491
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 .
107
33
248,492
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 .
176
17
248,493
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 .
83
11
248,494
def _extractSupportedAssociationType ( self , server_error , endpoint , assoc_type ) : # Any error message whose code is not 'unsupported-type' # should be considered a total failure. if server_error . error_code != 'unsupported-type' or server_error . message . isOpenID1 ( ) : logging . error ( 'Server error when requ...
Handle ServerErrors resulting from association requests .
362
9
248,495
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 .
208
14
248,496
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 # Leave out t...
Create an association request for the given assoc_type and session_type .
194
16
248,497
def _extractAssociation ( self , assoc_response , assoc_session ) : # Extract the common fields from the response, raising an # exception if they are not found assoc_type = assoc_response . getArg ( OPENID_NS , 'assoc_type' , no_default ) assoc_handle = assoc_response . getArg ( OPENID_NS , 'assoc_handle' , no_default ...
Attempt to extract an association from the response given the association response message and the established association session .
643
19
248,498
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 .
62
43
248,499
def addExtensionArg ( self , namespace , key , value ) : self . message . setArg ( namespace , key , value )
Add an extension argument to this OpenID authentication request .
28
11