1 """Simple registration request and response parsing and object representation
3 This module contains objects representing simple registration requests
4 and responses that can be used with both OpenID relying parties and
7 1. The relying party creates a request object and adds it to the
8 C{L{AuthRequest<openid.consumer.consumer.AuthRequest>}} object
9 before making the C{checkid_} request to the OpenID provider::
11 auth_request.addExtension(SRegRequest(required=['email']))
13 2. The OpenID provider extracts the simple registration request from
14 the OpenID request using C{L{SRegRequest.fromOpenIDRequest}},
15 gets the user's approval and data, creates a C{L{SRegResponse}}
16 object and adds it to the C{id_res} response::
18 sreg_req = SRegRequest.fromOpenIDRequest(checkid_request)
19 # [ get the user's approval and data, informing the user that
20 # the fields in sreg_response were requested ]
21 sreg_resp = SRegResponse.extractResponse(sreg_req, user_data)
22 sreg_resp.toMessage(openid_response.fields)
24 3. The relying party uses C{L{SRegResponse.fromSuccessResponse}} to
25 extract the data from the OpenID response::
27 sreg_resp = SRegResponse.fromSuccessResponse(success_response)
31 @var sreg_data_fields: The names of the data fields that are listed in
32 the sreg spec, and a description of them in English
34 @var sreg_uri: The preferred URI to use for the simple registration
35 namespace and XRD Type value
38 from openid
.message
import registerNamespaceAlias
, \
39 NamespaceAliasRegistrationError
40 from openid
.extension
import Extension
41 from openid
import oidutil
44 basestring
#pylint:disable-msg=W0104
47 basestring
= (str, unicode) #pylint:disable-msg=W0622
59 # The data fields that are listed in the sreg spec
61 'fullname':'Full Name',
62 'nickname':'Nickname',
63 'dob':'Date of Birth',
64 'email':'E-mail Address',
66 'postcode':'Postal Code',
68 'language':'Language',
69 'timezone':'Time Zone',
72 def checkFieldName(field_name
):
73 """Check to see that the given value is a valid simple
74 registration data field name.
76 @raise ValueError: if the field name is not a valid simple
77 registration data field name
79 if field_name
not in data_fields
:
80 raise ValueError('%r is not a defined simple registration field' %
83 # URI used in the wild for Yadis documents advertising simple
84 # registration support
85 ns_uri_1_0
= 'http://openid.net/sreg/1.0'
87 # URI in the draft specification for simple registration 1.1
88 # <http://openid.net/specs/openid-simple-registration-extension-1_1-01.html>
89 ns_uri_1_1
= 'http://openid.net/extensions/sreg/1.1'
91 # This attribute will always hold the preferred URI to use when adding
92 # sreg support to an XRDS file or in an OpenID namespace declaration.
96 registerNamespaceAlias(ns_uri_1_1
, 'sreg')
97 except NamespaceAliasRegistrationError
, e
:
98 oidutil
.log('registerNamespaceAlias(%r, %r) failed: %s' % (ns_uri_1_1
,
101 def supportsSReg(endpoint
):
102 """Does the given endpoint advertise support for simple
105 @param endpoint: The endpoint object as returned by OpenID discovery
106 @type endpoint: openid.consumer.discover.OpenIDEndpoint
108 @returns: Whether an sreg type was advertised by the endpoint
111 return (endpoint
.usesExtension(ns_uri_1_1
) or
112 endpoint
.usesExtension(ns_uri_1_0
))
114 class SRegNamespaceError(ValueError):
115 """The simple registration namespace was not found and could not
116 be created using the expected name (there's another extension
117 using the name 'sreg')
119 This is not I{illegal}, for OpenID 2, although it probably
120 indicates a problem, since it's not expected that other extensions
121 will re-use the alias that is in use for OpenID 1.
123 If this is an OpenID 1 request, then there is no recourse. This
124 should not happen unless some code has modified the namespaces for
125 the message that is being processed.
128 def getSRegNS(message
):
129 """Extract the simple registration namespace URI from the given
130 OpenID message. Handles OpenID 1 and 2, as well as both sreg
131 namespace URIs found in the wild, as well as missing namespace
132 definitions (for OpenID 1)
134 @param message: The OpenID message from which to parse simple
135 registration fields. This may be a request or response message.
136 @type message: C{L{openid.message.Message}}
138 @returns: the sreg namespace URI for the supplied message. The
139 message may be modified to define a simple registration
143 @raise ValueError: when using OpenID 1 if the message defines
144 the 'sreg' alias to be something other than a simple
147 # See if there exists an alias for one of the two defined simple
148 # registration types.
149 for sreg_ns_uri
in [ns_uri_1_1
, ns_uri_1_0
]:
150 alias
= message
.namespaces
.getAlias(sreg_ns_uri
)
151 if alias
is not None:
154 # There is no alias for either of the types, so try to add
155 # one. We default to using the modern value (1.1)
156 sreg_ns_uri
= ns_uri_1_1
158 message
.namespaces
.addAlias(ns_uri_1_1
, 'sreg')
159 except KeyError, why
:
160 # An alias for the string 'sreg' already exists, but it's
161 # defined for something other than simple registration
162 raise SRegNamespaceError(why
[0])
164 # we know that sreg_ns_uri defined, because it's defined in the
165 # else clause of the loop as well, so disable the warning
166 return sreg_ns_uri
#pylint:disable-msg=W0631
168 class SRegRequest(Extension
):
169 """An object to hold the state of a simple registration request.
171 @ivar required: A list of the required fields in this simple
173 @type required: [str]
175 @ivar optional: A list of the optional fields in this simple
177 @type optional: [str]
179 @ivar policy_url: The policy URL that was provided with the request
180 @type policy_url: str or NoneType
182 @group Consumer: requestField, requestFields, getExtensionArgs, addToOpenIDRequest
183 @group Server: fromOpenIDRequest, parseExtensionArgs
188 def __init__(self
, required
=None, optional
=None, policy_url
=None,
190 """Initialize an empty simple registration request"""
191 Extension
.__init
__(self
)
194 self
.policy_url
= policy_url
195 self
.ns_uri
= sreg_ns_uri
198 self
.requestFields(required
, required
=True, strict
=True)
201 self
.requestFields(optional
, required
=False, strict
=True)
203 # Assign getSRegNS to a static method so that it can be
204 # overridden for testing.
205 _getSRegNS
= staticmethod(getSRegNS
)
207 def fromOpenIDRequest(cls
, request
):
208 """Create a simple registration request that contains the
209 fields that were requested in the OpenID request with the
212 @param request: The OpenID request
213 @type request: openid.server.CheckIDRequest
215 @returns: The newly created simple registration request
216 @rtype: C{L{SRegRequest}}
220 # Since we're going to mess with namespace URI mapping, don't
221 # mutate the object that was passed in.
222 message
= request
.message
.copy()
224 self
.ns_uri
= self
._getSRegNS
(message
)
225 args
= message
.getArgs(self
.ns_uri
)
226 self
.parseExtensionArgs(args
)
230 fromOpenIDRequest
= classmethod(fromOpenIDRequest
)
232 def parseExtensionArgs(self
, args
, strict
=False):
233 """Parse the unqualified simple registration request
234 parameters and add them to this object.
236 This method is essentially the inverse of
237 C{L{getExtensionArgs}}. This method restores the serialized simple
238 registration request fields.
240 If you are extracting arguments from a standard OpenID
241 checkid_* request, you probably want to use C{L{fromOpenIDRequest}},
242 which will extract the sreg namespace and arguments from the
243 OpenID request. This method is intended for cases where the
244 OpenID server needs more control over how the arguments are
245 parsed than that method provides.
247 >>> args = message.getArgs(ns_uri)
248 >>> request.parseExtensionArgs(args)
250 @param args: The unqualified simple registration arguments
251 @type args: {str:str}
253 @param strict: Whether requests with fields that are not
254 defined in the simple registration specification should be
255 tolerated (and ignored)
258 @returns: None; updates this object
260 for list_name
in ['required', 'optional']:
261 required
= (list_name
== 'required')
262 items
= args
.get(list_name
)
264 for field_name
in items
.split(','):
266 self
.requestField(field_name
, required
, strict
)
271 self
.policy_url
= args
.get('policy_url')
273 def allRequestedFields(self
):
274 """A list of all of the simple registration fields that were
275 requested, whether they were required or optional.
279 return self
.required
+ self
.optional
281 def wereFieldsRequested(self
):
282 """Have any simple registration fields been requested?
286 return bool(self
.allRequestedFields())
288 def __contains__(self
, field_name
):
289 """Was this field in the request?"""
290 return (field_name
in self
.required
or
291 field_name
in self
.optional
)
293 def requestField(self
, field_name
, required
=False, strict
=False):
294 """Request the specified field from the OpenID user
296 @param field_name: the unqualified simple registration field name
297 @type field_name: str
299 @param required: whether the given field should be presented
300 to the user as being a required to successfully complete
303 @param strict: whether to raise an exception when a field is
304 added to a request more than once
306 @raise ValueError: when the field requested is not a simple
307 registration field or strict is set and the field was
308 requested more than once
310 checkFieldName(field_name
)
313 if field_name
in self
.required
or field_name
in self
.optional
:
314 raise ValueError('That field has already been requested')
316 if field_name
in self
.required
:
319 if field_name
in self
.optional
:
321 self
.optional
.remove(field_name
)
326 self
.required
.append(field_name
)
328 self
.optional
.append(field_name
)
330 def requestFields(self
, field_names
, required
=False, strict
=False):
331 """Add the given list of fields to the request
333 @param field_names: The simple registration data fields to request
334 @type field_names: [str]
336 @param required: Whether these values should be presented to
339 @param strict: whether to raise an exception when a field is
340 added to a request more than once
342 @raise ValueError: when a field requested is not a simple
343 registration field or strict is set and a field was
344 requested more than once
346 if isinstance(field_names
, basestring
):
347 raise TypeError('Fields should be passed as a list of '
348 'strings (not %r)' % (type(field_names
),))
350 for field_name
in field_names
:
351 self
.requestField(field_name
, required
, strict
=strict
)
353 def getExtensionArgs(self
):
354 """Get a dictionary of unqualified simple registration
355 arguments representing this request.
357 This method is essentially the inverse of
358 C{L{parseExtensionArgs}}. This method serializes the simple
359 registration request fields.
366 args
['required'] = ','.join(self
.required
)
369 args
['optional'] = ','.join(self
.optional
)
372 args
['policy_url'] = self
.policy_url
376 class SRegResponse(Extension
):
377 """Represents the data returned in a simple registration response
378 inside of an OpenID C{id_res} response. This object will be
379 created by the OpenID server, added to the C{id_res} response
380 object, and then extracted from the C{id_res} message by the
383 @ivar data: The simple registration data, keyed by the unqualified
384 simple registration name of the field (i.e. nickname is keyed
387 @ivar ns_uri: The URI under which the simple registration data was
388 stored in the response message.
390 @group Server: extractResponse
391 @group Consumer: fromSuccessResponse
392 @group Read-only dictionary interface: keys, iterkeys, items, iteritems,
393 __iter__, get, __getitem__, keys, has_key
398 def __init__(self
, data
=None, sreg_ns_uri
=ns_uri
):
399 Extension
.__init
__(self
)
405 self
.ns_uri
= sreg_ns_uri
407 def extractResponse(cls
, request
, data
):
408 """Take a C{L{SRegRequest}} and a dictionary of simple
409 registration values and create a C{L{SRegResponse}}
410 object containing that data.
412 @param request: The simple registration request object
413 @type request: SRegRequest
415 @param data: The simple registration data for this
416 response, as a dictionary from unqualified simple
417 registration field name to string (unicode) value. For
418 instance, the nickname should be stored under the key
420 @type data: {str:str}
422 @returns: a simple registration response object
426 self
.ns_uri
= request
.ns_uri
427 for field
in request
.allRequestedFields():
428 value
= data
.get(field
)
429 if value
is not None:
430 self
.data
[field
] = value
433 extractResponse
= classmethod(extractResponse
)
435 # Assign getSRegArgs to a static method so that it can be
436 # overridden for testing
437 _getSRegNS
= staticmethod(getSRegNS
)
439 def fromSuccessResponse(cls
, success_response
, signed_only
=True):
440 """Create a C{L{SRegResponse}} object from a successful OpenID
442 (C{L{openid.consumer.consumer.SuccessResponse}}) response
445 @param success_response: A SuccessResponse from consumer.complete()
446 @type success_response: C{L{openid.consumer.consumer.SuccessResponse}}
448 @param signed_only: Whether to process only data that was
449 signed in the id_res message from the server.
450 @type signed_only: bool
453 @returns: A simple registration response containing the data
454 that was supplied with the C{id_res} response.
457 self
.ns_uri
= self
._getSRegNS
(success_response
.message
)
459 args
= success_response
.getSignedNS(self
.ns_uri
)
461 args
= success_response
.message
.getArgs(self
.ns_uri
)
466 for field_name
in data_fields
:
467 if field_name
in args
:
468 self
.data
[field_name
] = args
[field_name
]
472 fromSuccessResponse
= classmethod(fromSuccessResponse
)
474 def getExtensionArgs(self
):
475 """Get the fields to put in the simple registration namespace
476 when adding them to an id_res message.
478 @see: openid.extension
482 # Read-only dictionary interface
483 def get(self
, field_name
, default
=None):
484 """Like dict.get, except that it checks that the field name is
485 defined by the simple registration specification"""
486 checkFieldName(field_name
)
487 return self
.data
.get(field_name
, default
)
490 """All of the data values in this simple registration response
492 return self
.data
.items()
495 return self
.data
.iteritems()
498 return self
.data
.keys()
501 return self
.data
.iterkeys()
503 def has_key(self
, key
):
506 def __contains__(self
, field_name
):
507 checkFieldName(field_name
)
508 return field_name
in self
.data
511 return iter(self
.data
)
513 def __getitem__(self
, field_name
):
514 checkFieldName(field_name
)
515 return self
.data
[field_name
]
517 def __nonzero__(self
):
518 return bool(self
.data
)