Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def decode(self, query): if not query: return None try: message = Message.fromPostArgs(query) except InvalidOpenIDNamespace, err: # It's useful to have a Message attached to a ProtocolError, so we ...
[ "I transform query parameters into an L{OpenIDRequest}.\n\n If the query does not seem to be an OpenID request at all, I return\n C{None}.\n\n @param query: The query parameters as a dictionary with each\n key mapping to one value.\n @type query: dict\n\n @raises Protoc...
Please provide a description of the function: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.\n\n @raises ProtocolError: This implementation always raises\n L{ProtocolError}.\n " ]
Please provide a description of the function:def handleRequest(self, request): handler = getattr(self, 'openid_' + request.mode, None) if handler is not None: return handler(request) else: raise NotImplementedError( "%s has no handler for a reques...
[ "Handle a request.\n\n Give me a request, I will give you a response. Unless it's a type\n of request I cannot handle myself, in which case I will raise\n C{NotImplementedError}. In that case, you can handle it yourself,\n or add a method to me for handling that request type.\n\n ...
Please provide a description of the function:def openid_associate(self, request): # XXX: TESTME assoc_type = request.assoc_type session_type = request.session.session_type if self.negotiator.isAllowed(assoc_type, session_type): assoc = self.signatory.createAssociatio...
[ "Handle and respond to C{associate} requests.\n\n @returntype: L{OpenIDResponse}\n " ]
Please provide a description of the function: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: ...
[ "Generate a Message object for sending to the relying party,\n after encoding.\n " ]
Please provide a description of the function:def whichEncoding(self): if self.hasReturnTo(): if self.openid_message.isOpenID1() and \ len(self.encodeToURL()) > OPENID1_URL_LIMIT: return ENCODE_HTML_FORM else: return ENCODE_URL ...
[ "How should I be encoded?\n\n @returns: one of ENCODE_URL, ENCODE_KVFORM, or None. If None,\n I cannot be encoded as a protocol message and should be\n displayed to the user.\n " ]
Please provide a description of the function:def startOpenID(request): if request.POST: # Start OpenID authentication. openid_url = request.POST['openid_identifier'] c = getConsumer(request) error = None try: auth_request = c.begin(openid_url) except...
[ "\n Start the OpenID authentication process. Renders an\n authentication form and accepts its POST.\n\n * Renders an error message if OpenID cannot be initiated\n\n * Requests some Simple Registration data using the OpenID\n library's Simple Registration machinery\n\n * Generates the appropriat...
Please provide a description of the function:def rpXRDS(request): return util.renderXRDS( request, [RP_RETURN_TO_URL_TYPE], [util.getViewURL(request, finishOpenID)])
[ "\n Return a relying party verification XRDS document\n " ]
Please provide a description of the function: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) ...
[ "Return the existing session or a new session" ]
Please provide a description of the function:def do_GET(self): try: self.parsed_uri = urlparse.urlparse(self.path) self.query = {} for k, v in cgi.parse_qsl(self.parsed_uri[4]): self.query[k] = v.decode('utf-8') path = self.parsed_uri[2] ...
[ "Dispatching logic. There are three paths defined:\n\n / - Display an empty form asking for an identity URL to\n verify\n /verify - Handle form submission, initiating OpenID verification\n /process - Handle a redirect from an OpenID server\n\n Any other path gets a 404...
Please provide a description of the function: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 ab...
[ "Handle the redirect from the OpenID server.\n " ]
Please provide a description of the function:def doAffiliate(self): sreg_req = sreg.SRegRequest(['nickname'], ['fullname', 'email']) href = sreg_req.toMessage().toURL(OPENID_PROVIDER_URL) message = % ( quoteattr(href), OPENID_PROVIDER_NAME) self.render(message)
[ "Direct the user sign up with an affiliate OpenID provider.", "Get an OpenID at <a href=%s>%s</a>" ]
Please provide a description of the function:def buildURL(self, action, **query): base = urlparse.urljoin(self.server.base_url, action) return appendArgs(base, query)
[ "Build a URL relative to the server base_url, with the given\n query parameters added." ]
Please provide a description of the function: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." ]
Please provide a description of the function: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 mess...
[ "Render a page." ]
Please provide a description of the function:def pageHeader(self, title): self.setSessionCookie() self.wfile.write('''\ Content-type: text/html; charset=UTF-8 <html> <head><title>%s</title></head> <style type="text/css"> * { font-family: verdana,sans-serif; } body...
[ "Render the page header" ]
Please provide a description of the function:def pageFooter(self, form_contents): if not form_contents: form_contents = '' self.wfile.write('''\ <div id="verify-form"> <form method="get" accept-charset="UTF-8" action=%s> Identifier: <input type="text" name...
[ "Render the page footer" ]
Please provide a description of the function: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: ...
[ "Execute the given function inside of a transaction, with an\n open cursor. If no exception is raised, the transaction is\n comitted, otherwise it is rolled back." ]
Please provide a description of the function: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.\n\n Association -> NoneType\n " ]
Please provide a description of the function: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,\n returning whether the association existed at all.\n\n (str, str) -> bool\n " ]
Please provide a description of the function:def txn_useNonce(self, server_url, timestamp, salt): if abs(timestamp - time.time()) > nonce.SKEW: return False try: self.db_add_nonce(server_url, timestamp, salt) except self.exceptions.IntegrityError: # ...
[ "Return whether this nonce is present, and if it is, then\n remove it from the set.\n\n str -> bool" ]
Please provide a description of the function:def db_set_assoc(self, server_url, handle, secret, issued, lifetime, assoc_type): result = self.db_get_assoc(server_url, handle) rows = self.cur.fetchall() if len(rows): # Update the table since this associations already exists. ...
[ "\n Set an association. This is implemented as a method because\n REPLACE INTO is not supported by PostgreSQL (and is not\n standard SQL).\n " ]
Please provide a description of the function: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.\n " ]
Please provide a description of the function: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." ]
Please provide a description of the function: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?\n\n @returntype: bool\n " ]
Please provide a description of the function: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 ...
[ "Return the root authority for an XRI.\n\n Example::\n\n rootAuthority(\"xri://@example\") == \"xri://@\"\n\n @type xri: unicode\n @returntype: unicode\n " ]
Please provide a description of the function: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, s...
[ "Add the arguments from this extension to the provided\n message, or create a new message containing only those\n arguments.\n\n @returns: The message with the extension arguments added\n " ]
Please provide a description of the function: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\n exists, make sure that it is, in fact, a directory.\n\n Can raise OSError\n\n str -> NoneType\n " ]
Please provide a description of the function: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\n exist.\n\n () -> NoneType\n " ]
Please provide a description of the function: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\n self.association_dir.\n\n The temporary directory should not be cleaned if there are any\n processes using the store. If there is no active process using\n the store, it is safe to remove all of the files in the\n temporary dire...
Please provide a description of the function: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]) ...
[ "Create a unique filename for a given server url and\n handle. This implementation does not assume anything about the\n format of the handle. The filename that is returned will\n contain the domain name from the server URL for ease of human\n inspection of the data directory.\n\n ...
Please provide a description of the function: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.getAssociationFilena...
[ "Retrieve an association. If no handle is specified, return\n the association with the latest expiration.\n\n (str, str or NoneType) -> Association or NoneType\n " ]
Please provide a description of the function: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 _removeIfP...
[ "Remove an association if it exists. Do nothing if it does not.\n\n (str, str) -> bool\n " ]
Please provide a description of the function: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 ...
[ "Return whether this nonce is valid.\n\n str -> bool\n " ]
Please provide a description of the function:def findOPLocalIdentifier(service_element, type_uris): # XXX: Test this function on its own! # Build the list of tags that could contain the OP-Local Identifier local_id_tags = [] if (OPENID_1_1_TYPE in type_uris or OPENID_1_0_TYPE in type_uris)...
[ "Find the OP-Local Identifier for this xrd:Service element.\n\n This considers openid:Delegate to be a synonym for xrd:LocalID if\n both OpenID 1.X and OpenID 2.0 types are present. If only OpenID\n 1.X is present, it returns the value of openid:Delegate. If only\n OpenID 2.0 is present, it returns the ...
Please provide a description of the function:def normalizeURL(url): try: normalized = urinorm.urinorm(url) except ValueError, why: raise DiscoveryFailure('Normalizing identifier: %s' % (why[0],), None) else: return urlparse.urldefrag(normalized)[0]
[ "Normalize a URL, converting normalization failures to\n DiscoveryFailure" ]
Please provide a description of the function:def arrangeByType(service_list, preferred_types): def enumerate(elts): return zip(range(len(elts)), elts) def bestMatchingService(service): for i, t in enumerate(preferred_types): if preferred_types[i] in service.t...
[ "Rearrange service_list in a new list so services are ordered by\n types listed in preferred_types. Return the new list.", "Return an iterable that pairs the index of an element with\n that element.\n\n For Python 2.2 compatibility", "Return the index of the first matching type, or something\n...
Please provide a description of the function: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 o...
[ "Extract OP Identifier services. If none found, return the\n rest, sorted with most preferred first according to\n OpenIDServiceEndpoint.openid_type_uris.\n\n openid_services is a list of OpenIDServiceEndpoint objects.\n\n Returns a list of OpenIDServiceEndpoint objects." ]
Please provide a description of the function:def discoverYadis(uri): # Might raise a yadis.discover.DiscoveryFailure if no document # came back for that URI at all. I don't think falling back # to OpenID 1.0 discovery on the same URL will help, so don't # bother to catch it. response = yadisDi...
[ "Discover OpenID services for a URI. Tries Yadis and falls back\n on old-style <link rel='...'> discovery if Yadis fails.\n\n @param uri: normalized identity URL\n @type uri: str\n\n @return: (claimed_id, services)\n @rtype: (str, list(OpenIDServiceEndpoint))\n\n @raises DiscoveryFailure: when dis...
Please provide a description of the function: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?\n\n I consider C{/server} endpoints to implicitly support C{/signon}.\n " ]
Please provide a description of the function:def getDisplayIdentifier(self): if self.display_identifier is not None: return self.display_identifier if self.claimed_id is None: return None else: return urlparse.urldefrag(self.claimed_id)[0]
[ "Return the display_identifier if set, else return the claimed_id.\n " ]
Please provide a description of the function: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 ele...
[ "Set the state of this object based on the contents of the\n service element." ]
Please provide a description of the function: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 we...
[ "Return the identifier that should be sent as the\n openid.identity parameter to the server." ]
Please provide a description of the function: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 no...
[ "Create a new instance of this class from the endpoint\n object passed in.\n\n @return: None or OpenIDServiceEndpoint for this endpoint object" ]
Please provide a description of the function:def fromHTML(cls, uri, html): discovery_types = [ (OPENID_2_0_TYPE, 'openid2.provider', 'openid2.local_id'), (OPENID_1_1_TYPE, 'openid.server', 'openid.delegate'), ] link_attrs = html_parse.parseLinkAttrs(html) ...
[ "Parse the given document as HTML looking for an OpenID <link\n rel=...>\n\n @rtype: [OpenIDServiceEndpoint]\n " ]
Please provide a description of the function:def fromDiscoveryResult(cls, discoveryResult): if discoveryResult.isXRDS(): method = cls.fromXRDS else: method = cls.fromHTML return method(discoveryResult.normalized_uri, discoveryResult.response...
[ "Create endpoints from a DiscoveryResult.\n\n @type discoveryResult: L{DiscoveryResult}\n\n @rtype: list of L{OpenIDServiceEndpoint}\n\n @raises XRDSError: When the XRDS does not parse.\n\n @since: 2.1.0\n " ]
Please provide a description of the function: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\n a given OP Endpoint URL\n\n @param op_endpoint_url: The URL of the endpoint\n @rtype: OpenIDServiceEndpoint\n " ]
Please provide a description of the function: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\n each combination is valid." ]
Please provide a description of the function:def addAllowedType(self, assoc_type, session_type=None): if self.allowed_types is None: self.allowed_types = [] if session_type is None: available = getSessionTypes(assoc_type) if not available: r...
[ "Add an association type and session type to the allowed\n types list. The assocation/session pairs are tried in the\n order that they are added." ]
Please provide a description of the function: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?" ]
Please provide a description of the function:def fromExpiresIn(cls, expires_in, handle, secret, assoc_type): issued = int(time.time()) lifetime = expires_in return cls(handle, secret, issued, lifetime, assoc_type)
[ "\n This is an alternate constructor used by the OpenID consumer\n library to create associations. C{L{OpenIDStore\n <openid.store.interface.OpenIDStore>}} implementations\n shouldn't use this constructor.\n\n\n @param expires_in: This is the amount of time this association\n ...
Please provide a description of the function:def getExpiresIn(self, now=None): if now is None: now = int(time.time()) return max(0, self.issued + self.lifetime - now)
[ "\n This returns the number of seconds this association is still\n valid for, or C{0} if the association is no longer valid.\n\n\n @return: The number of seconds this association is still valid\n for, or C{0} if the association is no longer valid.\n\n @rtype: C{int}\n "...
Please provide a description of the function: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...
[ "\n Convert an association to KV form.\n\n @return: String in KV form suitable for deserialization by\n deserialize.\n\n @rtype: str\n " ]
Please provide a description of the function:def deserialize(cls, assoc_s): pairs = kvform.kvToSeq(assoc_s, strict=True) keys = [] values = [] for k, v in pairs: keys.append(k) values.append(v) if keys != cls.assoc_keys: raise ValueEr...
[ "\n Parse an association as stored by serialize().\n\n inverse of serialize\n\n\n @param assoc_s: Association as serialized by serialize()\n\n @type assoc_s: str\n\n\n @return: instance of this class\n " ]
Please provide a description of the function:def sign(self, pairs): kv = kvform.seqToKV(pairs) try: mac = self._macs[self.assoc_type] except KeyError: raise ValueError( 'Unknown association type: %r' % (self.assoc_type,)) return mac(self...
[ "\n Generate a signature for a sequence of (key, value) pairs\n\n\n @param pairs: The pairs to sign, in order\n\n @type pairs: sequence of (str, str)\n\n\n @return: The binary signature of this sequence of pairs\n\n @rtype: str\n " ]
Please provide a description of the function:def getMessageSignature(self, message): pairs = self._makePairs(message) return oidutil.toBase64(self.sign(pairs))
[ "Return the signature of a message.\n\n If I am not a sign-all association, the message must have a\n signed list.\n\n @return: the signature, base64 encoded\n\n @rtype: str\n\n @raises ValueError: If there is no signed list and I am not a sign-all\n type of association...
Please provide a description of the function:def signMessage(self, message): if (message.hasKey(OPENID_NS, 'sig') or message.hasKey(OPENID_NS, 'signed')): raise ValueError('Message already has signed list or signature') extant_handle = message.getArg(OPENID_NS, 'assoc_h...
[ "Add a signature (and a signed list) to a message.\n\n @return: a new Message object with a signature\n @rtype: L{openid.message.Message}\n " ]
Please provide a description of the function: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 cryptut...
[ "Given a message with a signature, calculate a new signature\n and return whether it matches the signature in the message.\n\n @raises ValueError: if the message has no signature or no signature\n can be calculated for it.\n " ]
Please provide a description of the function: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\n\n This method is intended to be used by the relying party to add\n acceptable authentication types to the request.\n\n @param policy_uri: The identifier for the preferred type of\n authentication.\n @see: http://op...
Please provide a description of the function:def parseExtensionArgs(self, args): # preferred_auth_policies is a space-separated list of policy URIs self.preferred_auth_policies = [] policies_str = args.get('preferred_auth_policies') if policies_str: for uri in poli...
[ "Set the state of this request to be that expressed in these\n PAPE arguments\n\n @param args: The PAPE arguments without a namespace\n\n @rtype: None\n\n @raises ValueError: When the max_auth_age is not parseable as\n an integer\n " ]
Please provide a description of the function:def addPolicyURI(self, policy_uri): if policy_uri not in self.auth_policies: self.auth_policies.append(policy_uri)
[ "Add a authentication policy to this response\n\n This method is intended to be used by the provider to add a\n policy that the provider conformed to when authenticating the user.\n\n @param policy_uri: The identifier for the preferred type of\n authentication.\n @see: http://...
Please provide a description of the function:def fromSuccessResponse(cls, success_response): self = cls() # PAPE requires that the args be signed. args = success_response.getSignedNS(self.ns_uri) # Only try to construct a PAPE response if the arguments were # signed in...
[ "Create a C{L{Response}} object from a successful OpenID\n library response\n (C{L{openid.consumer.consumer.SuccessResponse}}) response\n message\n\n @param success_response: A SuccessResponse from consumer.complete()\n @type success_response: C{L{openid.consumer.consumer.SuccessR...
Please provide a description of the function:def parseExtensionArgs(self, args, strict=False): policies_str = args.get('auth_policies') if policies_str and policies_str != 'none': self.auth_policies = policies_str.split(' ') nist_level_str = args.get('nist_auth_level') ...
[ "Parse the provider authentication policy arguments into the\n internal state of this object\n\n @param args: unqualified provider authentication policy\n arguments\n\n @param strict: Whether to raise an exception when bad data is\n encountered\n\n @returns: None. T...
Please provide a description of the function: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_...
[ "Add an auth level URI alias to this request.\n\n @param auth_level_uri: The auth level URI to send in the\n request.\n\n @param alias: The namespace alias to use for this auth level\n in this message. May be None if the alias is not\n important.\n " ]
Please provide a description of the function:def _generateAlias(self): for i in xrange(1000): alias = 'cust%d' % (i,) if alias not in self.auth_level_aliases: return alias raise RuntimeError('Could not find an unused alias (tried 1000!)')
[ "Return an unused auth level alias" ]
Please provide a description of the function:def _getAlias(self, auth_level_uri): for (alias, existing_uri) in self.auth_level_aliases.iteritems(): if auth_level_uri == existing_uri: return alias raise KeyError(auth_level_uri)
[ "Return the alias for the specified auth level URI.\n\n @raises KeyError: if no alias is defined\n " ]
Please provide a description of the function:def fromOpenIDRequest(cls, request): self = cls() args = request.message.getArgs(self.ns_uri) is_openid1 = request.message.isOpenID1() if args == {}: return None self.parseExtensionArgs(args, is_openid1) ...
[ "Instantiate a Request object from the arguments in a\n C{checkid_*} OpenID message\n " ]
Please provide a description of the function:def parseExtensionArgs(self, args, is_openid1, strict=False): # preferred_auth_policies is a space-separated list of policy URIs self.preferred_auth_policies = [] policies_str = args.get('preferred_auth_policies') if policies_str: ...
[ "Set the state of this request to be that expressed in these\n PAPE arguments\n\n @param args: The PAPE arguments without a namespace\n\n @param strict: Whether to raise an exception if the input is\n out of spec or otherwise malformed. If strict is false,\n malformed inpu...
Please provide a description of the function: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.\n\n @param level: string representation of an authentication level\n valid for level_uri\n\n @param alias: An optional namespace alias for the given auth\n level URI. May be omitted if the alias is not\n significant. The li...
Please provide a description of the function:def addPolicyURI(self, policy_uri): if policy_uri == AUTH_NONE: raise RuntimeError( 'To send no policies, do not set any on the response.') if policy_uri not in self.auth_policies: self.auth_policies.append(po...
[ "Add a authentication policy to this response\n\n This method is intended to be used by the provider to add a\n policy that the provider conformed to when authenticating the user.\n\n @param policy_uri: The identifier for the preferred type of\n authentication.\n @see: http://...
Please provide a description of the function:def parseExtensionArgs(self, args, is_openid1, strict=False): policies_str = args.get('auth_policies') if policies_str: auth_policies = policies_str.split(' ') elif strict: raise ValueError('Missing auth_policies') ...
[ "Parse the provider authentication policy arguments into the\n internal state of this object\n\n @param args: unqualified provider authentication policy\n arguments\n\n @param strict: Whether to raise an exception when bad data is\n encountered\n\n @returns: None. T...
Please provide a description of the function: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. ' ...
[ "Discover services for a given URI.\n\n @param uri: The identity URI as a well-formed http or https\n URI. The well-formedness and the protocol are not checked, but\n the results of this function are undefined if those properties\n do not hold.\n\n @return: DiscoveryResult object\n\n @...
Please provide a description of the function: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 ...
[ "Given a HTTPResponse, return the location of the Yadis document.\n\n May be the URL just retrieved, another URL, or None, if I can't\n find any.\n\n [non-blocking]\n\n @returns: str or None\n " ]
Please provide a description of the function:def server(request): return direct_to_template( request, 'server/index.html', {'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds), })
[ "\n Respond to requests for the server's primary web page.\n " ]
Please provide a description of the function: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 Pro...
[ "\n Respond to low-level OpenID protocol messages.\n " ]
Please provide a description of the function:def handleCheckIDRequest(request, openid_request): # If the request was an IDP-driven identifier selection request # (i.e., the IDP URL was entered at the RP), then return the # default identity URL for this server. In a full-featured # provider, there c...
[ "\n Handle checkid_* requests. Get input from the user to find out\n whether she trusts the RP involved. Possibly, get intput about\n what Simple Registration information, if any, to send in the\n response.\n " ]
Please provide a description of the function: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, r...
[ "\n Render a page to the user so a trust decision can be made.\n\n @type openid_request: openid.server.server.CheckIDRequest\n " ]
Please provide a description of the function: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) ...
[ "\n Handle the result of a trust decision and respond to the RP\n accordingly.\n " ]
Please provide a description of the function:def displayResponse(request, openid_response): s = getServer(request) # Encode the response into something that is renderable. try: webresponse = s.encodeResponse(openid_response) except EncodingError, why: # If it couldn't be encoded, d...
[ "\n Display an OpenID response. Errors will be displayed directly to\n the user; successful responses and other protocol-level messages\n will be sent using the proper mechanism (i.e., direct response,\n redirection, etc.).\n " ]
Please provide a description of the function: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, ...
[ "Convert all files in a directory to apache mod_asis files in\n another directory." ]
Please provide a description of the function: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.\n\n or None if there are no associations.\n " ]
Please provide a description of the function:def cleanup(self): remove = [] for handle, assoc in self.assocs.iteritems(): if assoc.getExpiresIn() == 0: remove.append(handle) for handle in remove: del self.assocs[handle] return len(remove),...
[ "Remove expired associations.\n\n @return: tuple of (removed associations, remaining associations)\n " ]
Please provide a description of the function: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 ran...
[ "Extract a timestamp from the given nonce string\n\n @param nonce_string: the nonce from which to extract the timestamp\n @type nonce_string: str\n\n @returns: A pair of a Unix timestamp and the salt characters\n @returntype: (int, str)\n\n @raises ValueError: if the nonce does not start with a corre...
Please provide a description of the function: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 ...
[ "Is the timestamp that is part of the specified nonce string\n within the allowed clock-skew of the current time?\n\n @param nonce_string: The nonce that is being checked\n @type nonce_string: str\n\n @param allowed_skew: How many seconds should be allowed for\n completing the request, allowing f...
Please provide a description of the function: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\n\n @param when: Unix timestamp representing the issue time of the\n nonce. Defaults to the current time.\n @type when: int\n\n @returntype: str\n @returns: A string that should be usable as a one-way nonce\n\n @see: time\n " ]
Please provide a description of the function: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\n should need only this method.\n\n @raises Exception: any exceptions that may be raised by the default fetcher\n " ]
Please provide a description of the function: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\n\n @param fetcher: The fetcher to use as the default HTTP fetcher\n @type fetcher: HTTPFetcher\n\n @param wrap_exceptions: Whether to wrap exceptions thrown by the\n fetcher wil HTTPFetchingError so that they may be caught\n easier. By default, exceptions will be wra...
Please provide a description of the function: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." ]
Please provide a description of the function: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 ...
[ "Perform an HTTP request\n\n @raises Exception: Any exception that can be raised by httplib2\n\n @see: C{L{HTTPFetcher.fetch}}\n " ]
Please provide a description of the function: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), ...
[ "Perform the Yadis protocol on the input URL and return an\n iterable of resulting endpoint objects.\n\n @param flt: A filter object or something that is convertable to\n a filter object (using mkFilter) that will be used to generate\n endpoint objects. This defaults to generating BasicEndpoint\...
Please provide a description of the function: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)) ...
[ "Generate an iterable of endpoint objects given this input data,\n presumably from the result of performing the Yadis protocol.\n\n @param normalized_uri: The input URL, after following redirects,\n as in the Yadis protocol.\n\n\n @param xrd_data: The XML text the XRDS file fetched from the\n ...
Please provide a description of the function:def seqToKV(seq, strict=False): def err(msg): formatted = 'seqToKV warning: %s: %r' % (msg, seq) if strict: raise KVFormError(formatted) else: logging.warn(formatted) lines = [] for k, v in seq: if isi...
[ "Represent a sequence of pairs of strings as newline-terminated\n key:value pairs. The pairs are generated in the order given.\n\n @param seq: The pairs\n @type seq: [(str, (unicode|str))]\n\n @return: A string representation of the sequence\n @rtype: str\n " ]
Please provide a description of the function: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, st...
[ "Find all link tags in a string representing a HTML document and\n return a list of their attributes.\n\n @param html: the text to parse\n @type html: str or unicode\n\n @return: A list of dictionaries of attributes, one for each link tag\n @rtype: [[(type(html), type(html))]]\n " ]
Please provide a description of the function: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?" ]
Please provide a description of the function: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?" ]
Please provide a description of the function: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\n in the list that has target_rel as a relationship." ]
Please provide a description of the function:def getOpenIDStore(filestore_path, table_prefix): if not settings.DATABASES.get('default', {'ENGINE':None}).get('ENGINE'): return FileOpenIDStore(filestore_path) # Possible side-effect: create a database connection if one isn't # already open. c...
[ "\n Returns an OpenID association store object based on the database\n engine chosen for this Django application.\n\n * If no database engine is chosen, a filesystem-based store will\n be used whose path is filestore_path.\n\n * If a database engine is chosen, a store object for that database\n ...
Please provide a description of the function:def getBaseURL(req): name = req.META['HTTP_HOST'] try: name = name[:name.index(':')] except: pass try: port = int(req.META['SERVER_PORT']) except: port = 80 proto = req.META['SERVER_PROTOCOL'] if 'HTTPS' in ...
[ "\n Given a Django web request object, returns the OpenID 'trust root'\n for that request; namely, the absolute URL to the site root which\n is serving the Django request. The trust root will include the\n proper scheme and authority. It will lack a port if the port is\n standard (80, 443).\n " ...
Please provide a description of the function:def renderXRDS(request, type_uris, endpoint_urls): response = direct_to_template( request, 'xrds.xml', {'type_uris':type_uris, 'endpoint_urls':endpoint_urls,}) response['Content-Type'] = YADIS_CONTENT_TYPE return response
[ "Render an XRDS page with the specified type URIs and endpoint\n URLs in one service block, and return a response with the\n appropriate content-type.\n " ]
Please provide a description of the function: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: ...
[ "Find a working ElementTree implementation, trying the standard\n places that such a thing might show up.\n\n >>> ElementTree = importElementTree()\n\n @param module_names: The names of modules to try to use as\n ElementTree. Defaults to C{L{elementtree_modules}}\n\n @returns: An ElementTree modu...