sreg.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. """Simple registration request and response parsing and object representation
  2. This module contains objects representing simple registration requests
  3. and responses that can be used with both OpenID relying parties and
  4. OpenID providers.
  5. 1. The relying party creates a request object and adds it to the
  6. C{L{AuthRequest<openid.consumer.consumer.AuthRequest>}} object
  7. before making the C{checkid_} request to the OpenID provider::
  8. auth_request.addExtension(SRegRequest(required=['email']))
  9. 2. The OpenID provider extracts the simple registration request from
  10. the OpenID request using C{L{SRegRequest.fromOpenIDRequest}},
  11. gets the user's approval and data, creates a C{L{SRegResponse}}
  12. object and adds it to the C{id_res} response::
  13. sreg_req = SRegRequest.fromOpenIDRequest(checkid_request)
  14. # [ get the user's approval and data, informing the user that
  15. # the fields in sreg_response were requested ]
  16. sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
  17. sreg_resp.toMessage(openid_response.fields)
  18. 3. The relying party uses C{L{SRegResponse.fromSuccessResponse}} to
  19. extract the data from the OpenID response::
  20. sreg_resp = SRegResponse.fromSuccessResponse(success_response)
  21. @since: 2.0
  22. @var sreg_data_fields: The names of the data fields that are listed in
  23. the sreg spec, and a description of them in English
  24. @var sreg_uri: The preferred URI to use for the simple registration
  25. namespace and XRD Type value
  26. """
  27. from openid.message import registerNamespaceAlias, \
  28. NamespaceAliasRegistrationError
  29. from openid.extension import Extension
  30. import logging
  31. logger = logging.getLogger(__name__)
  32. try:
  33. str #pylint:disable-msg=W0104
  34. except NameError:
  35. # For Python 2.2
  36. str = (str, str) #pylint:disable-msg=W0622
  37. __all__ = [
  38. 'SRegRequest',
  39. 'SRegResponse',
  40. 'data_fields',
  41. 'ns_uri',
  42. 'ns_uri_1_0',
  43. 'ns_uri_1_1',
  44. 'supportsSReg',
  45. ]
  46. # The data fields that are listed in the sreg spec
  47. data_fields = {
  48. 'fullname': 'Full Name',
  49. 'nickname': 'Nickname',
  50. 'dob': 'Date of Birth',
  51. 'email': 'E-mail Address',
  52. 'gender': 'Gender',
  53. 'postcode': 'Postal Code',
  54. 'country': 'Country',
  55. 'language': 'Language',
  56. 'timezone': 'Time Zone',
  57. }
  58. def checkFieldName(field_name):
  59. """Check to see that the given value is a valid simple
  60. registration data field name.
  61. @raise ValueError: if the field name is not a valid simple
  62. registration data field name
  63. """
  64. if field_name not in data_fields:
  65. raise ValueError('%r is not a defined simple registration field' %
  66. (field_name, ))
  67. # URI used in the wild for Yadis documents advertising simple
  68. # registration support
  69. ns_uri_1_0 = 'http://openid.net/sreg/1.0'
  70. # URI in the draft specification for simple registration 1.1
  71. # <http://openid.net/specs/openid-simple-registration-extension-1_1-01.html>
  72. ns_uri_1_1 = 'http://openid.net/extensions/sreg/1.1'
  73. # This attribute will always hold the preferred URI to use when adding
  74. # sreg support to an XRDS file or in an OpenID namespace declaration.
  75. ns_uri = ns_uri_1_1
  76. try:
  77. registerNamespaceAlias(ns_uri_1_1, 'sreg')
  78. except NamespaceAliasRegistrationError as e:
  79. logger.exception('registerNamespaceAlias(%r, %r) failed: %s' %
  80. (ns_uri_1_1, 'sreg', str(e), ))
  81. def supportsSReg(endpoint):
  82. """Does the given endpoint advertise support for simple
  83. registration?
  84. @param endpoint: The endpoint object as returned by OpenID discovery
  85. @type endpoint: openid.consumer.discover.OpenIDEndpoint
  86. @returns: Whether an sreg type was advertised by the endpoint
  87. @rtype: bool
  88. """
  89. return (endpoint.usesExtension(ns_uri_1_1) or
  90. endpoint.usesExtension(ns_uri_1_0))
  91. class SRegNamespaceError(ValueError):
  92. """The simple registration namespace was not found and could not
  93. be created using the expected name (there's another extension
  94. using the name 'sreg')
  95. This is not I{illegal}, for OpenID 2, although it probably
  96. indicates a problem, since it's not expected that other extensions
  97. will re-use the alias that is in use for OpenID 1.
  98. If this is an OpenID 1 request, then there is no recourse. This
  99. should not happen unless some code has modified the namespaces for
  100. the message that is being processed.
  101. """
  102. def getSRegNS(message):
  103. """Extract the simple registration namespace URI from the given
  104. OpenID message. Handles OpenID 1 and 2, as well as both sreg
  105. namespace URIs found in the wild, as well as missing namespace
  106. definitions (for OpenID 1)
  107. @param message: The OpenID message from which to parse simple
  108. registration fields. This may be a request or response message.
  109. @type message: C{L{openid.message.Message}}
  110. @returns: the sreg namespace URI for the supplied message. The
  111. message may be modified to define a simple registration
  112. namespace.
  113. @rtype: C{str}
  114. @raise ValueError: when using OpenID 1 if the message defines
  115. the 'sreg' alias to be something other than a simple
  116. registration type.
  117. """
  118. # See if there exists an alias for one of the two defined simple
  119. # registration types.
  120. for sreg_ns_uri in [ns_uri_1_1, ns_uri_1_0]:
  121. alias = message.namespaces.getAlias(sreg_ns_uri)
  122. if alias is not None:
  123. break
  124. else:
  125. # There is no alias for either of the types, so try to add
  126. # one. We default to using the modern value (1.1)
  127. sreg_ns_uri = ns_uri_1_1
  128. try:
  129. message.namespaces.addAlias(ns_uri_1_1, 'sreg')
  130. except KeyError as why:
  131. # An alias for the string 'sreg' already exists, but it's
  132. # defined for something other than simple registration
  133. raise SRegNamespaceError(why)
  134. # we know that sreg_ns_uri defined, because it's defined in the
  135. # else clause of the loop as well, so disable the warning
  136. return sreg_ns_uri #pylint:disable-msg=W0631
  137. class SRegRequest(Extension):
  138. """An object to hold the state of a simple registration request.
  139. @ivar required: A list of the required fields in this simple
  140. registration request
  141. @type required: [str]
  142. @ivar optional: A list of the optional fields in this simple
  143. registration request
  144. @type optional: [str]
  145. @ivar policy_url: The policy URL that was provided with the request
  146. @type policy_url: str or NoneType
  147. @group Consumer: requestField, requestFields, getExtensionArgs, addToOpenIDRequest
  148. @group Server: fromOpenIDRequest, parseExtensionArgs
  149. """
  150. ns_alias = 'sreg'
  151. def __init__(self,
  152. required=None,
  153. optional=None,
  154. policy_url=None,
  155. sreg_ns_uri=ns_uri):
  156. """Initialize an empty simple registration request"""
  157. Extension.__init__(self)
  158. self.required = []
  159. self.optional = []
  160. self.policy_url = policy_url
  161. self.ns_uri = sreg_ns_uri
  162. if required:
  163. self.requestFields(required, required=True, strict=True)
  164. if optional:
  165. self.requestFields(optional, required=False, strict=True)
  166. # Assign getSRegNS to a static method so that it can be
  167. # overridden for testing.
  168. _getSRegNS = staticmethod(getSRegNS)
  169. def fromOpenIDRequest(cls, request):
  170. """Create a simple registration request that contains the
  171. fields that were requested in the OpenID request with the
  172. given arguments
  173. @param request: The OpenID request
  174. @type request: openid.server.CheckIDRequest
  175. @returns: The newly created simple registration request
  176. @rtype: C{L{SRegRequest}}
  177. """
  178. self = cls()
  179. # Since we're going to mess with namespace URI mapping, don't
  180. # mutate the object that was passed in.
  181. message = request.message.copy()
  182. self.ns_uri = self._getSRegNS(message)
  183. args = message.getArgs(self.ns_uri)
  184. self.parseExtensionArgs(args)
  185. return self
  186. fromOpenIDRequest = classmethod(fromOpenIDRequest)
  187. def parseExtensionArgs(self, args, strict=False):
  188. """Parse the unqualified simple registration request
  189. parameters and add them to this object.
  190. This method is essentially the inverse of
  191. C{L{getExtensionArgs}}. This method restores the serialized simple
  192. registration request fields.
  193. If you are extracting arguments from a standard OpenID
  194. checkid_* request, you probably want to use C{L{fromOpenIDRequest}},
  195. which will extract the sreg namespace and arguments from the
  196. OpenID request. This method is intended for cases where the
  197. OpenID server needs more control over how the arguments are
  198. parsed than that method provides.
  199. >>> args = message.getArgs(ns_uri)
  200. >>> request.parseExtensionArgs(args)
  201. @param args: The unqualified simple registration arguments
  202. @type args: {str:str}
  203. @param strict: Whether requests with fields that are not
  204. defined in the simple registration specification should be
  205. tolerated (and ignored)
  206. @type strict: bool
  207. @returns: None; updates this object
  208. """
  209. for list_name in ['required', 'optional']:
  210. required = (list_name == 'required')
  211. items = args.get(list_name)
  212. if items:
  213. for field_name in items.split(','):
  214. try:
  215. self.requestField(field_name, required, strict)
  216. except ValueError:
  217. if strict:
  218. raise
  219. self.policy_url = args.get('policy_url')
  220. def allRequestedFields(self):
  221. """A list of all of the simple registration fields that were
  222. requested, whether they were required or optional.
  223. @rtype: [str]
  224. """
  225. return self.required + self.optional
  226. def wereFieldsRequested(self):
  227. """Have any simple registration fields been requested?
  228. @rtype: bool
  229. """
  230. return bool(self.allRequestedFields())
  231. def __contains__(self, field_name):
  232. """Was this field in the request?"""
  233. return (field_name in self.required or field_name in self.optional)
  234. def requestField(self, field_name, required=False, strict=False):
  235. """Request the specified field from the OpenID user
  236. @param field_name: the unqualified simple registration field name
  237. @type field_name: str
  238. @param required: whether the given field should be presented
  239. to the user as being a required to successfully complete
  240. the request
  241. @param strict: whether to raise an exception when a field is
  242. added to a request more than once
  243. @raise ValueError: when the field requested is not a simple
  244. registration field or strict is set and the field was
  245. requested more than once
  246. """
  247. checkFieldName(field_name)
  248. if strict:
  249. if field_name in self.required or field_name in self.optional:
  250. raise ValueError('That field has already been requested')
  251. else:
  252. if field_name in self.required:
  253. return
  254. if field_name in self.optional:
  255. if required:
  256. self.optional.remove(field_name)
  257. else:
  258. return
  259. if required:
  260. self.required.append(field_name)
  261. else:
  262. self.optional.append(field_name)
  263. def requestFields(self, field_names, required=False, strict=False):
  264. """Add the given list of fields to the request
  265. @param field_names: The simple registration data fields to request
  266. @type field_names: [str]
  267. @param required: Whether these values should be presented to
  268. the user as required
  269. @param strict: whether to raise an exception when a field is
  270. added to a request more than once
  271. @raise ValueError: when a field requested is not a simple
  272. registration field or strict is set and a field was
  273. requested more than once
  274. """
  275. if isinstance(field_names, str):
  276. raise TypeError('Fields should be passed as a list of '
  277. 'strings (not %r)' % (type(field_names), ))
  278. for field_name in field_names:
  279. self.requestField(field_name, required, strict=strict)
  280. def getExtensionArgs(self):
  281. """Get a dictionary of unqualified simple registration
  282. arguments representing this request.
  283. This method is essentially the inverse of
  284. C{L{parseExtensionArgs}}. This method serializes the simple
  285. registration request fields.
  286. @rtype: {str:str}
  287. """
  288. args = {}
  289. if self.required:
  290. args['required'] = ','.join(self.required)
  291. if self.optional:
  292. args['optional'] = ','.join(self.optional)
  293. if self.policy_url:
  294. args['policy_url'] = self.policy_url
  295. return args
  296. class SRegResponse(Extension):
  297. """Represents the data returned in a simple registration response
  298. inside of an OpenID C{id_res} response. This object will be
  299. created by the OpenID server, added to the C{id_res} response
  300. object, and then extracted from the C{id_res} message by the
  301. Consumer.
  302. @ivar data: The simple registration data, keyed by the unqualified
  303. simple registration name of the field (i.e. nickname is keyed
  304. by C{'nickname'})
  305. @ivar ns_uri: The URI under which the simple registration data was
  306. stored in the response message.
  307. @group Server: extractResponse
  308. @group Consumer: fromSuccessResponse
  309. @group Read-only dictionary interface: keys, iterkeys, items, iteritems,
  310. __iter__, get, __getitem__, keys, has_key
  311. """
  312. ns_alias = 'sreg'
  313. def __init__(self, data=None, sreg_ns_uri=ns_uri):
  314. Extension.__init__(self)
  315. if data is None:
  316. self.data = {}
  317. else:
  318. self.data = data
  319. self.ns_uri = sreg_ns_uri
  320. def extractResponse(cls, request, data):
  321. """Take a C{L{SRegRequest}} and a dictionary of simple
  322. registration values and create a C{L{SRegResponse}}
  323. object containing that data.
  324. @param request: The simple registration request object
  325. @type request: SRegRequest
  326. @param data: The simple registration data for this
  327. response, as a dictionary from unqualified simple
  328. registration field name to string (unicode) value. For
  329. instance, the nickname should be stored under the key
  330. 'nickname'.
  331. @type data: {str:str}
  332. @returns: a simple registration response object
  333. @rtype: SRegResponse
  334. """
  335. self = cls()
  336. self.ns_uri = request.ns_uri
  337. for field in request.allRequestedFields():
  338. value = data.get(field)
  339. if value is not None:
  340. self.data[field] = value
  341. return self
  342. extractResponse = classmethod(extractResponse)
  343. # Assign getSRegArgs to a static method so that it can be
  344. # overridden for testing
  345. _getSRegNS = staticmethod(getSRegNS)
  346. def fromSuccessResponse(cls, success_response, signed_only=True):
  347. """Create a C{L{SRegResponse}} object from a successful OpenID
  348. library response
  349. (C{L{openid.consumer.consumer.SuccessResponse}}) response
  350. message
  351. @param success_response: A SuccessResponse from consumer.complete()
  352. @type success_response: C{L{openid.consumer.consumer.SuccessResponse}}
  353. @param signed_only: Whether to process only data that was
  354. signed in the id_res message from the server.
  355. @type signed_only: bool
  356. @rtype: SRegResponse
  357. @returns: A simple registration response containing the data
  358. that was supplied with the C{id_res} response.
  359. """
  360. self = cls()
  361. self.ns_uri = self._getSRegNS(success_response.message)
  362. if signed_only:
  363. args = success_response.getSignedNS(self.ns_uri)
  364. else:
  365. args = success_response.message.getArgs(self.ns_uri)
  366. if not args:
  367. return None
  368. for field_name in data_fields:
  369. if field_name in args:
  370. self.data[field_name] = args[field_name]
  371. return self
  372. fromSuccessResponse = classmethod(fromSuccessResponse)
  373. def getExtensionArgs(self):
  374. """Get the fields to put in the simple registration namespace
  375. when adding them to an id_res message.
  376. @see: openid.extension
  377. """
  378. return self.data
  379. # Read-only dictionary interface
  380. def get(self, field_name, default=None):
  381. """Like dict.get, except that it checks that the field name is
  382. defined by the simple registration specification"""
  383. checkFieldName(field_name)
  384. return self.data.get(field_name, default)
  385. def items(self):
  386. """All of the data values in this simple registration response
  387. """
  388. return list(self.data.items())
  389. def iteritems(self):
  390. return iter(self.data.items())
  391. def keys(self):
  392. return list(self.data.keys())
  393. def iterkeys(self):
  394. return iter(self.data.keys())
  395. def has_key(self, key):
  396. return key in self
  397. def __contains__(self, field_name):
  398. checkFieldName(field_name)
  399. return field_name in self.data
  400. def __iter__(self):
  401. return iter(self.data)
  402. def __getitem__(self, field_name):
  403. checkFieldName(field_name)
  404. return self.data[field_name]
  405. def __bool__(self):
  406. return bool(self.data)