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 ( self . session ) return manager
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 . setArg ( OPENID_NS , 'error' , message ) if preferred_association_type : response . fields . setArg ( OPENID_NS , 'assoc_type' , preferred_association_type ) if preferred_session_type : response . fields . setArg ( OPENID_NS , 'session_type' , preferred_session_type ) return response
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 . mode = "checkid_setup" self . return_to = message . getArg ( OPENID_NS , 'return_to' ) if message . isOpenID1 ( ) and not self . return_to : fmt = "Missing required field 'return_to' from %r" raise ProtocolError ( message , text = fmt % ( message , ) ) self . identity = message . getArg ( OPENID_NS , 'identity' ) self . claimed_id = message . getArg ( OPENID_NS , 'claimed_id' ) if message . isOpenID1 ( ) : if self . identity is None : s = "OpenID 1 message did not contain openid.identity" raise ProtocolError ( message , text = s ) else : if self . identity and not self . claimed_id : s = ( "OpenID 2.0 message contained openid.identity but not " "claimed_id" ) raise ProtocolError ( message , text = s ) elif self . claimed_id and not self . identity : s = ( "OpenID 2.0 message contained openid.claimed_id but not " "identity" ) raise ProtocolError ( message , text = s ) # There's a case for making self.trust_root be a TrustRoot # here. But if TrustRoot isn't currently part of the "public" API, # I'm not sure it's worth doing. if message . isOpenID1 ( ) : trust_root_param = 'trust_root' else : trust_root_param = 'realm' # Using 'or' here is slightly different than sending a default # argument to getArg, as it will treat no value and an empty # string as equivalent. self . trust_root = ( message . getArg ( OPENID_NS , trust_root_param ) or self . return_to ) if not message . isOpenID1 ( ) : if self . return_to is self . trust_root is None : raise ProtocolError ( message , "openid.realm required when " + "openid.return_to absent" ) self . assoc_handle = message . getArg ( OPENID_NS , 'assoc_handle' ) # Using TrustRoot.parse here is a bit misleading, as we're not # parsing return_to as a trust root at all. However, valid URLs # are valid trust roots, so we can use this to get an idea if it # is a valid URL. Not all trust roots are valid return_to URLs, # however (particularly ones with wildcards), so this is still a # little sketchy. if self . return_to is not None and not TrustRoot . parse ( self . return_to ) : raise MalformedReturnURL ( message , self . return_to ) # I first thought that checking to see if the return_to is within # the trust_root is premature here, a logic-not-decoding thing. But # it was argued that this is really part of data validation. A # request with an invalid trust_root/return_to is broken regardless of # application, right? if not self . trustRootValid ( ) : raise UntrustedReturnURL ( message , self . return_to , self . trust_root ) return 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_setup_url. 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 : q [ 'realm' ] = self . trust_root if self . assoc_handle : q [ 'assoc_handle' ] = self . assoc_handle response = Message ( self . message . getOpenIDNamespace ( ) ) response . updateArgs ( OPENID_NS , q ) return response . toURL ( server_url )
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 . toURL ( self . return_to )
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 , ex : logging . exception ( "Error in verifying %s with %s: %s" % ( message , assoc , ex ) ) return False return valid
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 properties when # creating the fallback association. assoc = self . getAssociation ( assoc_handle , dumb = False , checkExpiration = False ) if not assoc or assoc . expiresIn <= 0 : # fall back to dumb mode signed_response . fields . setArg ( OPENID_NS , 'invalidate_handle' , assoc_handle ) assoc_type = assoc and assoc . assoc_type or 'HMAC-SHA1' if assoc and assoc . expiresIn <= 0 : # now do the clean-up that the disabled checkExpiration # code didn't get to do. self . invalidate ( assoc_handle , dumb = False ) assoc = self . createAssociation ( dumb = True , assoc_type = assoc_type ) else : # dumb mode. assoc = self . createAssociation ( dumb = True ) try : signed_response . fields = assoc . signMessage ( signed_response . fields ) except kvform . KVFormError , err : raise EncodingError ( response , explanation = str ( err ) ) return signed_response
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_LIFETIME , handle , secret , assoc_type ) if dumb : key = self . _dumb_key else : key = self . _normal_key self . store . storeAssociation ( key , assoc ) return assoc
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 association request, as it must have # the association's secret. 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 . expiresIn <= 0 : logging . info ( "requested %sdumb key %r is expired (by %s seconds)" % ( ( not dumb ) and 'not-' or '' , assoc_handle , assoc . expiresIn ) ) if checkExpiration : self . store . removeAssociation ( key , assoc_handle ) assoc = None return assoc
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 self . reference is not None : reply . setArg ( OPENID_NS , 'reference' , str ( self . reference ) ) return reply
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 : sid = sid_morsel . value else : sid = None else : sid = None # If a session id was not set, create a new one if sid is None : sid = randomString ( 16 , '0123456789abcdef' ) session = None else : session = self . server . sessions . get ( sid ) # If no session exists for this session ID, create one if session is None : session = self . server . sessions [ sid ] = { } session [ 'id' ] = sid self . session = session return session
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 . path info = oidconsumer . complete ( self . query , url ) sreg_resp = None pape_resp = None css_class = 'error' display_identifier = info . getDisplayIdentifier ( ) if info . status == consumer . FAILURE and display_identifier : # In the case of failure, if info is non-None, it is the # URL that we were verifying. We include it in the error # message to help the user figure out what happened. fmt = "Verification of %s failed: %s" message = fmt % ( cgi . escape ( display_identifier ) , info . message ) elif info . status == consumer . SUCCESS : # Success means that the transaction completed without # error. If info is None, it means that the user cancelled # the verification. css_class = 'alert' # This is a successful verification attempt. If this # was a real application, we would do our login, # comment posting, etc. here. fmt = "You have successfully verified %s as your identity." message = fmt % ( cgi . escape ( display_identifier ) , ) sreg_resp = sreg . SRegResponse . fromSuccessResponse ( info ) pape_resp = pape . Response . fromSuccessResponse ( info ) if info . endpoint . canonicalID : # You should authorize i-name users by their canonicalID, # rather than their more human-friendly identifiers. That # way their account with you is not compromised if their # i-name registration expires and is bought by someone else. message += ( " This is an i-name, and its persistent ID is %s" % ( cgi . escape ( info . endpoint . canonicalID ) , ) ) elif info . status == consumer . CANCEL : # cancelled message = 'Verification cancelled' elif info . status == consumer . SETUP_NEEDED : if info . setup_url : message = '<a href=%s>Setup needed</a>' % ( quoteattr ( info . setup_url ) , ) else : # This means auth didn't succeed, but you're welcome to try # non-immediate mode. message = 'Setup needed' else : # Either we don't understand the code or there is no # openid_url included with the error. Give a generic # failure message. The library should supply debug # information in a log. message = 'Verification failed.' self . render ( message , css_class , display_identifier , sreg_data = sreg_resp , pape_data = pape_resp )
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 . wfile . write ( message ) self . wfile . write ( "</div>" ) if sreg_data is not None : self . renderSREG ( sreg_data ) if pape_data is not None : self . renderPAPE ( pape_data ) self . pageFooter ( form_contents )
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 . 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 .
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 added return True
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 real xriparse function. Hopefully nobody does # that *ever*. root = authority [ : authority . index ( ')' ) + 1 ] elif authority [ 0 ] in XRI_AUTHORITIES : # Other XRI reference. root = authority [ 0 ] else : # IRI reference. XXX: Can IRI authorities have segments? segments = authority . split ( '!' ) segments = reduce ( list . __add__ , map ( lambda s : s . split ( '*' ) , segments ) ) root = segments [ 0 ] return XRI ( root )
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 . isOpenID1 ( ) try : message . namespaces . addAlias ( self . ns_uri , self . ns_alias , implicit = implicit ) except KeyError : if message . namespaces . getAlias ( self . ns_uri ) != self . ns_alias : raise message . updateArgs ( self . ns_uri , self . getExtensionArgs ( ) ) return message
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 = _safe64 ( handle ) else : handle_hash = '' filename = '%s-%s-%s-%s' % ( proto , domain , url_hash , handle_hash ) return os . path . join ( self . association_dir , filename )
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 : association_files = os . listdir ( self . association_dir ) matching_files = [ ] # strip off the path to do the comparison name = os . path . basename ( filename ) for association_file in association_files : if association_file . startswith ( name ) : matching_files . append ( association_file ) matching_associations = [ ] # read the matching files and sort by time issued for name in matching_files : full_name = os . path . join ( self . association_dir , name ) association = self . _getAssociation ( full_name ) if association is not None : matching_associations . append ( ( association . issued , association ) ) matching_associations . sort ( ) # return the most recently issued one. if matching_associations : ( _ , assoc ) = matching_associations [ - 1 ] return assoc else : return None
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 = '' , '' domain = _filenameEscape ( rest . split ( '/' , 1 ) [ 0 ] ) url_hash = _safe64 ( server_url ) salt_hash = _safe64 ( salt ) filename = '%08x-%s-%s-%s-%s' % ( timestamp , proto , domain , url_hash , salt_hash ) filename = os . path . join ( self . nonce_dir , filename ) try : fd = os . open ( filename , os . O_CREAT | os . O_EXCL | os . O_WRONLY , 0200 ) except OSError , why : if why . errno == EEXIST : return False else : raise else : os . close ( fd ) return True
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, or something higher if no type matches. This provides an ordering in which service elements that contain a type that comes earlier in the preferred types list come before service elements that come later. If a service element has more than one type, the most preferred one wins. """ for i , t in enumerate ( preferred_types ) : if preferred_types [ i ] in service . type_uris : return i return len ( preferred_types ) # Build a list with the service elements in tuples whose # comparison will prefer the one with the best matching service prio_services = [ ( bestMatchingService ( s ) , orig_index , s ) for ( orig_index , s ) in enumerate ( service_list ) ] prio_services . sort ( ) # Now that the services are sorted by priority, remove the sort # keys from the list. for i in range ( len ( prio_services ) ) : prio_services [ i ] = prio_services [ i ] [ 2 ] return prio_services
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 pathological configuration anyway, so I don't # think I care. 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 .
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 ) : 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 .
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 ( endpoint . yadis_url , endpoint . uri , endpoint . type_uris , endpoint . service_element ) else : openid_endpoint = None return openid_endpoint
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 field_name in self . assoc_keys : pairs . append ( ( field_name , data [ field_name ] ) ) return kvform . seqToKV ( pairs , strict = True )
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 : raise KeyError ( 'Attempting to redefine alias %r from %r to %r' , alias , existing_uri , auth_level_uri ) self . auth_level_aliases [ alias ] = auth_level_uri
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 after following redirects result . normalized_uri = resp . final_url # Attempt to find out where to go to discover the document # or if we already have it result . content_type = resp . headers . get ( 'content-type' ) result . xrds_uri = whereIsYadis ( resp ) if result . xrds_uri and result . usedYadisLocation ( ) : resp = fetchers . fetch ( result . xrds_uri ) if resp . status not in ( 200 , 206 ) : exc = DiscoveryFailure ( 'HTTP Response status from Yadis host is not 200. ' 'Got status %r' % ( resp . status , ) , resp ) exc . identity_url = result . normalized_uri raise exc result . content_type = resp . headers . get ( 'content-type' ) result . response_text = resp . body return result
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_type . split ( ';' , 1 ) [ 0 ] . lower ( ) == YADIS_CONTENT_TYPE ) : return resp . final_url else : # Try the header yadis_loc = resp . headers . get ( YADIS_HEADER_NAME . lower ( ) ) if not yadis_loc : # Parse as HTML if the header is missing. # # XXX: do we want to do something with content-type, like # have a whitelist or a blacklist (for detecting that it's # HTML)? # Decode body by encoding of file content_type = content_type or '' encoding = content_type . rsplit ( ';' , 1 ) if len ( encoding ) == 2 and encoding [ 1 ] . strip ( ) . startswith ( 'charset=' ) : encoding = encoding [ 1 ] . split ( '=' , 1 ) [ 1 ] . strip ( ) else : encoding = 'UTF-8' try : content = resp . body . decode ( encoding ) except UnicodeError : # Keep encoded version in case yadis location can be found before encoding shut this up. # Possible errors will be caught lower. content = resp . body try : yadis_loc = findHTMLMeta ( StringIO ( content ) ) except ( MetaNotFound , UnicodeError ) : # UnicodeError: Response body could not be encoded and xrds location # could not be found before troubles occurs. pass return yadis_loc
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 invalid. return direct_to_template ( request , 'server/endpoint.html' , { 'error' : str ( why ) } ) # If we did not get a request, display text indicating that this # is an endpoint. if openid_request is None : return direct_to_template ( request , 'server/endpoint.html' , { } ) # We got a request; if the mode is checkid_*, we will handle it by # getting feedback from the user or by checking the session. if openid_request . mode in [ "checkid_immediate" , "checkid_setup" ] : return handleCheckIDRequest ( request , openid_request ) else : # We got some other kind of OpenID request, so we let the # server handle this. openid_response = s . handleRequest ( openid_request ) return displayResponse ( request , openid_response )
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 : trust_root_valid = "DISCOVERY_FAILED" except HTTPFetchingError , err : trust_root_valid = "Unreachable" pape_request = pape . Request . fromOpenIDRequest ( openid_request ) return direct_to_template ( request , 'server/trust.html' , { 'trust_root' : trust_root , 'trust_handler_url' : getViewURL ( request , processTrustResult ) , 'trust_root_valid' : trust_root_valid , 'pape_request' : pape_request , } )
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 # accordingly. allowed = 'allow' in request . POST # Generate a response with the appropriate answer. openid_response = openid_request . answer ( allowed , identity = response_identity ) # Send Simple Registration data in the response, if appropriate. if allowed : sreg_data = { 'fullname' : 'Example User' , 'nickname' : 'example' , 'dob' : '1970-01-01' , 'email' : 'invalid@example.com' , 'gender' : 'F' , 'postcode' : '12345' , 'country' : 'ES' , 'language' : 'eu' , 'timezone' : 'America/New_York' , } sreg_req = sreg . SRegRequest . fromOpenIDRequest ( openid_request ) sreg_resp = sreg . SRegResponse . extractResponse ( sreg_req , sreg_data ) openid_response . addExtension ( sreg_resp ) pape_response = pape . Response ( ) pape_response . setAuthLevel ( pape . LEVELS_NIST , 0 ) openid_response . addExtension ( pape_response ) return displayResponse ( request , openid_response )
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 ( out_dir , test_name ) out_file = file ( out_file_name , 'w' ) out_file . write ( data ) manifest = [ manifest_header ] for success , input_name , id_name , result_name in discoverdata . testlist : if not success : continue writeTestFile ( input_name ) input_url = urlparse . urljoin ( base_url , input_name ) id_url = urlparse . urljoin ( base_url , id_name ) result_url = urlparse . urljoin ( base_url , result_name ) manifest . append ( '\t' . join ( ( input_url , id_url , result_url ) ) ) manifest . append ( '\n' ) manifest_file_name = os . path . join ( out_dir , 'manifest.txt' ) manifest_file = file ( manifest_file_name , 'w' ) for chunk in manifest : manifest_file . write ( chunk ) manifest_file . close ( )
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 = now + allowed_skew # the stamp is not too far in the future and is not too far in # the past return past <= stamp <= 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 ValueError ( 'URL is not a HTTP URL: %r' % ( url , ) ) httplib2_response , content = self . httplib2 . request ( url , method , body = body , headers = headers ) # Translate the httplib2 response to our HTTP response abstraction # When a 400 is returned, there is no "content-location" # header set. This seems like a bug to me. I can't think of a # case where we really care about the final URL when it is an # error response, but being careful about it can't hurt. try : final_url = httplib2_response [ 'content-location' ] except KeyError : # We're assuming that no redirects occurred assert not httplib2_response . previous # And this should never happen for a successful response assert httplib2_response . status != 200 final_url = url return HTTPResponse ( body = content , final_url = final_url , headers = dict ( httplib2_response . items ( ) ) , status = httplib2_response . status , )
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 . start ( 'contents' ) == - 1 : return [ ] start , end = head_mo . span ( 'contents' ) link_mos = link_find . finditer ( stripped , head_mo . start ( ) , head_mo . end ( ) ) matches = [ ] for link_mo in link_mos : start = link_mo . start ( ) + 5 link_attrs = { } for attr_mo in attr_find . finditer ( stripped , start ) : if attr_mo . lastgroup == 'end_link' : break # Either q_val or unq_val must be present, but not both # unq_val is a True (non-empty) value if it is present attr_name , q_val , unq_val = attr_mo . group ( 'attr_name' , 'q_val' , 'unq_val' ) attr_val = ent_replace . sub ( replaceEnt , unq_val or q_val ) link_attrs [ attr_name ] = attr_val matches . append ( link_attrs ) return matches
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/>' ) except ( SystemExit , MemoryError , AssertionError ) : raise except : logging . exception ( 'Not using ElementTree library %r because it failed to ' 'parse a trivial document: %s' % mod_name ) else : return ElementTree else : raise ImportError ( 'No ElementTree library found. ' 'You may need to install one. ' 'Tried importing %r' % ( module_names , ) )
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:%M:%SZ" ) return datetime ( * expires_time [ 0 : 6 ] )
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 until we require python >= 2.4. parent_sought = childID [ : childID . rindex ( '!' ) ] parent = xri . XRI ( xrd . findtext ( canonicalID_tag ) ) if parent_sought != parent . lower ( ) : raise XRDSFraud ( "%r can not come from %s" % ( childID , parent ) ) childID = parent_sought root = xri . rootAuthority ( iname ) if not xri . providerIsAuthoritative ( root , childID ) : raise XRDSFraud ( "%r can not come from root %r" % ( childID , root ) ) return canonicalID
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 status code from server %s: %s' error_message = fmt % ( server_url , response . status ) raise fetchers . HTTPFetchingError ( error_message ) return response_message
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 [ 'success' , 'cancel' ] and response . identity_url is not None ) : disco = Discovery ( self . session , response . identity_url , self . session_key_prefix ) # This is OK to do even if we did not do discovery in # the first place. disco . cleanup ( force = True ) return response
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 . return_to_args [ self . openid1_return_to_identifier_name ] = request . endpoint . claimed_id return request
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 ( user_setup_url )
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" % ( return_to , message . getArg ( OPENID_NS , 'return_to' ) ) ) # Verify discovery information: endpoint = self . _verifyDiscoveryResults ( message , endpoint ) logging . info ( "Received id_res response from %s using association %s" % ( endpoint . server_url , message . getArg ( OPENID_NS , 'assoc_handle' ) ) ) self . _idResCheckSignature ( message , endpoint . server_url ) # Will raise a ProtocolError if the nonce is bad self . _idResCheckNonce ( message , endpoint ) signed_list_str = message . getArg ( OPENID_NS , 'signed' , no_default ) signed_list = signed_list_str . split ( ',' ) signed_fields = [ "openid." + s for s in signed_list ] return SuccessResponse ( endpoint , message , signed_fields )
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 ) for rt_key , rt_value in parsed_args : try : value = query [ rt_key ] if rt_value != value : format = ( "parameter %s value %r does not match " "return_to's value %r" ) raise ProtocolError ( format % ( rt_key , value , rt_value ) ) except KeyError : format = "return_to parameter %s absent from query %r" raise ProtocolError ( format % ( rt_key , query ) ) # Make sure all non-OpenID arguments in the response are also # in the signed return_to. bare_args = message . getArgs ( BARE_NS ) for pair in bare_args . iteritems ( ) : if pair not in parsed_args : raise ProtocolError ( "Parameter %s not in return_to URL" % ( pair [ 0 ] , ) )
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 discovery, so we can't compare a # claimed identifier with a fragment to discovered information. defragged_claimed_id , _ = urldefrag ( to_match . claimed_id ) if defragged_claimed_id != endpoint . claimed_id : raise ProtocolError ( 'Claimed ID does not match (different subjects!), ' 'Expected %s, got %s' % ( defragged_claimed_id , endpoint . claimed_id ) ) if to_match . getLocalID ( ) != endpoint . getLocalID ( ) : raise ProtocolError ( 'local_id mismatch. Expected %s, got %s' % ( to_match . getLocalID ( ) , endpoint . getLocalID ( ) ) ) # If the server URL is None, this must be an OpenID 1 # response, because op_endpoint is a required parameter in # OpenID 2. In that case, we don't actually care what the # discovered server_url is, because signature checking or # check_auth should take care of that check for us. if to_match . server_url is None : assert to_match . preferredNamespace ( ) == OPENID1_NS , ( """The code calling this must ensure that OpenID 2 responses have a non-none `openid.op_endpoint' and that it is set as the `server_url' attribute of the `to_match' endpoint.""" ) elif to_match . server_url != endpoint . server_url : raise ProtocolError ( 'OP Endpoint mismatch. Expected %s, got %s' % ( to_match . server_url , endpoint . server_url ) )
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 . _verifyDiscoveredServices ( claimed_id , services , to_match_endpoints )
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 , ) ) if self . store is None : logging . error ( 'Unexpectedly got invalidate_handle without ' 'a store!' ) else : self . store . removeAssociation ( server_url , invalidate_handle ) if is_valid == 'true' : return True else : logging . error ( 'Server responds that checkAuth call is not valid' ) return False
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 requesting an association from %r: %s' % ( endpoint . server_url , server_error . error_text ) ) return None # The server didn't like the association/session type # that we sent, and it sent us back a message that # might tell us how to handle it. logging . error ( 'Unsupported association type %s: %s' % ( assoc_type , server_error . error_text , ) ) # Extract the session_type and assoc_type from the # error message assoc_type = server_error . message . getArg ( OPENID_NS , 'assoc_type' ) session_type = server_error . message . getArg ( OPENID_NS , 'session_type' ) if assoc_type is None or session_type is None : logging . error ( 'Server responded with unsupported association ' 'session but did not supply a fallback.' ) return None elif not self . negotiator . isAllowed ( assoc_type , session_type ) : fmt = ( 'Server sent unsupported session/association type: ' 'session_type=%s, assoc_type=%s' ) logging . error ( fmt % ( session_type , assoc_type ) ) return None else : return assoc_type , session_type
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.associate request failed: %s' % ( why [ 0 ] , ) ) return None try : assoc = self . _extractAssociation ( response , assoc_session ) except KeyError , why : logging . exception ( 'Missing required parameter in response from %s: %s' % ( endpoint . server_url , why [ 0 ] ) ) return None except ProtocolError , why : logging . exception ( 'Protocol error parsing response from %s: %s' % ( endpoint . server_url , why [ 0 ] ) ) return None else : return assoc
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 the session type if we're in compatibility mode # *and* it's no-encryption. if ( not endpoint . compatibilityMode ( ) or assoc_session . session_type != 'no-encryption' ) : args [ 'session_type' ] = assoc_session . session_type args . update ( assoc_session . getRequest ( ) ) message = Message . fromOpenIDArgs ( args ) return assoc_session , message
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 ) # expires_in is a base-10 string. The Python parsing will # accept literals that have whitespace around them and will # accept negative values. Neither of these are really in-spec, # but we think it's OK to accept them. expires_in_str = assoc_response . getArg ( OPENID_NS , 'expires_in' , no_default ) try : expires_in = int ( expires_in_str ) except ValueError , why : raise ProtocolError ( 'Invalid expires_in field: %s' % ( why [ 0 ] , ) ) # OpenID 1 has funny association session behaviour. if assoc_response . isOpenID1 ( ) : session_type = self . _getOpenID1SessionType ( assoc_response ) else : session_type = assoc_response . getArg ( OPENID2_NS , 'session_type' , no_default ) # Session type mismatch if assoc_session . session_type != session_type : if ( assoc_response . isOpenID1 ( ) and session_type == 'no-encryption' ) : # In OpenID 1, any association request can result in a # 'no-encryption' association response. Setting # assoc_session to a new no-encryption session should # make the rest of this function work properly for # that case. assoc_session = PlainTextConsumerSession ( ) else : # Any other mismatch, regardless of protocol version # results in the failure of the association session # altogether. fmt = 'Session type mismatch. Expected %r, got %r' message = fmt % ( assoc_session . session_type , session_type ) raise ProtocolError ( message ) # Make sure assoc_type is valid for session_type if assoc_type not in assoc_session . allowed_assoc_types : fmt = 'Unsupported assoc_type for session %s returned: %s' raise ProtocolError ( fmt % ( assoc_session . session_type , assoc_type ) ) # Delegate to the association session to extract the secret # from the response, however is appropriate for that session # type. try : secret = assoc_session . extractSecret ( assoc_response ) except ValueError , why : fmt = 'Malformed response for %s session: %s' raise ProtocolError ( fmt % ( assoc_session . session_type , why [ 0 ] ) ) return Association . fromExpiresIn ( expires_in , assoc_handle , secret , assoc_type )
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