repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
openid/python-openid | openid/yadis/manager.py | Discovery.getManager | def getManager(self, force=False):
"""Extract the YadisServiceManager for this object's URL and
suffix from the session.
@param force: True if the manager should be returned
regardless of whether it's a manager for self.url.
@return: The current YadisServiceManager, if it's for this
URL, or else None
"""
manager = self.session.get(self.getSessionKey())
if (manager is not None and (manager.forURL(self.url) or force)):
return manager
else:
return None | python | def getManager(self, force=False):
"""Extract the YadisServiceManager for this object's URL and
suffix from the session.
@param force: True if the manager should be returned
regardless of whether it's a manager for self.url.
@return: The current YadisServiceManager, if it's for this
URL, or else None
"""
manager = self.session.get(self.getSessionKey())
if (manager is not None and (manager.forURL(self.url) or force)):
return manager
else:
return None | [
"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.
@param force: True if the manager should be returned
regardless of whether it's a manager for self.url.
@return: The current YadisServiceManager, if it's for this
URL, or else None | [
"Extract",
"the",
"YadisServiceManager",
"for",
"this",
"object",
"s",
"URL",
"and",
"suffix",
"from",
"the",
"session",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L146-L160 | train |
openid/python-openid | openid/yadis/manager.py | Discovery.createManager | def createManager(self, services, yadis_url=None):
"""Create a new YadisService Manager for this starting URL and
suffix, and store it in the session.
@raises KeyError: When I already have a manager.
@return: A new YadisServiceManager or 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 | python | def createManager(self, services, yadis_url=None):
"""Create a new YadisService Manager for this starting URL and
suffix, and store it in the session.
@raises KeyError: When I already have a manager.
@return: A new YadisServiceManager or 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 | [
"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.
@raises KeyError: When I already have a manager.
@return: A new YadisServiceManager or None | [
"Create",
"a",
"new",
"YadisService",
"Manager",
"for",
"this",
"starting",
"URL",
"and",
"suffix",
"and",
"store",
"it",
"in",
"the",
"session",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L162-L180 | train |
openid/python-openid | openid/yadis/manager.py | Discovery.destroyManager | def destroyManager(self, force=False):
"""Delete any YadisServiceManager with this starting URL and
suffix from the session.
If there is no service manager or the service manager is for a
different URL, it silently does nothing.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url.
"""
if self.getManager(force=force) is not None:
key = self.getSessionKey()
del self.session[key] | python | def destroyManager(self, force=False):
"""Delete any YadisServiceManager with this starting URL and
suffix from the session.
If there is no service manager or the service manager is for a
different URL, it silently does nothing.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url.
"""
if self.getManager(force=force) is not None:
key = self.getSessionKey()
del self.session[key] | [
"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.
If there is no service manager or the service manager is for a
different URL, it silently does nothing.
@param force: True if the manager should be deleted regardless
of whether it's a manager for self.url. | [
"Delete",
"any",
"YadisServiceManager",
"with",
"this",
"starting",
"URL",
"and",
"suffix",
"from",
"the",
"session",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/manager.py#L182-L194 | train |
openid/python-openid | openid/dh.py | DiffieHellman._setPrivate | def _setPrivate(self, private):
"""This is here to make testing easier"""
self.private = private
self.public = pow(self.generator, self.private, self.modulus) | python | def _setPrivate(self, private):
"""This is here to make testing easier"""
self.private = private
self.public = pow(self.generator, self.private, self.modulus) | [
"def",
"_setPrivate",
"(",
"self",
",",
"private",
")",
":",
"self",
".",
"private",
"=",
"private",
"self",
".",
"public",
"=",
"pow",
"(",
"self",
".",
"generator",
",",
"self",
".",
"private",
",",
"self",
".",
"modulus",
")"
] | This is here to make testing easier | [
"This",
"is",
"here",
"to",
"make",
"testing",
"easier"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/dh.py#L27-L30 | train |
openid/python-openid | openid/server/server.py | AssociateRequest.answerUnsupported | def answerUnsupported(self, message, preferred_association_type=None,
preferred_session_type=None):
"""Respond to this request indicating that the association
type or association session type is not supported."""
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 | python | def answerUnsupported(self, message, preferred_association_type=None,
preferred_session_type=None):
"""Respond to this request indicating that the association
type or association session type is not supported."""
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 | [
"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. | [
"Respond",
"to",
"this",
"request",
"indicating",
"that",
"the",
"association",
"type",
"or",
"association",
"session",
"type",
"is",
"not",
"supported",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L486-L505 | train |
openid/python-openid | openid/server/server.py | CheckIDRequest.fromMessage | def fromMessage(klass, message, op_endpoint):
"""Construct me from an OpenID message.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When the C{return_to} URL is outside
the C{trust_root}.
@param message: An OpenID checkid_* request Message
@type message: openid.message.Message
@param op_endpoint: The endpoint URL of the server that this
message was sent to.
@type op_endpoint: str
@returntype: L{CheckIDRequest}
"""
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 | python | def fromMessage(klass, message, op_endpoint):
"""Construct me from an OpenID message.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When the C{return_to} URL is outside
the C{trust_root}.
@param message: An OpenID checkid_* request Message
@type message: openid.message.Message
@param op_endpoint: The endpoint URL of the server that this
message was sent to.
@type op_endpoint: str
@returntype: L{CheckIDRequest}
"""
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 | [
"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.
@raises ProtocolError: When not all required parameters are present
in the message.
@raises MalformedReturnURL: When the C{return_to} URL is not a URL.
@raises UntrustedReturnURL: When the C{return_to} URL is outside
the C{trust_root}.
@param message: An OpenID checkid_* request Message
@type message: openid.message.Message
@param op_endpoint: The endpoint URL of the server that this
message was sent to.
@type op_endpoint: str
@returntype: L{CheckIDRequest} | [
"Construct",
"me",
"from",
"an",
"OpenID",
"message",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L580-L672 | train |
openid/python-openid | openid/server/server.py | CheckIDRequest.trustRootValid | def trustRootValid(self):
"""Is my return_to under my trust_root?
@returntype: bool
"""
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 | python | def trustRootValid(self):
"""Is my return_to under my trust_root?
@returntype: bool
"""
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 | [
"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?
@returntype: bool | [
"Is",
"my",
"return_to",
"under",
"my",
"trust_root?"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L684-L698 | train |
openid/python-openid | openid/server/server.py | CheckIDRequest.encodeToURL | def encodeToURL(self, server_url):
"""Encode this request as a URL to GET.
@param server_url: The URL of the OpenID server to make this request of.
@type server_url: str
@returntype: str
@raises NoReturnError: when I do not have a return_to.
"""
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) | python | def encodeToURL(self, server_url):
"""Encode this request as a URL to GET.
@param server_url: The URL of the OpenID server to make this request of.
@type server_url: str
@returntype: str
@raises NoReturnError: when I do not have a return_to.
"""
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) | [
"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.
@param server_url: The URL of the OpenID server to make this request of.
@type server_url: str
@returntype: str
@raises NoReturnError: when I do not have a return_to. | [
"Encode",
"this",
"request",
"as",
"a",
"URL",
"to",
"GET",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L883-L914 | train |
openid/python-openid | openid/server/server.py | CheckIDRequest.getCancelURL | def getCancelURL(self):
"""Get the URL to cancel this request.
Useful for creating a "Cancel" button on a web form so that operation
can be carried out directly without another trip through the server.
(Except you probably want to make another trip through the server so
that it knows that the user did make a decision. Or you could simulate
this method by doing C{.answer(False).encodeToURL()})
@returntype: str
@returns: The return_to URL with openid.mode = cancel.
@raises NoReturnError: when I do not have a return_to.
"""
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) | python | def getCancelURL(self):
"""Get the URL to cancel this request.
Useful for creating a "Cancel" button on a web form so that operation
can be carried out directly without another trip through the server.
(Except you probably want to make another trip through the server so
that it knows that the user did make a decision. Or you could simulate
this method by doing C{.answer(False).encodeToURL()})
@returntype: str
@returns: The return_to URL with openid.mode = cancel.
@raises NoReturnError: when I do not have a return_to.
"""
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) | [
"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.
Useful for creating a "Cancel" button on a web form so that operation
can be carried out directly without another trip through the server.
(Except you probably want to make another trip through the server so
that it knows that the user did make a decision. Or you could simulate
this method by doing C{.answer(False).encodeToURL()})
@returntype: str
@returns: The return_to URL with openid.mode = cancel.
@raises NoReturnError: when I do not have a return_to. | [
"Get",
"the",
"URL",
"to",
"cancel",
"this",
"request",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L917-L941 | train |
openid/python-openid | openid/server/server.py | OpenIDResponse.toFormMarkup | def toFormMarkup(self, form_tag_attrs=None):
"""Returns the form markup for this response.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@returntype: str
@since: 2.1.0
"""
return self.fields.toFormMarkup(self.request.return_to,
form_tag_attrs=form_tag_attrs) | python | def toFormMarkup(self, form_tag_attrs=None):
"""Returns the form markup for this response.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@returntype: str
@since: 2.1.0
"""
return self.fields.toFormMarkup(self.request.return_to,
form_tag_attrs=form_tag_attrs) | [
"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.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@returntype: str
@since: 2.1.0 | [
"Returns",
"the",
"form",
"markup",
"for",
"this",
"response",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L990-L1003 | train |
openid/python-openid | openid/server/server.py | Signatory.verify | def verify(self, assoc_handle, message):
"""Verify that the signature for some data is valid.
@param assoc_handle: The handle of the association used to sign the
data.
@type assoc_handle: str
@param message: The signed message to verify
@type message: openid.message.Message
@returns: C{True} if the signature is valid, C{False} if not.
@returntype: bool
"""
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 | python | def verify(self, assoc_handle, message):
"""Verify that the signature for some data is valid.
@param assoc_handle: The handle of the association used to sign the
data.
@type assoc_handle: str
@param message: The signed message to verify
@type message: openid.message.Message
@returns: C{True} if the signature is valid, C{False} if not.
@returntype: bool
"""
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 | [
"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.
@param assoc_handle: The handle of the association used to sign the
data.
@type assoc_handle: str
@param message: The signed message to verify
@type message: openid.message.Message
@returns: C{True} if the signature is valid, C{False} if not.
@returntype: bool | [
"Verify",
"that",
"the",
"signature",
"for",
"some",
"data",
"is",
"valid",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1159-L1186 | train |
openid/python-openid | openid/server/server.py | Signatory.sign | def sign(self, response):
"""Sign a response.
I take a L{OpenIDResponse}, create a signature for everything
in its L{signed<OpenIDResponse.signed>} list, and return a new
copy of the response object with that signature included.
@param response: A response to sign.
@type response: L{OpenIDResponse}
@returns: A signed copy of the response.
@returntype: L{OpenIDResponse}
"""
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 | python | def sign(self, response):
"""Sign a response.
I take a L{OpenIDResponse}, create a signature for everything
in its L{signed<OpenIDResponse.signed>} list, and return a new
copy of the response object with that signature included.
@param response: A response to sign.
@type response: L{OpenIDResponse}
@returns: A signed copy of the response.
@returntype: L{OpenIDResponse}
"""
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 | [
"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.
I take a L{OpenIDResponse}, create a signature for everything
in its L{signed<OpenIDResponse.signed>} list, and return a new
copy of the response object with that signature included.
@param response: A response to sign.
@type response: L{OpenIDResponse}
@returns: A signed copy of the response.
@returntype: L{OpenIDResponse} | [
"Sign",
"a",
"response",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1189-L1231 | train |
openid/python-openid | openid/server/server.py | Signatory.createAssociation | def createAssociation(self, dumb=True, assoc_type='HMAC-SHA1'):
"""Make a new association.
@param dumb: Is this association for a dumb-mode transaction?
@type dumb: bool
@param assoc_type: The type of association to create. Currently
there is only one type defined, C{HMAC-SHA1}.
@type assoc_type: str
@returns: the new association.
@returntype: L{openid.association.Association}
"""
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 | python | def createAssociation(self, dumb=True, assoc_type='HMAC-SHA1'):
"""Make a new association.
@param dumb: Is this association for a dumb-mode transaction?
@type dumb: bool
@param assoc_type: The type of association to create. Currently
there is only one type defined, C{HMAC-SHA1}.
@type assoc_type: str
@returns: the new association.
@returntype: L{openid.association.Association}
"""
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 | [
"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.
@param dumb: Is this association for a dumb-mode transaction?
@type dumb: bool
@param assoc_type: The type of association to create. Currently
there is only one type defined, C{HMAC-SHA1}.
@type assoc_type: str
@returns: the new association.
@returntype: L{openid.association.Association} | [
"Make",
"a",
"new",
"association",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1234-L1259 | train |
openid/python-openid | openid/server/server.py | Signatory.getAssociation | def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
"""Get the association with the specified handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with that
handle was found.
@returntype: L{openid.association.Association}
"""
# 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 | python | def getAssociation(self, assoc_handle, dumb, checkExpiration=True):
"""Get the association with the specified handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with that
handle was found.
@returntype: L{openid.association.Association}
"""
# 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 | [
"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.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
@returns: the association, or None if no valid association with that
handle was found.
@returntype: L{openid.association.Association} | [
"Get",
"the",
"association",
"with",
"the",
"specified",
"handle",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1262-L1295 | train |
openid/python-openid | openid/server/server.py | Signatory.invalidate | def invalidate(self, assoc_handle, dumb):
"""Invalidates the association with the given handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
"""
if dumb:
key = self._dumb_key
else:
key = self._normal_key
self.store.removeAssociation(key, assoc_handle) | python | def invalidate(self, assoc_handle, dumb):
"""Invalidates the association with the given handle.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool
"""
if dumb:
key = self._dumb_key
else:
key = self._normal_key
self.store.removeAssociation(key, assoc_handle) | [
"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.
@type assoc_handle: str
@param dumb: Is this association used with dumb mode?
@type dumb: bool | [
"Invalidates",
"the",
"association",
"with",
"the",
"given",
"handle",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1298-L1310 | train |
openid/python-openid | openid/server/server.py | Decoder.defaultDecoder | def defaultDecoder(self, message, server):
"""Called to decode queries when no handler for that mode is found.
@raises ProtocolError: This implementation always raises
L{ProtocolError}.
"""
mode = message.getArg(OPENID_NS, 'mode')
fmt = "Unrecognized OpenID mode %r"
raise ProtocolError(message, text=fmt % (mode,)) | python | def defaultDecoder(self, message, server):
"""Called to decode queries when no handler for that mode is found.
@raises ProtocolError: This implementation always raises
L{ProtocolError}.
"""
mode = message.getArg(OPENID_NS, 'mode')
fmt = "Unrecognized OpenID mode %r"
raise ProtocolError(message, text=fmt % (mode,)) | [
"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.
@raises ProtocolError: This implementation always raises
L{ProtocolError}. | [
"Called",
"to",
"decode",
"queries",
"when",
"no",
"handler",
"for",
"that",
"mode",
"is",
"found",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1448-L1456 | train |
openid/python-openid | openid/server/server.py | ProtocolError.toMessage | def toMessage(self):
"""Generate a Message object for sending to the relying party,
after encoding.
"""
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 | python | def toMessage(self):
"""Generate a Message object for sending to the relying party,
after encoding.
"""
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 | [
"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. | [
"Generate",
"a",
"Message",
"object",
"for",
"sending",
"to",
"the",
"relying",
"party",
"after",
"encoding",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/server/server.py#L1674-L1689 | train |
openid/python-openid | examples/djopenid/consumer/views.py | rpXRDS | def rpXRDS(request):
"""
Return a relying party verification XRDS document
"""
return util.renderXRDS(
request,
[RP_RETURN_TO_URL_TYPE],
[util.getViewURL(request, finishOpenID)]) | python | def rpXRDS(request):
"""
Return a relying party verification XRDS document
"""
return util.renderXRDS(
request,
[RP_RETURN_TO_URL_TYPE],
[util.getViewURL(request, finishOpenID)]) | [
"def",
"rpXRDS",
"(",
"request",
")",
":",
"return",
"util",
".",
"renderXRDS",
"(",
"request",
",",
"[",
"RP_RETURN_TO_URL_TYPE",
"]",
",",
"[",
"util",
".",
"getViewURL",
"(",
"request",
",",
"finishOpenID",
")",
"]",
")"
] | Return a relying party verification XRDS document | [
"Return",
"a",
"relying",
"party",
"verification",
"XRDS",
"document"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/djopenid/consumer/views.py#L213-L220 | train |
openid/python-openid | examples/consumer.py | OpenIDRequestHandler.getSession | def getSession(self):
"""Return the existing session or a new session"""
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 | python | def getSession(self):
"""Return the existing session or a new session"""
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 | [
"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 | [
"Return",
"the",
"existing",
"session",
"or",
"a",
"new",
"session"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/consumer.py#L77-L107 | train |
openid/python-openid | examples/consumer.py | OpenIDRequestHandler.doProcess | def doProcess(self):
"""Handle the redirect from the OpenID server.
"""
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) | python | def doProcess(self):
"""Handle the redirect from the OpenID server.
"""
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) | [
"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. | [
"Handle",
"the",
"redirect",
"from",
"the",
"OpenID",
"server",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/consumer.py#L222-L285 | train |
openid/python-openid | examples/consumer.py | OpenIDRequestHandler.notFound | def notFound(self):
"""Render a page with a 404 return code and a message."""
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) | python | def notFound(self):
"""Render a page with a 404 return code and a message."""
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) | [
"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. | [
"Render",
"a",
"page",
"with",
"a",
"404",
"return",
"code",
"and",
"a",
"message",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/consumer.py#L343-L348 | train |
openid/python-openid | examples/consumer.py | OpenIDRequestHandler.render | def render(self, message=None, css_class='alert', form_contents=None,
status=200, title="Python OpenID Consumer Example",
sreg_data=None, pape_data=None):
"""Render a page."""
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) | python | def render(self, message=None, css_class='alert', form_contents=None,
status=200, title="Python OpenID Consumer Example",
sreg_data=None, pape_data=None):
"""Render a page."""
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) | [
"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. | [
"Render",
"a",
"page",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/consumer.py#L350-L367 | train |
openid/python-openid | openid/store/sqlstore.py | SQLStore._callInTransaction | def _callInTransaction(self, func, *args, **kwargs):
"""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."""
# 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 | python | def _callInTransaction(self, func, *args, **kwargs):
"""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."""
# 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 | [
"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. | [
"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",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L162-L182 | train |
openid/python-openid | openid/store/sqlstore.py | SQLStore.txn_storeAssociation | def txn_storeAssociation(self, server_url, association):
"""Set the association for the server URL.
Association -> NoneType
"""
a = association
self.db_set_assoc(
server_url,
a.handle,
self.blobEncode(a.secret),
a.issued,
a.lifetime,
a.assoc_type) | python | def txn_storeAssociation(self, server_url, association):
"""Set the association for the server URL.
Association -> NoneType
"""
a = association
self.db_set_assoc(
server_url,
a.handle,
self.blobEncode(a.secret),
a.issued,
a.lifetime,
a.assoc_type) | [
"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.
Association -> NoneType | [
"Set",
"the",
"association",
"for",
"the",
"server",
"URL",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L195-L207 | train |
openid/python-openid | openid/store/sqlstore.py | SQLStore.txn_removeAssociation | def txn_removeAssociation(self, server_url, handle):
"""Remove the association for the given server URL and handle,
returning whether the association existed at all.
(str, str) -> bool
"""
self.db_remove_assoc(server_url, handle)
return self.cur.rowcount > 0 | python | def txn_removeAssociation(self, server_url, handle):
"""Remove the association for the given server URL and handle,
returning whether the association existed at all.
(str, str) -> bool
"""
self.db_remove_assoc(server_url, handle)
return self.cur.rowcount > 0 | [
"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.
(str, str) -> bool | [
"Remove",
"the",
"association",
"for",
"the",
"given",
"server",
"URL",
"and",
"handle",
"returning",
"whether",
"the",
"association",
"existed",
"at",
"all",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L243-L250 | train |
openid/python-openid | openid/store/sqlstore.py | SQLStore.txn_useNonce | def txn_useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is present, and if it is, then
remove it from the set.
str -> bool"""
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 | python | def txn_useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is present, and if it is, then
remove it from the set.
str -> bool"""
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 | [
"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.
str -> bool | [
"Return",
"whether",
"this",
"nonce",
"is",
"present",
"and",
"if",
"it",
"is",
"then",
"remove",
"it",
"from",
"the",
"set",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/sqlstore.py#L254-L269 | train |
openid/python-openid | openid/yadis/xri.py | _escape_xref | def _escape_xref(xref_match):
"""Escape things that need to be escaped if they're in a cross-reference.
"""
xref = xref_match.group()
xref = xref.replace('/', '%2F')
xref = xref.replace('?', '%3F')
xref = xref.replace('#', '%23')
return xref | python | def _escape_xref(xref_match):
"""Escape things that need to be escaped if they're in a cross-reference.
"""
xref = xref_match.group()
xref = xref.replace('/', '%2F')
xref = xref.replace('?', '%3F')
xref = xref.replace('#', '%23')
return xref | [
"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. | [
"Escape",
"things",
"that",
"need",
"to",
"be",
"escaped",
"if",
"they",
"re",
"in",
"a",
"cross",
"-",
"reference",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L79-L86 | train |
openid/python-openid | openid/yadis/xri.py | escapeForIRI | def escapeForIRI(xri):
"""Escape things that need to be escaped when transforming to an IRI."""
xri = xri.replace('%', '%25')
xri = _xref_re.sub(_escape_xref, xri)
return xri | python | def escapeForIRI(xri):
"""Escape things that need to be escaped when transforming to an IRI."""
xri = xri.replace('%', '%25')
xri = _xref_re.sub(_escape_xref, xri)
return xri | [
"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. | [
"Escape",
"things",
"that",
"need",
"to",
"be",
"escaped",
"when",
"transforming",
"to",
"an",
"IRI",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L89-L93 | train |
openid/python-openid | openid/yadis/xri.py | providerIsAuthoritative | def providerIsAuthoritative(providerID, canonicalID):
"""Is this provider ID authoritative for this XRI?
@returntype: bool
"""
# XXX: can't use rsplit until we require python >= 2.4.
lastbang = canonicalID.rindex('!')
parent = canonicalID[:lastbang]
return parent == providerID | python | def providerIsAuthoritative(providerID, canonicalID):
"""Is this provider ID authoritative for this XRI?
@returntype: bool
"""
# XXX: can't use rsplit until we require python >= 2.4.
lastbang = canonicalID.rindex('!')
parent = canonicalID[:lastbang]
return parent == providerID | [
"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?
@returntype: bool | [
"Is",
"this",
"provider",
"ID",
"authoritative",
"for",
"this",
"XRI?"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L112-L120 | train |
openid/python-openid | openid/yadis/xri.py | rootAuthority | def rootAuthority(xri):
"""Return the root authority for an XRI.
Example::
rootAuthority("xri://@example") == "xri://@"
@type xri: unicode
@returntype: unicode
"""
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) | python | def rootAuthority(xri):
"""Return the root authority for an XRI.
Example::
rootAuthority("xri://@example") == "xri://@"
@type xri: unicode
@returntype: unicode
"""
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) | [
"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.
Example::
rootAuthority("xri://@example") == "xri://@"
@type xri: unicode
@returntype: unicode | [
"Return",
"the",
"root",
"authority",
"for",
"an",
"XRI",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/xri.py#L123-L153 | train |
openid/python-openid | openid/extension.py | Extension.toMessage | def toMessage(self, message=None):
"""Add the arguments from this extension to the provided
message, or create a new message containing only those
arguments.
@returns: The message with the extension arguments added
"""
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 | python | def toMessage(self, message=None):
"""Add the arguments from this extension to the provided
message, or create a new message containing only those
arguments.
@returns: The message with the extension arguments added
"""
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 | [
"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.
@returns: The message with the extension arguments added | [
"Add",
"the",
"arguments",
"from",
"this",
"extension",
"to",
"the",
"provided",
"message",
"or",
"create",
"a",
"new",
"message",
"containing",
"only",
"those",
"arguments",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extension.py#L23-L46 | train |
openid/python-openid | openid/store/filestore.py | _ensureDir | def _ensureDir(dir_name):
"""Create dir_name as a directory if it does not exist. If it
exists, make sure that it is, in fact, a directory.
Can raise OSError
str -> NoneType
"""
try:
os.makedirs(dir_name)
except OSError, why:
if why.errno != EEXIST or not os.path.isdir(dir_name):
raise | python | def _ensureDir(dir_name):
"""Create dir_name as a directory if it does not exist. If it
exists, make sure that it is, in fact, a directory.
Can raise OSError
str -> NoneType
"""
try:
os.makedirs(dir_name)
except OSError, why:
if why.errno != EEXIST or not os.path.isdir(dir_name):
raise | [
"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.
Can raise OSError
str -> NoneType | [
"Create",
"dir_name",
"as",
"a",
"directory",
"if",
"it",
"does",
"not",
"exist",
".",
"If",
"it",
"exists",
"make",
"sure",
"that",
"it",
"is",
"in",
"fact",
"a",
"directory",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L96-L108 | train |
openid/python-openid | openid/store/filestore.py | FileOpenIDStore._setup | def _setup(self):
"""Make sure that the directories in which we store our data
exist.
() -> NoneType
"""
_ensureDir(self.nonce_dir)
_ensureDir(self.association_dir)
_ensureDir(self.temp_dir) | python | def _setup(self):
"""Make sure that the directories in which we store our data
exist.
() -> NoneType
"""
_ensureDir(self.nonce_dir)
_ensureDir(self.association_dir)
_ensureDir(self.temp_dir) | [
"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.
() -> NoneType | [
"Make",
"sure",
"that",
"the",
"directories",
"in",
"which",
"we",
"store",
"our",
"data",
"exist",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L153-L161 | train |
openid/python-openid | openid/store/filestore.py | FileOpenIDStore._mktemp | def _mktemp(self):
"""Create a temporary file on the same filesystem as
self.association_dir.
The temporary directory should not be cleaned if there are any
processes using the store. If there is no active process using
the store, it is safe to remove all of the files in the
temporary directory.
() -> (file, str)
"""
fd, name = mkstemp(dir=self.temp_dir)
try:
file_obj = os.fdopen(fd, 'wb')
return file_obj, name
except:
_removeIfPresent(name)
raise | python | def _mktemp(self):
"""Create a temporary file on the same filesystem as
self.association_dir.
The temporary directory should not be cleaned if there are any
processes using the store. If there is no active process using
the store, it is safe to remove all of the files in the
temporary directory.
() -> (file, str)
"""
fd, name = mkstemp(dir=self.temp_dir)
try:
file_obj = os.fdopen(fd, 'wb')
return file_obj, name
except:
_removeIfPresent(name)
raise | [
"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.
The temporary directory should not be cleaned if there are any
processes using the store. If there is no active process using
the store, it is safe to remove all of the files in the
temporary directory.
() -> (file, str) | [
"Create",
"a",
"temporary",
"file",
"on",
"the",
"same",
"filesystem",
"as",
"self",
".",
"association_dir",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L163-L180 | train |
openid/python-openid | openid/store/filestore.py | FileOpenIDStore.getAssociationFilename | def getAssociationFilename(self, server_url, handle):
"""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.
(str, str) -> str
"""
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) | python | def getAssociationFilename(self, server_url, handle):
"""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.
(str, str) -> str
"""
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) | [
"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.
(str, str) -> str | [
"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",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L182-L204 | train |
openid/python-openid | openid/store/filestore.py | FileOpenIDStore.getAssociation | def getAssociation(self, server_url, handle=None):
"""Retrieve an association. If no handle is specified, return
the association with the latest expiration.
(str, str or NoneType) -> Association or NoneType
"""
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 | python | def getAssociation(self, server_url, handle=None):
"""Retrieve an association. If no handle is specified, return
the association with the latest expiration.
(str, str or NoneType) -> Association or NoneType
"""
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 | [
"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.
(str, str or NoneType) -> Association or NoneType | [
"Retrieve",
"an",
"association",
".",
"If",
"no",
"handle",
"is",
"specified",
"return",
"the",
"association",
"with",
"the",
"latest",
"expiration",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L248-L288 | train |
openid/python-openid | openid/store/filestore.py | FileOpenIDStore.removeAssociation | def removeAssociation(self, server_url, handle):
"""Remove an association if it exists. Do nothing if it does not.
(str, str) -> bool
"""
assoc = self.getAssociation(server_url, handle)
if assoc is None:
return 0
else:
filename = self.getAssociationFilename(server_url, handle)
return _removeIfPresent(filename) | python | def removeAssociation(self, server_url, handle):
"""Remove an association if it exists. Do nothing if it does not.
(str, str) -> bool
"""
assoc = self.getAssociation(server_url, handle)
if assoc is None:
return 0
else:
filename = self.getAssociationFilename(server_url, handle)
return _removeIfPresent(filename) | [
"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.
(str, str) -> bool | [
"Remove",
"an",
"association",
"if",
"it",
"exists",
".",
"Do",
"nothing",
"if",
"it",
"does",
"not",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L318-L328 | train |
openid/python-openid | openid/store/filestore.py | FileOpenIDStore.useNonce | def useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is valid.
str -> bool
"""
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 | python | def useNonce(self, server_url, timestamp, salt):
"""Return whether this nonce is valid.
str -> bool
"""
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 | [
"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.
str -> bool | [
"Return",
"whether",
"this",
"nonce",
"is",
"valid",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/filestore.py#L330-L362 | train |
openid/python-openid | openid/consumer/discover.py | arrangeByType | def arrangeByType(service_list, preferred_types):
"""Rearrange service_list in a new list so services are ordered by
types listed in preferred_types. Return the new list."""
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 | python | def arrangeByType(service_list, preferred_types):
"""Rearrange service_list in a new list so services are ordered by
types listed in preferred_types. Return the new list."""
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 | [
"def",
"arrangeByType",
"(",
"service_list",
",",
"preferred_types",
")",
":",
"def",
"enumerate",
"(",
"elts",
")",
":",
"\"\"\"Return an iterable that pairs the index of an element with\n that element.\n\n For Python 2.2 compatibility\"\"\"",
"return",
"zip",
"(",
"range",
"(",
"len",
"(",
"elts",
")",
")",
",",
"elts",
")",
"def",
"bestMatchingService",
"(",
"service",
")",
":",
"\"\"\"Return the index of the first matching type, or something\n higher if no type matches.\n\n This provides an ordering in which service elements that\n contain a type that comes earlier in the preferred types list\n come before service elements that come later. If a service\n element has more than one type, the most preferred one wins.\n \"\"\"",
"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. | [
"Rearrange",
"service_list",
"in",
"a",
"new",
"list",
"so",
"services",
"are",
"ordered",
"by",
"types",
"listed",
"in",
"preferred_types",
".",
"Return",
"the",
"new",
"list",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L319-L356 | train |
openid/python-openid | openid/consumer/discover.py | getOPOrUserServices | def getOPOrUserServices(openid_services):
"""Extract OP Identifier services. If none found, return the
rest, sorted with most preferred first according to
OpenIDServiceEndpoint.openid_type_uris.
openid_services is a list of OpenIDServiceEndpoint objects.
Returns a list of OpenIDServiceEndpoint objects."""
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 | python | def getOPOrUserServices(openid_services):
"""Extract OP Identifier services. If none found, return the
rest, sorted with most preferred first according to
OpenIDServiceEndpoint.openid_type_uris.
openid_services is a list of OpenIDServiceEndpoint objects.
Returns a list of OpenIDServiceEndpoint objects."""
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 | [
"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.
openid_services is a list of OpenIDServiceEndpoint objects.
Returns a list of OpenIDServiceEndpoint objects. | [
"Extract",
"OP",
"Identifier",
"services",
".",
"If",
"none",
"found",
"return",
"the",
"rest",
"sorted",
"with",
"most",
"preferred",
"first",
"according",
"to",
"OpenIDServiceEndpoint",
".",
"openid_type_uris",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L358-L372 | train |
openid/python-openid | openid/consumer/discover.py | OpenIDServiceEndpoint.supportsType | def supportsType(self, type_uri):
"""Does this endpoint support this type?
I consider C{/server} endpoints to implicitly support C{/signon}.
"""
return (
(type_uri in self.type_uris) or
(type_uri == OPENID_2_0_TYPE and self.isOPIdentifier())
) | python | def supportsType(self, type_uri):
"""Does this endpoint support this type?
I consider C{/server} endpoints to implicitly support C{/signon}.
"""
return (
(type_uri in self.type_uris) or
(type_uri == OPENID_2_0_TYPE and self.isOPIdentifier())
) | [
"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?
I consider C{/server} endpoints to implicitly support C{/signon}. | [
"Does",
"this",
"endpoint",
"support",
"this",
"type?"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L76-L84 | train |
openid/python-openid | openid/consumer/discover.py | OpenIDServiceEndpoint.parseService | def parseService(self, yadis_url, uri, type_uris, service_element):
"""Set the state of this object based on the contents of the
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 | python | def parseService(self, yadis_url, uri, type_uris, service_element):
"""Set the state of this object based on the contents of the
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 | [
"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. | [
"Set",
"the",
"state",
"of",
"this",
"object",
"based",
"on",
"the",
"contents",
"of",
"the",
"service",
"element",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L102-L116 | train |
openid/python-openid | openid/consumer/discover.py | OpenIDServiceEndpoint.getLocalID | def getLocalID(self):
"""Return the identifier that should be sent as the
openid.identity parameter to the server."""
# 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 | python | def getLocalID(self):
"""Return the identifier that should be sent as the
openid.identity parameter to the server."""
# 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 | [
"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. | [
"Return",
"the",
"identifier",
"that",
"should",
"be",
"sent",
"as",
"the",
"openid",
".",
"identity",
"parameter",
"to",
"the",
"server",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L118-L128 | train |
openid/python-openid | openid/consumer/discover.py | OpenIDServiceEndpoint.fromBasicServiceEndpoint | def fromBasicServiceEndpoint(cls, endpoint):
"""Create a new instance of this class from the endpoint
object passed in.
@return: None or OpenIDServiceEndpoint for this endpoint object"""
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 | python | def fromBasicServiceEndpoint(cls, endpoint):
"""Create a new instance of this class from the endpoint
object passed in.
@return: None or OpenIDServiceEndpoint for this endpoint object"""
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 | [
"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.
@return: None or OpenIDServiceEndpoint for this endpoint object | [
"Create",
"a",
"new",
"instance",
"of",
"this",
"class",
"from",
"the",
"endpoint",
"object",
"passed",
"in",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L130-L149 | train |
openid/python-openid | openid/consumer/discover.py | OpenIDServiceEndpoint.fromDiscoveryResult | def fromDiscoveryResult(cls, discoveryResult):
"""Create endpoints from a DiscoveryResult.
@type discoveryResult: L{DiscoveryResult}
@rtype: list of L{OpenIDServiceEndpoint}
@raises XRDSError: When the XRDS does not parse.
@since: 2.1.0
"""
if discoveryResult.isXRDS():
method = cls.fromXRDS
else:
method = cls.fromHTML
return method(discoveryResult.normalized_uri,
discoveryResult.response_text) | python | def fromDiscoveryResult(cls, discoveryResult):
"""Create endpoints from a DiscoveryResult.
@type discoveryResult: L{DiscoveryResult}
@rtype: list of L{OpenIDServiceEndpoint}
@raises XRDSError: When the XRDS does not parse.
@since: 2.1.0
"""
if discoveryResult.isXRDS():
method = cls.fromXRDS
else:
method = cls.fromHTML
return method(discoveryResult.normalized_uri,
discoveryResult.response_text) | [
"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.
@type discoveryResult: L{DiscoveryResult}
@rtype: list of L{OpenIDServiceEndpoint}
@raises XRDSError: When the XRDS does not parse.
@since: 2.1.0 | [
"Create",
"endpoints",
"from",
"a",
"DiscoveryResult",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L200-L216 | train |
openid/python-openid | openid/consumer/discover.py | OpenIDServiceEndpoint.fromOPEndpointURL | def fromOPEndpointURL(cls, op_endpoint_url):
"""Construct an OP-Identifier OpenIDServiceEndpoint object for
a given OP Endpoint URL
@param op_endpoint_url: The URL of the endpoint
@rtype: OpenIDServiceEndpoint
"""
service = cls()
service.server_url = op_endpoint_url
service.type_uris = [OPENID_IDP_2_0_TYPE]
return service | python | def fromOPEndpointURL(cls, op_endpoint_url):
"""Construct an OP-Identifier OpenIDServiceEndpoint object for
a given OP Endpoint URL
@param op_endpoint_url: The URL of the endpoint
@rtype: OpenIDServiceEndpoint
"""
service = cls()
service.server_url = op_endpoint_url
service.type_uris = [OPENID_IDP_2_0_TYPE]
return service | [
"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
@param op_endpoint_url: The URL of the endpoint
@rtype: OpenIDServiceEndpoint | [
"Construct",
"an",
"OP",
"-",
"Identifier",
"OpenIDServiceEndpoint",
"object",
"for",
"a",
"given",
"OP",
"Endpoint",
"URL"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/discover.py#L221-L231 | train |
openid/python-openid | openid/association.py | SessionNegotiator.setAllowedTypes | def setAllowedTypes(self, allowed_types):
"""Set the allowed association types, checking to make sure
each combination is valid."""
for (assoc_type, session_type) in allowed_types:
checkSessionType(assoc_type, session_type)
self.allowed_types = allowed_types | python | def setAllowedTypes(self, allowed_types):
"""Set the allowed association types, checking to make sure
each combination is valid."""
for (assoc_type, session_type) in allowed_types:
checkSessionType(assoc_type, session_type)
self.allowed_types = allowed_types | [
"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. | [
"Set",
"the",
"allowed",
"association",
"types",
"checking",
"to",
"make",
"sure",
"each",
"combination",
"is",
"valid",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L143-L149 | train |
openid/python-openid | openid/association.py | SessionNegotiator.isAllowed | def isAllowed(self, assoc_type, session_type):
"""Is this combination of association type and session type allowed?"""
assoc_good = (assoc_type, session_type) in self.allowed_types
matches = session_type in getSessionTypes(assoc_type)
return assoc_good and matches | python | def isAllowed(self, assoc_type, session_type):
"""Is this combination of association type and session type allowed?"""
assoc_good = (assoc_type, session_type) in self.allowed_types
matches = session_type in getSessionTypes(assoc_type)
return assoc_good and matches | [
"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? | [
"Is",
"this",
"combination",
"of",
"association",
"type",
"and",
"session",
"type",
"allowed?"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L172-L176 | train |
openid/python-openid | openid/association.py | Association.serialize | def serialize(self):
"""
Convert an association to KV form.
@return: String in KV form suitable for deserialization by
deserialize.
@rtype: str
"""
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) | python | def serialize(self):
"""
Convert an association to KV form.
@return: String in KV form suitable for deserialization by
deserialize.
@rtype: str
"""
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) | [
"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.
@return: String in KV form suitable for deserialization by
deserialize.
@rtype: str | [
"Convert",
"an",
"association",
"to",
"KV",
"form",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L398-L421 | train |
openid/python-openid | openid/association.py | Association.getMessageSignature | def getMessageSignature(self, message):
"""Return the signature of a message.
If I am not a sign-all association, the message must have a
signed list.
@return: the signature, base64 encoded
@rtype: str
@raises ValueError: If there is no signed list and I am not a sign-all
type of association.
"""
pairs = self._makePairs(message)
return oidutil.toBase64(self.sign(pairs)) | python | def getMessageSignature(self, message):
"""Return the signature of a message.
If I am not a sign-all association, the message must have a
signed list.
@return: the signature, base64 encoded
@rtype: str
@raises ValueError: If there is no signed list and I am not a sign-all
type of association.
"""
pairs = self._makePairs(message)
return oidutil.toBase64(self.sign(pairs)) | [
"def",
"getMessageSignature",
"(",
"self",
",",
"message",
")",
":",
"pairs",
"=",
"self",
".",
"_makePairs",
"(",
"message",
")",
"return",
"oidutil",
".",
"toBase64",
"(",
"self",
".",
"sign",
"(",
"pairs",
")",
")"
] | Return the signature of a message.
If I am not a sign-all association, the message must have a
signed list.
@return: the signature, base64 encoded
@rtype: str
@raises ValueError: If there is no signed list and I am not a sign-all
type of association. | [
"Return",
"the",
"signature",
"of",
"a",
"message",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L482-L496 | train |
openid/python-openid | openid/association.py | Association.checkMessageSignature | def checkMessageSignature(self, message):
"""Given a message with a signature, calculate a new signature
and return whether it matches the signature in the message.
@raises ValueError: if the message has no signature or no signature
can be calculated for it.
"""
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) | python | def checkMessageSignature(self, message):
"""Given a message with a signature, calculate a new signature
and return whether it matches the signature in the message.
@raises ValueError: if the message has no signature or no signature
can be calculated for it.
"""
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) | [
"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.
@raises ValueError: if the message has no signature or no signature
can be calculated for it. | [
"Given",
"a",
"message",
"with",
"a",
"signature",
"calculate",
"a",
"new",
"signature",
"and",
"return",
"whether",
"it",
"matches",
"the",
"signature",
"in",
"the",
"message",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/association.py#L524-L535 | train |
openid/python-openid | openid/extensions/draft/pape2.py | Request.addPolicyURI | def addPolicyURI(self, policy_uri):
"""Add an acceptable authentication policy URI to this request
This method is intended to be used by the relying party to add
acceptable authentication types to the request.
@param policy_uri: The identifier for the preferred type of
authentication.
@see: http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#auth_policies
"""
if policy_uri not in self.preferred_auth_policies:
self.preferred_auth_policies.append(policy_uri) | python | def addPolicyURI(self, policy_uri):
"""Add an acceptable authentication policy URI to this request
This method is intended to be used by the relying party to add
acceptable authentication types to the request.
@param policy_uri: The identifier for the preferred type of
authentication.
@see: http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#auth_policies
"""
if policy_uri not in self.preferred_auth_policies:
self.preferred_auth_policies.append(policy_uri) | [
"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
This method is intended to be used by the relying party to add
acceptable authentication types to the request.
@param policy_uri: The identifier for the preferred type of
authentication.
@see: http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#auth_policies | [
"Add",
"an",
"acceptable",
"authentication",
"policy",
"URI",
"to",
"this",
"request"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/draft/pape2.py#L60-L71 | train |
openid/python-openid | openid/extensions/draft/pape5.py | PAPEExtension._addAuthLevelAlias | def _addAuthLevelAlias(self, auth_level_uri, alias=None):
"""Add an auth level URI alias to this request.
@param auth_level_uri: The auth level URI to send in the
request.
@param alias: The namespace alias to use for this auth level
in this message. May be None if the alias is not
important.
"""
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 | python | def _addAuthLevelAlias(self, auth_level_uri, alias=None):
"""Add an auth level URI alias to this request.
@param auth_level_uri: The auth level URI to send in the
request.
@param alias: The namespace alias to use for this auth level
in this message. May be None if the alias is not
important.
"""
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 | [
"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.
@param auth_level_uri: The auth level URI to send in the
request.
@param alias: The namespace alias to use for this auth level
in this message. May be None if the alias is not
important. | [
"Add",
"an",
"auth",
"level",
"URI",
"alias",
"to",
"this",
"request",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/draft/pape5.py#L49-L70 | train |
openid/python-openid | openid/extensions/draft/pape5.py | Response.setAuthLevel | def setAuthLevel(self, level_uri, level, alias=None):
"""Set the value for the given auth level type.
@param level: string representation of an authentication level
valid for level_uri
@param alias: An optional namespace alias for the given auth
level URI. May be omitted if the alias is not
significant. The library will use a reasonable default for
widely-used auth level types.
"""
self._addAuthLevelAlias(level_uri, alias)
self.auth_levels[level_uri] = level | python | def setAuthLevel(self, level_uri, level, alias=None):
"""Set the value for the given auth level type.
@param level: string representation of an authentication level
valid for level_uri
@param alias: An optional namespace alias for the given auth
level URI. May be omitted if the alias is not
significant. The library will use a reasonable default for
widely-used auth level types.
"""
self._addAuthLevelAlias(level_uri, alias)
self.auth_levels[level_uri] = level | [
"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.
@param level: string representation of an authentication level
valid for level_uri
@param alias: An optional namespace alias for the given auth
level URI. May be omitted if the alias is not
significant. The library will use a reasonable default for
widely-used auth level types. | [
"Set",
"the",
"value",
"for",
"the",
"given",
"auth",
"level",
"type",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/extensions/draft/pape5.py#L298-L310 | train |
openid/python-openid | openid/yadis/discover.py | discover | def discover(uri):
"""Discover services for a given URI.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
@return: DiscoveryResult object
@raises Exception: Any exception that can be raised by fetching a URL with
the given fetcher.
@raises DiscoveryFailure: When the HTTP response does not have a 200 code.
"""
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 | python | def discover(uri):
"""Discover services for a given URI.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
@return: DiscoveryResult object
@raises Exception: Any exception that can be raised by fetching a URL with
the given fetcher.
@raises DiscoveryFailure: When the HTTP response does not have a 200 code.
"""
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 | [
"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.
@param uri: The identity URI as a well-formed http or https
URI. The well-formedness and the protocol are not checked, but
the results of this function are undefined if those properties
do not hold.
@return: DiscoveryResult object
@raises Exception: Any exception that can be raised by fetching a URL with
the given fetcher.
@raises DiscoveryFailure: When the HTTP response does not have a 200 code. | [
"Discover",
"services",
"for",
"a",
"given",
"URI",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/discover.py#L57-L98 | train |
openid/python-openid | openid/yadis/discover.py | whereIsYadis | def whereIsYadis(resp):
"""Given a HTTPResponse, return the location of the Yadis document.
May be the URL just retrieved, another URL, or None, if I can't
find any.
[non-blocking]
@returns: str or None
"""
# 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 | python | def whereIsYadis(resp):
"""Given a HTTPResponse, return the location of the Yadis document.
May be the URL just retrieved, another URL, or None, if I can't
find any.
[non-blocking]
@returns: str or None
"""
# 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 | [
"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.
May be the URL just retrieved, another URL, or None, if I can't
find any.
[non-blocking]
@returns: str or None | [
"Given",
"a",
"HTTPResponse",
"return",
"the",
"location",
"of",
"the",
"Yadis",
"document",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/discover.py#L102-L154 | train |
openid/python-openid | examples/djopenid/server/views.py | endpoint | def endpoint(request):
"""
Respond to low-level OpenID protocol messages.
"""
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) | python | def endpoint(request):
"""
Respond to low-level OpenID protocol messages.
"""
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) | [
"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. | [
"Respond",
"to",
"low",
"-",
"level",
"OpenID",
"protocol",
"messages",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/djopenid/server/views.py#L101-L136 | train |
openid/python-openid | examples/djopenid/server/views.py | showDecidePage | def showDecidePage(request, openid_request):
"""
Render a page to the user so a trust decision can be made.
@type openid_request: openid.server.server.CheckIDRequest
"""
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,
}) | python | def showDecidePage(request, openid_request):
"""
Render a page to the user so a trust decision can be made.
@type openid_request: openid.server.server.CheckIDRequest
"""
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,
}) | [
"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.
@type openid_request: openid.server.server.CheckIDRequest | [
"Render",
"a",
"page",
"to",
"the",
"user",
"so",
"a",
"trust",
"decision",
"can",
"be",
"made",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/djopenid/server/views.py#L179-L206 | train |
openid/python-openid | examples/djopenid/server/views.py | processTrustResult | def processTrustResult(request):
"""
Handle the result of a trust decision and respond to the RP
accordingly.
"""
# 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) | python | def processTrustResult(request):
"""
Handle the result of a trust decision and respond to the RP
accordingly.
"""
# 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) | [
"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. | [
"Handle",
"the",
"result",
"of",
"a",
"trust",
"decision",
"and",
"respond",
"to",
"the",
"RP",
"accordingly",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/examples/djopenid/server/views.py#L208-L250 | train |
openid/python-openid | admin/builddiscover.py | buildDiscover | def buildDiscover(base_url, out_dir):
"""Convert all files in a directory to apache mod_asis files in
another directory."""
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() | python | def buildDiscover(base_url, out_dir):
"""Convert all files in a directory to apache mod_asis files in
another directory."""
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() | [
"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. | [
"Convert",
"all",
"files",
"in",
"a",
"directory",
"to",
"apache",
"mod_asis",
"files",
"in",
"another",
"directory",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/admin/builddiscover.py#L31-L63 | train |
openid/python-openid | openid/store/memstore.py | ServerAssocs.best | def best(self):
"""Returns association with the oldest issued date.
or None if there are no associations.
"""
best = None
for assoc in self.assocs.values():
if best is None or best.issued < assoc.issued:
best = assoc
return best | python | def best(self):
"""Returns association with the oldest issued date.
or None if there are no associations.
"""
best = None
for assoc in self.assocs.values():
if best is None or best.issued < assoc.issued:
best = assoc
return best | [
"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.
or None if there are no associations. | [
"Returns",
"association",
"with",
"the",
"oldest",
"issued",
"date",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/memstore.py#L26-L35 | train |
openid/python-openid | openid/store/nonce.py | split | def split(nonce_string):
"""Extract a timestamp from the given nonce string
@param nonce_string: the nonce from which to extract the timestamp
@type nonce_string: str
@returns: A pair of a Unix timestamp and the salt characters
@returntype: (int, str)
@raises ValueError: if the nonce does not start with a correctly
formatted time 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:] | python | def split(nonce_string):
"""Extract a timestamp from the given nonce string
@param nonce_string: the nonce from which to extract the timestamp
@type nonce_string: str
@returns: A pair of a Unix timestamp and the salt characters
@returntype: (int, str)
@raises ValueError: if the nonce does not start with a correctly
formatted time 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:] | [
"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
@param nonce_string: the nonce from which to extract the timestamp
@type nonce_string: str
@returns: A pair of a Unix timestamp and the salt characters
@returntype: (int, str)
@raises ValueError: if the nonce does not start with a correctly
formatted time string | [
"Extract",
"a",
"timestamp",
"from",
"the",
"given",
"nonce",
"string"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/nonce.py#L22-L41 | train |
openid/python-openid | openid/store/nonce.py | checkTimestamp | def checkTimestamp(nonce_string, allowed_skew=SKEW, now=None):
"""Is the timestamp that is part of the specified nonce string
within the allowed clock-skew of the current time?
@param nonce_string: The nonce that is being checked
@type nonce_string: str
@param allowed_skew: How many seconds should be allowed for
completing the request, allowing for clock skew.
@type allowed_skew: int
@param now: The current time, as a Unix timestamp
@type now: int
@returntype: bool
@returns: Whether the timestamp is correctly formatted and within
the allowed skew of the current time.
"""
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 | python | def checkTimestamp(nonce_string, allowed_skew=SKEW, now=None):
"""Is the timestamp that is part of the specified nonce string
within the allowed clock-skew of the current time?
@param nonce_string: The nonce that is being checked
@type nonce_string: str
@param allowed_skew: How many seconds should be allowed for
completing the request, allowing for clock skew.
@type allowed_skew: int
@param now: The current time, as a Unix timestamp
@type now: int
@returntype: bool
@returns: Whether the timestamp is correctly formatted and within
the allowed skew of the current time.
"""
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 | [
"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?
@param nonce_string: The nonce that is being checked
@type nonce_string: str
@param allowed_skew: How many seconds should be allowed for
completing the request, allowing for clock skew.
@type allowed_skew: int
@param now: The current time, as a Unix timestamp
@type now: int
@returntype: bool
@returns: Whether the timestamp is correctly formatted and within
the allowed skew of the current time. | [
"Is",
"the",
"timestamp",
"that",
"is",
"part",
"of",
"the",
"specified",
"nonce",
"string",
"within",
"the",
"allowed",
"clock",
"-",
"skew",
"of",
"the",
"current",
"time?"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/nonce.py#L43-L77 | train |
openid/python-openid | openid/store/nonce.py | mkNonce | def mkNonce(when=None):
"""Generate a nonce with the current timestamp
@param when: Unix timestamp representing the issue time of the
nonce. Defaults to the current time.
@type when: int
@returntype: str
@returns: A string that should be usable as a one-way nonce
@see: time
"""
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 | python | def mkNonce(when=None):
"""Generate a nonce with the current timestamp
@param when: Unix timestamp representing the issue time of the
nonce. Defaults to the current time.
@type when: int
@returntype: str
@returns: A string that should be usable as a one-way nonce
@see: time
"""
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 | [
"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
@param when: Unix timestamp representing the issue time of the
nonce. Defaults to the current time.
@type when: int
@returntype: str
@returns: A string that should be usable as a one-way nonce
@see: time | [
"Generate",
"a",
"nonce",
"with",
"the",
"current",
"timestamp"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/store/nonce.py#L79-L98 | train |
openid/python-openid | openid/fetchers.py | fetch | def fetch(url, body=None, headers=None):
"""Invoke the fetch method on the default fetcher. Most users
should need only this method.
@raises Exception: any exceptions that may be raised by the default fetcher
"""
fetcher = getDefaultFetcher()
return fetcher.fetch(url, body, headers) | python | def fetch(url, body=None, headers=None):
"""Invoke the fetch method on the default fetcher. Most users
should need only this method.
@raises Exception: any exceptions that may be raised by the default fetcher
"""
fetcher = getDefaultFetcher()
return fetcher.fetch(url, body, headers) | [
"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.
@raises Exception: any exceptions that may be raised by the default fetcher | [
"Invoke",
"the",
"fetch",
"method",
"on",
"the",
"default",
"fetcher",
".",
"Most",
"users",
"should",
"need",
"only",
"this",
"method",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/fetchers.py#L35-L42 | train |
openid/python-openid | openid/fetchers.py | setDefaultFetcher | def setDefaultFetcher(fetcher, wrap_exceptions=True):
"""Set the default fetcher
@param fetcher: The fetcher to use as the default HTTP fetcher
@type fetcher: HTTPFetcher
@param wrap_exceptions: Whether to wrap exceptions thrown by the
fetcher wil HTTPFetchingError so that they may be caught
easier. By default, exceptions will be wrapped. In general,
unwrapped fetchers are useful for debugging of fetching errors
or if your fetcher raises well-known exceptions that you would
like to catch.
@type wrap_exceptions: bool
"""
global _default_fetcher
if fetcher is None or not wrap_exceptions:
_default_fetcher = fetcher
else:
_default_fetcher = ExceptionWrappingFetcher(fetcher) | python | def setDefaultFetcher(fetcher, wrap_exceptions=True):
"""Set the default fetcher
@param fetcher: The fetcher to use as the default HTTP fetcher
@type fetcher: HTTPFetcher
@param wrap_exceptions: Whether to wrap exceptions thrown by the
fetcher wil HTTPFetchingError so that they may be caught
easier. By default, exceptions will be wrapped. In general,
unwrapped fetchers are useful for debugging of fetching errors
or if your fetcher raises well-known exceptions that you would
like to catch.
@type wrap_exceptions: bool
"""
global _default_fetcher
if fetcher is None or not wrap_exceptions:
_default_fetcher = fetcher
else:
_default_fetcher = ExceptionWrappingFetcher(fetcher) | [
"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
@param fetcher: The fetcher to use as the default HTTP fetcher
@type fetcher: HTTPFetcher
@param wrap_exceptions: Whether to wrap exceptions thrown by the
fetcher wil HTTPFetchingError so that they may be caught
easier. By default, exceptions will be wrapped. In general,
unwrapped fetchers are useful for debugging of fetching errors
or if your fetcher raises well-known exceptions that you would
like to catch.
@type wrap_exceptions: bool | [
"Set",
"the",
"default",
"fetcher"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/fetchers.py#L74-L92 | train |
openid/python-openid | openid/fetchers.py | usingCurl | def usingCurl():
"""Whether the currently set HTTP fetcher is a Curl HTTP fetcher."""
fetcher = getDefaultFetcher()
if isinstance(fetcher, ExceptionWrappingFetcher):
fetcher = fetcher.fetcher
return isinstance(fetcher, CurlHTTPFetcher) | python | def usingCurl():
"""Whether the currently set HTTP fetcher is a Curl HTTP fetcher."""
fetcher = getDefaultFetcher()
if isinstance(fetcher, ExceptionWrappingFetcher):
fetcher = fetcher.fetcher
return isinstance(fetcher, CurlHTTPFetcher) | [
"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. | [
"Whether",
"the",
"currently",
"set",
"HTTP",
"fetcher",
"is",
"a",
"Curl",
"HTTP",
"fetcher",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/fetchers.py#L94-L99 | train |
openid/python-openid | openid/fetchers.py | HTTPLib2Fetcher.fetch | def fetch(self, url, body=None, headers=None):
"""Perform an HTTP request
@raises Exception: Any exception that can be raised by httplib2
@see: C{L{HTTPFetcher.fetch}}
"""
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,
) | python | def fetch(self, url, body=None, headers=None):
"""Perform an HTTP request
@raises Exception: Any exception that can be raised by httplib2
@see: C{L{HTTPFetcher.fetch}}
"""
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,
) | [
"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
@raises Exception: Any exception that can be raised by httplib2
@see: C{L{HTTPFetcher.fetch}} | [
"Perform",
"an",
"HTTP",
"request"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/fetchers.py#L386-L430 | train |
openid/python-openid | openid/yadis/services.py | getServiceEndpoints | def getServiceEndpoints(input_url, flt=None):
"""Perform the Yadis protocol on the input URL and return an
iterable of resulting endpoint objects.
@param flt: A filter object or something that is convertable to
a filter object (using mkFilter) that will be used to generate
endpoint objects. This defaults to generating BasicEndpoint
objects.
@param input_url: The URL on which to perform the Yadis protocol
@return: The normalized identity URL and an iterable of endpoint
objects generated by the filter function.
@rtype: (str, [endpoint])
@raises DiscoveryFailure: when Yadis fails to obtain an XRDS document.
"""
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) | python | def getServiceEndpoints(input_url, flt=None):
"""Perform the Yadis protocol on the input URL and return an
iterable of resulting endpoint objects.
@param flt: A filter object or something that is convertable to
a filter object (using mkFilter) that will be used to generate
endpoint objects. This defaults to generating BasicEndpoint
objects.
@param input_url: The URL on which to perform the Yadis protocol
@return: The normalized identity URL and an iterable of endpoint
objects generated by the filter function.
@rtype: (str, [endpoint])
@raises DiscoveryFailure: when Yadis fails to obtain an XRDS document.
"""
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) | [
"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.
@param flt: A filter object or something that is convertable to
a filter object (using mkFilter) that will be used to generate
endpoint objects. This defaults to generating BasicEndpoint
objects.
@param input_url: The URL on which to perform the Yadis protocol
@return: The normalized identity URL and an iterable of endpoint
objects generated by the filter function.
@rtype: (str, [endpoint])
@raises DiscoveryFailure: when Yadis fails to obtain an XRDS document. | [
"Perform",
"the",
"Yadis",
"protocol",
"on",
"the",
"input",
"URL",
"and",
"return",
"an",
"iterable",
"of",
"resulting",
"endpoint",
"objects",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/services.py#L7-L31 | train |
openid/python-openid | openid/yadis/services.py | applyFilter | def applyFilter(normalized_uri, xrd_data, flt=None):
"""Generate an iterable of endpoint objects given this input data,
presumably from the result of performing the Yadis protocol.
@param normalized_uri: The input URL, after following redirects,
as in the Yadis protocol.
@param xrd_data: The XML text the XRDS file fetched from the
normalized URI.
@type xrd_data: str
"""
flt = mkFilter(flt)
et = parseXRDS(xrd_data)
endpoints = []
for service_element in iterServices(et):
endpoints.extend(
flt.getServiceEndpoints(normalized_uri, service_element))
return endpoints | python | def applyFilter(normalized_uri, xrd_data, flt=None):
"""Generate an iterable of endpoint objects given this input data,
presumably from the result of performing the Yadis protocol.
@param normalized_uri: The input URL, after following redirects,
as in the Yadis protocol.
@param xrd_data: The XML text the XRDS file fetched from the
normalized URI.
@type xrd_data: str
"""
flt = mkFilter(flt)
et = parseXRDS(xrd_data)
endpoints = []
for service_element in iterServices(et):
endpoints.extend(
flt.getServiceEndpoints(normalized_uri, service_element))
return endpoints | [
"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.
@param normalized_uri: The input URL, after following redirects,
as in the Yadis protocol.
@param xrd_data: The XML text the XRDS file fetched from the
normalized URI.
@type xrd_data: str | [
"Generate",
"an",
"iterable",
"of",
"endpoint",
"objects",
"given",
"this",
"input",
"data",
"presumably",
"from",
"the",
"result",
"of",
"performing",
"the",
"Yadis",
"protocol",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/services.py#L33-L54 | train |
openid/python-openid | openid/consumer/html_parse.py | parseLinkAttrs | def parseLinkAttrs(html):
"""Find all link tags in a string representing a HTML document and
return a list of their attributes.
@param html: the text to parse
@type html: str or unicode
@return: A list of dictionaries of attributes, one for each link tag
@rtype: [[(type(html), type(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 | python | def parseLinkAttrs(html):
"""Find all link tags in a string representing a HTML document and
return a list of their attributes.
@param html: the text to parse
@type html: str or unicode
@return: A list of dictionaries of attributes, one for each link tag
@rtype: [[(type(html), type(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 | [
"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.
@param html: the text to parse
@type html: str or unicode
@return: A list of dictionaries of attributes, one for each link tag
@rtype: [[(type(html), type(html))]] | [
"Find",
"all",
"link",
"tags",
"in",
"a",
"string",
"representing",
"a",
"HTML",
"document",
"and",
"return",
"a",
"list",
"of",
"their",
"attributes",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L174-L215 | train |
openid/python-openid | openid/consumer/html_parse.py | relMatches | def relMatches(rel_attr, target_rel):
"""Does this target_rel appear in the rel_str?"""
# XXX: TESTME
rels = rel_attr.strip().split()
for rel in rels:
rel = rel.lower()
if rel == target_rel:
return 1
return 0 | python | def relMatches(rel_attr, target_rel):
"""Does this target_rel appear in the rel_str?"""
# XXX: TESTME
rels = rel_attr.strip().split()
for rel in rels:
rel = rel.lower()
if rel == target_rel:
return 1
return 0 | [
"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? | [
"Does",
"this",
"target_rel",
"appear",
"in",
"the",
"rel_str?"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L217-L226 | train |
openid/python-openid | openid/consumer/html_parse.py | linkHasRel | def linkHasRel(link_attrs, target_rel):
"""Does this link have target_rel as a relationship?"""
# XXX: TESTME
rel_attr = link_attrs.get('rel')
return rel_attr and relMatches(rel_attr, target_rel) | python | def linkHasRel(link_attrs, target_rel):
"""Does this link have target_rel as a relationship?"""
# XXX: TESTME
rel_attr = link_attrs.get('rel')
return rel_attr and relMatches(rel_attr, target_rel) | [
"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? | [
"Does",
"this",
"link",
"have",
"target_rel",
"as",
"a",
"relationship?"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L228-L232 | train |
openid/python-openid | openid/consumer/html_parse.py | findFirstHref | def findFirstHref(link_attrs_list, target_rel):
"""Return the value of the href attribute for the first link tag
in the list that has target_rel as a relationship."""
# XXX: TESTME
matches = findLinksRel(link_attrs_list, target_rel)
if not matches:
return None
first = matches[0]
return first.get('href') | python | def findFirstHref(link_attrs_list, target_rel):
"""Return the value of the href attribute for the first link tag
in the list that has target_rel as a relationship."""
# XXX: TESTME
matches = findLinksRel(link_attrs_list, target_rel)
if not matches:
return None
first = matches[0]
return first.get('href') | [
"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. | [
"Return",
"the",
"value",
"of",
"the",
"href",
"attribute",
"for",
"the",
"first",
"link",
"tag",
"in",
"the",
"list",
"that",
"has",
"target_rel",
"as",
"a",
"relationship",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/html_parse.py#L241-L249 | train |
openid/python-openid | openid/oidutil.py | importElementTree | def importElementTree(module_names=None):
"""Find a working ElementTree implementation, trying the standard
places that such a thing might show up.
>>> ElementTree = importElementTree()
@param module_names: The names of modules to try to use as
ElementTree. Defaults to C{L{elementtree_modules}}
@returns: An ElementTree module
"""
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,)
) | python | def importElementTree(module_names=None):
"""Find a working ElementTree implementation, trying the standard
places that such a thing might show up.
>>> ElementTree = importElementTree()
@param module_names: The names of modules to try to use as
ElementTree. Defaults to C{L{elementtree_modules}}
@returns: An ElementTree module
"""
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,)
) | [
"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.
>>> ElementTree = importElementTree()
@param module_names: The names of modules to try to use as
ElementTree. Defaults to C{L{elementtree_modules}}
@returns: An ElementTree module | [
"Find",
"a",
"working",
"ElementTree",
"implementation",
"trying",
"the",
"standard",
"places",
"that",
"such",
"a",
"thing",
"might",
"show",
"up",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/oidutil.py#L55-L89 | train |
openid/python-openid | openid/yadis/etxrd.py | getYadisXRD | def getYadisXRD(xrd_tree):
"""Return the XRD element that should contain the Yadis services"""
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 | python | def getYadisXRD(xrd_tree):
"""Return the XRD element that should contain the Yadis services"""
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 | [
"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 | [
"Return",
"the",
"XRD",
"element",
"that",
"should",
"contain",
"the",
"Yadis",
"services"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/etxrd.py#L119-L133 | train |
openid/python-openid | openid/yadis/etxrd.py | getXRDExpiration | def getXRDExpiration(xrd_element, default=None):
"""Return the expiration date of this XRD element, or None if no
expiration was specified.
@type xrd_element: ElementTree node
@param default: The value to use as the expiration if no
expiration was specified in the XRD.
@rtype: datetime.datetime
@raises ValueError: If the xrd:Expires element is present, but its
contents are not formatted according to the specification.
"""
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]) | python | def getXRDExpiration(xrd_element, default=None):
"""Return the expiration date of this XRD element, or None if no
expiration was specified.
@type xrd_element: ElementTree node
@param default: The value to use as the expiration if no
expiration was specified in the XRD.
@rtype: datetime.datetime
@raises ValueError: If the xrd:Expires element is present, but its
contents are not formatted according to the specification.
"""
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]) | [
"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.
@type xrd_element: ElementTree node
@param default: The value to use as the expiration if no
expiration was specified in the XRD.
@rtype: datetime.datetime
@raises ValueError: If the xrd:Expires element is present, but its
contents are not formatted according to the specification. | [
"Return",
"the",
"expiration",
"date",
"of",
"this",
"XRD",
"element",
"or",
"None",
"if",
"no",
"expiration",
"was",
"specified",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/etxrd.py#L135-L157 | train |
openid/python-openid | openid/yadis/etxrd.py | getCanonicalID | def getCanonicalID(iname, xrd_tree):
"""Return the CanonicalID from this XRDS document.
@param iname: the XRI being resolved.
@type iname: unicode
@param xrd_tree: The XRDS output from the resolver.
@type xrd_tree: ElementTree
@returns: The XRI CanonicalID or None.
@returntype: unicode or None
"""
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 | python | def getCanonicalID(iname, xrd_tree):
"""Return the CanonicalID from this XRDS document.
@param iname: the XRI being resolved.
@type iname: unicode
@param xrd_tree: The XRDS output from the resolver.
@type xrd_tree: ElementTree
@returns: The XRI CanonicalID or None.
@returntype: unicode or None
"""
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 | [
"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.
@param iname: the XRI being resolved.
@type iname: unicode
@param xrd_tree: The XRDS output from the resolver.
@type xrd_tree: ElementTree
@returns: The XRI CanonicalID or None.
@returntype: unicode or None | [
"Return",
"the",
"CanonicalID",
"from",
"this",
"XRDS",
"document",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/etxrd.py#L159-L194 | train |
openid/python-openid | openid/yadis/etxrd.py | getPriorityStrict | def getPriorityStrict(element):
"""Get the priority of this element.
Raises ValueError if the value of the priority is invalid. If no
priority is specified, it returns a value that compares greater
than any other value.
"""
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 | python | def getPriorityStrict(element):
"""Get the priority of this element.
Raises ValueError if the value of the priority is invalid. If no
priority is specified, it returns a value that compares greater
than any other value.
"""
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 | [
"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.
Raises ValueError if the value of the priority is invalid. If no
priority is specified, it returns a value that compares greater
than any other value. | [
"Get",
"the",
"priority",
"of",
"this",
"element",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/etxrd.py#L211-L227 | train |
openid/python-openid | openid/consumer/consumer.py | makeKVPost | def makeKVPost(request_message, server_url):
"""Make a Direct Request to an OpenID Provider and return the
result as a Message object.
@raises openid.fetchers.HTTPFetchingError: if an error is
encountered in making the HTTP post.
@rtype: L{openid.message.Message}
"""
# 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) | python | def makeKVPost(request_message, server_url):
"""Make a Direct Request to an OpenID Provider and return the
result as a Message object.
@raises openid.fetchers.HTTPFetchingError: if an error is
encountered in making the HTTP post.
@rtype: L{openid.message.Message}
"""
# 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) | [
"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.
@raises openid.fetchers.HTTPFetchingError: if an error is
encountered in making the HTTP post.
@rtype: L{openid.message.Message} | [
"Make",
"a",
"Direct",
"Request",
"to",
"an",
"OpenID",
"Provider",
"and",
"return",
"the",
"result",
"as",
"a",
"Message",
"object",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L217-L230 | train |
openid/python-openid | openid/consumer/consumer.py | _httpResponseToMessage | def _httpResponseToMessage(response, server_url):
"""Adapt a POST response to a Message.
@type response: L{openid.fetchers.HTTPResponse}
@param response: Result of a POST to an OpenID endpoint.
@rtype: L{openid.message.Message}
@raises openid.fetchers.HTTPFetchingError: if the server returned a
status of other than 200 or 400.
@raises ServerError: if the server returned an OpenID error.
"""
# 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 | python | def _httpResponseToMessage(response, server_url):
"""Adapt a POST response to a Message.
@type response: L{openid.fetchers.HTTPResponse}
@param response: Result of a POST to an OpenID endpoint.
@rtype: L{openid.message.Message}
@raises openid.fetchers.HTTPFetchingError: if the server returned a
status of other than 200 or 400.
@raises ServerError: if the server returned an OpenID error.
"""
# 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 | [
"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.
@type response: L{openid.fetchers.HTTPResponse}
@param response: Result of a POST to an OpenID endpoint.
@rtype: L{openid.message.Message}
@raises openid.fetchers.HTTPFetchingError: if the server returned a
status of other than 200 or 400.
@raises ServerError: if the server returned an OpenID error. | [
"Adapt",
"a",
"POST",
"response",
"to",
"a",
"Message",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L233-L256 | train |
openid/python-openid | openid/consumer/consumer.py | Consumer.complete | def complete(self, query, current_url):
"""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.
@param query: A dictionary of the query parameters for this
HTTP request.
@param current_url: The URL used to invoke the application.
Extract the URL from your application's web
request framework and specify it here to have it checked
against the openid.return_to value in the response. If
the return_to URL check fails, the status of the
completion will be FAILURE.
@returns: a subclass of Response. The type of response is
indicated by the status attribute, which will be one of
SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED.
@see: L{SuccessResponse<openid.consumer.consumer.SuccessResponse>}
@see: L{CancelResponse<openid.consumer.consumer.CancelResponse>}
@see: L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>}
@see: L{FailureResponse<openid.consumer.consumer.FailureResponse>}
"""
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 | python | def complete(self, query, current_url):
"""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.
@param query: A dictionary of the query parameters for this
HTTP request.
@param current_url: The URL used to invoke the application.
Extract the URL from your application's web
request framework and specify it here to have it checked
against the openid.return_to value in the response. If
the return_to URL check fails, the status of the
completion will be FAILURE.
@returns: a subclass of Response. The type of response is
indicated by the status attribute, which will be one of
SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED.
@see: L{SuccessResponse<openid.consumer.consumer.SuccessResponse>}
@see: L{CancelResponse<openid.consumer.consumer.CancelResponse>}
@see: L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>}
@see: L{FailureResponse<openid.consumer.consumer.FailureResponse>}
"""
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 | [
"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.
@param query: A dictionary of the query parameters for this
HTTP request.
@param current_url: The URL used to invoke the application.
Extract the URL from your application's web
request framework and specify it here to have it checked
against the openid.return_to value in the response. If
the return_to URL check fails, the status of the
completion will be FAILURE.
@returns: a subclass of Response. The type of response is
indicated by the status attribute, which will be one of
SUCCESS, CANCEL, FAILURE, or SETUP_NEEDED.
@see: L{SuccessResponse<openid.consumer.consumer.SuccessResponse>}
@see: L{CancelResponse<openid.consumer.consumer.CancelResponse>}
@see: L{SetupNeededResponse<openid.consumer.consumer.SetupNeededResponse>}
@see: L{FailureResponse<openid.consumer.consumer.FailureResponse>} | [
"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",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L387-L432 | train |
openid/python-openid | openid/consumer/consumer.py | ServerError.fromMessage | def fromMessage(cls, message):
"""Generate a ServerError instance, extracting the error text
and the error code from the 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) | python | def fromMessage(cls, message):
"""Generate a ServerError instance, extracting the error text
and the error code from the 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) | [
"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. | [
"Generate",
"a",
"ServerError",
"instance",
"extracting",
"the",
"error",
"text",
"and",
"the",
"error",
"code",
"from",
"the",
"message",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L544-L550 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer.begin | def begin(self, service_endpoint):
"""Create an AuthRequest object for the specified
service_endpoint. This method will create an association if
necessary."""
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 | python | def begin(self, service_endpoint):
"""Create an AuthRequest object for the specified
service_endpoint. This method will create an association if
necessary."""
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 | [
"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. | [
"Create",
"an",
"AuthRequest",
"object",
"for",
"the",
"specified",
"service_endpoint",
".",
"This",
"method",
"will",
"create",
"an",
"association",
"if",
"necessary",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L592-L608 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer.complete | def complete(self, 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.
"""
mode = message.getArg(OPENID_NS, 'mode', '<No mode set>')
modeMethod = getattr(self, '_complete_' + mode,
self._completeInvalid)
return modeMethod(message, endpoint, return_to) | python | def complete(self, 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.
"""
mode = message.getArg(OPENID_NS, 'mode', '<No mode set>')
modeMethod = getattr(self, '_complete_' + mode,
self._completeInvalid)
return modeMethod(message, endpoint, return_to) | [
"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. | [
"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",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L610-L620 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._checkSetupNeeded | def _checkSetupNeeded(self, message):
"""Check an id_res message to see if it is a
checkid_immediate cancel response.
@raises SetupNeededError: if it is a checkid_immediate cancellation
"""
# 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) | python | def _checkSetupNeeded(self, message):
"""Check an id_res message to see if it is a
checkid_immediate cancel response.
@raises SetupNeededError: if it is a checkid_immediate cancellation
"""
# 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) | [
"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.
@raises SetupNeededError: if it is a checkid_immediate cancellation | [
"Check",
"an",
"id_res",
"message",
"to",
"see",
"if",
"it",
"is",
"a",
"checkid_immediate",
"cancel",
"response",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L687-L699 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._doIdRes | def _doIdRes(self, message, endpoint, return_to):
"""Handle id_res responses that are not cancellations of
immediate mode requests.
@param message: the response paramaters.
@param endpoint: the discovered endpoint object. May be None.
@raises ProtocolError: If the message contents are not
well-formed according to the OpenID specification. This
includes missing fields or not signing fields that should
be signed.
@raises DiscoveryFailure: If the subject of the id_res message
does not match the supplied endpoint, and discovery on the
identifier in the message fails (this should only happen
when using OpenID 2)
@returntype: L{Response}
"""
# 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) | python | def _doIdRes(self, message, endpoint, return_to):
"""Handle id_res responses that are not cancellations of
immediate mode requests.
@param message: the response paramaters.
@param endpoint: the discovered endpoint object. May be None.
@raises ProtocolError: If the message contents are not
well-formed according to the OpenID specification. This
includes missing fields or not signing fields that should
be signed.
@raises DiscoveryFailure: If the subject of the id_res message
does not match the supplied endpoint, and discovery on the
identifier in the message fails (this should only happen
when using OpenID 2)
@returntype: L{Response}
"""
# 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) | [
"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.
@param message: the response paramaters.
@param endpoint: the discovered endpoint object. May be None.
@raises ProtocolError: If the message contents are not
well-formed according to the OpenID specification. This
includes missing fields or not signing fields that should
be signed.
@raises DiscoveryFailure: If the subject of the id_res message
does not match the supplied endpoint, and discovery on the
identifier in the message fails (this should only happen
when using OpenID 2)
@returntype: L{Response} | [
"Handle",
"id_res",
"responses",
"that",
"are",
"not",
"cancellations",
"of",
"immediate",
"mode",
"requests",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L701-L744 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._verifyReturnToArgs | def _verifyReturnToArgs(query):
"""Verify that the arguments in the return_to URL are present in this
response.
"""
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],)) | python | def _verifyReturnToArgs(query):
"""Verify that the arguments in the return_to URL are present in this
response.
"""
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],)) | [
"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. | [
"Verify",
"that",
"the",
"arguments",
"in",
"the",
"return_to",
"URL",
"are",
"present",
"in",
"this",
"response",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L843-L873 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._verifyDiscoveryResults | def _verifyDiscoveryResults(self, resp_msg, endpoint=None):
"""
Extract the information from an OpenID assertion message and
verify it against the original
@param endpoint: The endpoint that resulted from doing discovery
@param resp_msg: The id_res message object
@returns: the verified endpoint
"""
if resp_msg.getOpenIDNamespace() == OPENID2_NS:
return self._verifyDiscoveryResultsOpenID2(resp_msg, endpoint)
else:
return self._verifyDiscoveryResultsOpenID1(resp_msg, endpoint) | python | def _verifyDiscoveryResults(self, resp_msg, endpoint=None):
"""
Extract the information from an OpenID assertion message and
verify it against the original
@param endpoint: The endpoint that resulted from doing discovery
@param resp_msg: The id_res message object
@returns: the verified endpoint
"""
if resp_msg.getOpenIDNamespace() == OPENID2_NS:
return self._verifyDiscoveryResultsOpenID2(resp_msg, endpoint)
else:
return self._verifyDiscoveryResultsOpenID1(resp_msg, endpoint) | [
"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
@param endpoint: The endpoint that resulted from doing discovery
@param resp_msg: The id_res message object
@returns: the verified endpoint | [
"Extract",
"the",
"information",
"from",
"an",
"OpenID",
"assertion",
"message",
"and",
"verify",
"it",
"against",
"the",
"original"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L877-L890 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._verifyDiscoverySingle | def _verifyDiscoverySingle(self, endpoint, to_match):
"""Verify that the given endpoint matches the information
extracted from the OpenID assertion, and raise an exception if
there is a mismatch.
@type endpoint: openid.consumer.discover.OpenIDServiceEndpoint
@type to_match: openid.consumer.discover.OpenIDServiceEndpoint
@rtype: NoneType
@raises ProtocolError: when the endpoint does not match the
discovered information.
"""
# 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)) | python | def _verifyDiscoverySingle(self, endpoint, to_match):
"""Verify that the given endpoint matches the information
extracted from the OpenID assertion, and raise an exception if
there is a mismatch.
@type endpoint: openid.consumer.discover.OpenIDServiceEndpoint
@type to_match: openid.consumer.discover.OpenIDServiceEndpoint
@rtype: NoneType
@raises ProtocolError: when the endpoint does not match the
discovered information.
"""
# 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)) | [
"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\n responses have a non-none `openid.op_endpoint' and\n that it is set as the `server_url' attribute of the\n `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.
@type endpoint: openid.consumer.discover.OpenIDServiceEndpoint
@type to_match: openid.consumer.discover.OpenIDServiceEndpoint
@rtype: NoneType
@raises ProtocolError: when the endpoint does not match the
discovered information. | [
"Verify",
"that",
"the",
"given",
"endpoint",
"matches",
"the",
"information",
"extracted",
"from",
"the",
"OpenID",
"assertion",
"and",
"raise",
"an",
"exception",
"if",
"there",
"is",
"a",
"mismatch",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L989-L1035 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._discoverAndVerify | def _discoverAndVerify(self, claimed_id, 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.
@type to_match: openid.consumer.discover.OpenIDServiceEndpoint
@param to_match: The endpoint whose information we're confirming
@rtype: openid.consumer.discover.OpenIDServiceEndpoint
@returns: The result of performing discovery on the claimed
identifier in `to_match'
@raises DiscoveryFailure: when discovery fails.
"""
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) | python | def _discoverAndVerify(self, claimed_id, 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.
@type to_match: openid.consumer.discover.OpenIDServiceEndpoint
@param to_match: The endpoint whose information we're confirming
@rtype: openid.consumer.discover.OpenIDServiceEndpoint
@returns: The result of performing discovery on the claimed
identifier in `to_match'
@raises DiscoveryFailure: when discovery fails.
"""
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) | [
"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.
@type to_match: openid.consumer.discover.OpenIDServiceEndpoint
@param to_match: The endpoint whose information we're confirming
@rtype: openid.consumer.discover.OpenIDServiceEndpoint
@returns: The result of performing discovery on the claimed
identifier in `to_match'
@raises DiscoveryFailure: when discovery fails. | [
"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",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1037-L1058 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._processCheckAuthResponse | def _processCheckAuthResponse(self, response, server_url):
"""Process the response message from a check_authentication
request, invalidating associations if requested.
"""
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 | python | def _processCheckAuthResponse(self, response, server_url):
"""Process the response message from a check_authentication
request, invalidating associations if requested.
"""
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 | [
"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. | [
"Process",
"the",
"response",
"message",
"from",
"a",
"check_authentication",
"request",
"invalidating",
"associations",
"if",
"requested",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1125-L1145 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._getAssociation | def _getAssociation(self, endpoint):
"""Get an association for the endpoint's server_url.
First try seeing if we have a good association in the
store. If we do not, then attempt to negotiate an association
with the server.
If we negotiate a good association, it will get stored.
@returns: A valid association for the endpoint's server_url or None
@rtype: openid.association.Association or NoneType
"""
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 | python | def _getAssociation(self, endpoint):
"""Get an association for the endpoint's server_url.
First try seeing if we have a good association in the
store. If we do not, then attempt to negotiate an association
with the server.
If we negotiate a good association, it will get stored.
@returns: A valid association for the endpoint's server_url or None
@rtype: openid.association.Association or NoneType
"""
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 | [
"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.
First try seeing if we have a good association in the
store. If we do not, then attempt to negotiate an association
with the server.
If we negotiate a good association, it will get stored.
@returns: A valid association for the endpoint's server_url or None
@rtype: openid.association.Association or NoneType | [
"Get",
"an",
"association",
"for",
"the",
"endpoint",
"s",
"server_url",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1147-L1166 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._extractSupportedAssociationType | def _extractSupportedAssociationType(self, server_error, endpoint,
assoc_type):
"""Handle ServerErrors resulting from association requests.
@returns: If server replied with an C{unsupported-type} error,
return a tuple of supported C{association_type}, C{session_type}.
Otherwise logs the error and returns None.
@rtype: tuple or None
"""
# 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 | python | def _extractSupportedAssociationType(self, server_error, endpoint,
assoc_type):
"""Handle ServerErrors resulting from association requests.
@returns: If server replied with an C{unsupported-type} error,
return a tuple of supported C{association_type}, C{session_type}.
Otherwise logs the error and returns None.
@rtype: tuple or None
"""
# 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 | [
"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.
@returns: If server replied with an C{unsupported-type} error,
return a tuple of supported C{association_type}, C{session_type}.
Otherwise logs the error and returns None.
@rtype: tuple or None | [
"Handle",
"ServerErrors",
"resulting",
"from",
"association",
"requests",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1207-L1247 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._requestAssociation | def _requestAssociation(self, endpoint, assoc_type, session_type):
"""Make and process one association request to this endpoint's
OP endpoint URL.
@returns: An association object or None if the association
processing failed.
@raises ServerError: when the remote OpenID server returns an error.
"""
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 | python | def _requestAssociation(self, endpoint, assoc_type, session_type):
"""Make and process one association request to this endpoint's
OP endpoint URL.
@returns: An association object or None if the association
processing failed.
@raises ServerError: when the remote OpenID server returns an error.
"""
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 | [
"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.
@returns: An association object or None if the association
processing failed.
@raises ServerError: when the remote OpenID server returns an error. | [
"Make",
"and",
"process",
"one",
"association",
"request",
"to",
"this",
"endpoint",
"s",
"OP",
"endpoint",
"URL",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1250-L1279 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._createAssociateRequest | def _createAssociateRequest(self, endpoint, assoc_type, session_type):
"""Create an association request for the given assoc_type and
session_type.
@param endpoint: The endpoint whose server_url will be
queried. The important bit about the endpoint is whether
it's in compatiblity mode (OpenID 1.1)
@param assoc_type: The association type that the request
should ask for.
@type assoc_type: str
@param session_type: The session type that should be used in
the association request. The session_type is used to
create an association session object, and that session
object is asked for any additional fields that it needs to
add to the request.
@type session_type: str
@returns: a pair of the association session object and the
request message that will be sent to the server.
@rtype: (association session type (depends on session_type),
openid.message.Message)
"""
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 | python | def _createAssociateRequest(self, endpoint, assoc_type, session_type):
"""Create an association request for the given assoc_type and
session_type.
@param endpoint: The endpoint whose server_url will be
queried. The important bit about the endpoint is whether
it's in compatiblity mode (OpenID 1.1)
@param assoc_type: The association type that the request
should ask for.
@type assoc_type: str
@param session_type: The session type that should be used in
the association request. The session_type is used to
create an association session object, and that session
object is asked for any additional fields that it needs to
add to the request.
@type session_type: str
@returns: a pair of the association session object and the
request message that will be sent to the server.
@rtype: (association session type (depends on session_type),
openid.message.Message)
"""
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 | [
"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.
@param endpoint: The endpoint whose server_url will be
queried. The important bit about the endpoint is whether
it's in compatiblity mode (OpenID 1.1)
@param assoc_type: The association type that the request
should ask for.
@type assoc_type: str
@param session_type: The session type that should be used in
the association request. The session_type is used to
create an association session object, and that session
object is asked for any additional fields that it needs to
add to the request.
@type session_type: str
@returns: a pair of the association session object and the
request message that will be sent to the server.
@rtype: (association session type (depends on session_type),
openid.message.Message) | [
"Create",
"an",
"association",
"request",
"for",
"the",
"given",
"assoc_type",
"and",
"session_type",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1281-L1324 | train |
openid/python-openid | openid/consumer/consumer.py | GenericConsumer._extractAssociation | def _extractAssociation(self, assoc_response, assoc_session):
"""Attempt to extract an association from the response, given
the association response message and the established
association session.
@param assoc_response: The association response message from
the server
@type assoc_response: openid.message.Message
@param assoc_session: The association session object that was
used when making the request
@type assoc_session: depends on the session type of the request
@raises ProtocolError: when data is malformed
@raises KeyError: when a field is missing
@rtype: openid.association.Association
"""
# 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) | python | def _extractAssociation(self, assoc_response, assoc_session):
"""Attempt to extract an association from the response, given
the association response message and the established
association session.
@param assoc_response: The association response message from
the server
@type assoc_response: openid.message.Message
@param assoc_session: The association session object that was
used when making the request
@type assoc_session: depends on the session type of the request
@raises ProtocolError: when data is malformed
@raises KeyError: when a field is missing
@rtype: openid.association.Association
"""
# 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) | [
"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.
@param assoc_response: The association response message from
the server
@type assoc_response: openid.message.Message
@param assoc_session: The association session object that was
used when making the request
@type assoc_session: depends on the session type of the request
@raises ProtocolError: when data is malformed
@raises KeyError: when a field is missing
@rtype: openid.association.Association | [
"Attempt",
"to",
"extract",
"an",
"association",
"from",
"the",
"response",
"given",
"the",
"association",
"response",
"message",
"and",
"the",
"established",
"association",
"session",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1364-L1440 | train |
openid/python-openid | openid/consumer/consumer.py | AuthRequest.setAnonymous | def setAnonymous(self, 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.
Anonymous requests are not allowed when the request is made
with OpenID 1.
@raises ValueError: when attempting to set an OpenID1 request
as 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 | python | def setAnonymous(self, 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.
Anonymous requests are not allowed when the request is made
with OpenID 1.
@raises ValueError: when attempting to set an OpenID1 request
as 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 | [
"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.
Anonymous requests are not allowed when the request is made
with OpenID 1.
@raises ValueError: when attempting to set an OpenID1 request
as 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",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1469-L1485 | train |
openid/python-openid | openid/consumer/consumer.py | AuthRequest.addExtensionArg | def addExtensionArg(self, namespace, key, value):
"""Add an extension argument to this OpenID authentication
request.
Use caution when adding arguments, because they will be
URL-escaped and appended to the redirect URL, which can easily
get quite long.
@param namespace: The namespace for the extension. For
example, the simple registration extension uses the
namespace C{sreg}.
@type namespace: str
@param key: The key within the extension namespace. For
example, the nickname field in the simple registration
extension's key is C{nickname}.
@type key: str
@param value: The value to provide to the server for this
argument.
@type value: str
"""
self.message.setArg(namespace, key, value) | python | def addExtensionArg(self, namespace, key, value):
"""Add an extension argument to this OpenID authentication
request.
Use caution when adding arguments, because they will be
URL-escaped and appended to the redirect URL, which can easily
get quite long.
@param namespace: The namespace for the extension. For
example, the simple registration extension uses the
namespace C{sreg}.
@type namespace: str
@param key: The key within the extension namespace. For
example, the nickname field in the simple registration
extension's key is C{nickname}.
@type key: str
@param value: The value to provide to the server for this
argument.
@type value: str
"""
self.message.setArg(namespace, key, value) | [
"def",
"addExtensionArg",
"(",
"self",
",",
"namespace",
",",
"key",
",",
"value",
")",
":",
"self",
".",
"message",
".",
"setArg",
"(",
"namespace",
",",
"key",
",",
"value",
")"
] | Add an extension argument to this OpenID authentication
request.
Use caution when adding arguments, because they will be
URL-escaped and appended to the redirect URL, which can easily
get quite long.
@param namespace: The namespace for the extension. For
example, the simple registration extension uses the
namespace C{sreg}.
@type namespace: str
@param key: The key within the extension namespace. For
example, the nickname field in the simple registration
extension's key is C{nickname}.
@type key: str
@param value: The value to provide to the server for this
argument.
@type value: str | [
"Add",
"an",
"extension",
"argument",
"to",
"this",
"OpenID",
"authentication",
"request",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1496-L1521 | train |
openid/python-openid | openid/consumer/consumer.py | AuthRequest.redirectURL | def redirectURL(self, realm, return_to=None, immediate=False):
"""Returns a URL with an encoded OpenID request.
The resulting URL is the OpenID provider's endpoint URL with
parameters appended as query arguments. You should redirect
the user agent to this URL.
OpenID 2.0 endpoints also accept POST requests, see
C{L{shouldSendRedirect}} and C{L{formMarkup}}.
@param realm: The URL (or URL pattern) that identifies your
web site to the user when she is authorizing it.
@type realm: str
@param return_to: The URL that the OpenID provider will send the
user back to after attempting to verify her identity.
Not specifying a return_to URL means that the user will not
be returned to the site issuing the request upon its
completion.
@type return_to: str
@param immediate: If True, the OpenID provider is to send back
a response immediately, useful for behind-the-scenes
authentication attempts. Otherwise the OpenID provider
may engage the user before providing a response. This is
the default case, as the user may need to provide
credentials or approve the request before a positive
response can be sent.
@type immediate: bool
@returns: The URL to redirect the user agent to.
@returntype: str
"""
message = self.getMessage(realm, return_to, immediate)
return message.toURL(self.endpoint.server_url) | python | def redirectURL(self, realm, return_to=None, immediate=False):
"""Returns a URL with an encoded OpenID request.
The resulting URL is the OpenID provider's endpoint URL with
parameters appended as query arguments. You should redirect
the user agent to this URL.
OpenID 2.0 endpoints also accept POST requests, see
C{L{shouldSendRedirect}} and C{L{formMarkup}}.
@param realm: The URL (or URL pattern) that identifies your
web site to the user when she is authorizing it.
@type realm: str
@param return_to: The URL that the OpenID provider will send the
user back to after attempting to verify her identity.
Not specifying a return_to URL means that the user will not
be returned to the site issuing the request upon its
completion.
@type return_to: str
@param immediate: If True, the OpenID provider is to send back
a response immediately, useful for behind-the-scenes
authentication attempts. Otherwise the OpenID provider
may engage the user before providing a response. This is
the default case, as the user may need to provide
credentials or approve the request before a positive
response can be sent.
@type immediate: bool
@returns: The URL to redirect the user agent to.
@returntype: str
"""
message = self.getMessage(realm, return_to, immediate)
return message.toURL(self.endpoint.server_url) | [
"def",
"redirectURL",
"(",
"self",
",",
"realm",
",",
"return_to",
"=",
"None",
",",
"immediate",
"=",
"False",
")",
":",
"message",
"=",
"self",
".",
"getMessage",
"(",
"realm",
",",
"return_to",
",",
"immediate",
")",
"return",
"message",
".",
"toURL",
"(",
"self",
".",
"endpoint",
".",
"server_url",
")"
] | Returns a URL with an encoded OpenID request.
The resulting URL is the OpenID provider's endpoint URL with
parameters appended as query arguments. You should redirect
the user agent to this URL.
OpenID 2.0 endpoints also accept POST requests, see
C{L{shouldSendRedirect}} and C{L{formMarkup}}.
@param realm: The URL (or URL pattern) that identifies your
web site to the user when she is authorizing it.
@type realm: str
@param return_to: The URL that the OpenID provider will send the
user back to after attempting to verify her identity.
Not specifying a return_to URL means that the user will not
be returned to the site issuing the request upon its
completion.
@type return_to: str
@param immediate: If True, the OpenID provider is to send back
a response immediately, useful for behind-the-scenes
authentication attempts. Otherwise the OpenID provider
may engage the user before providing a response. This is
the default case, as the user may need to provide
credentials or approve the request before a positive
response can be sent.
@type immediate: bool
@returns: The URL to redirect the user agent to.
@returntype: str | [
"Returns",
"a",
"URL",
"with",
"an",
"encoded",
"OpenID",
"request",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1608-L1647 | train |