1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
|
# Copyright (c) 2013, Patrick Uiterwijk <puiterwijk@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of Patrick Uiterwijk nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL Patrick Uiterwijk BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Teams extension request and response parsing and object representation
This module contains objects representing team extension requests
and responses that can be used with both OpenID relying parties and
OpenID providers.
1. The relying party creates a request object and adds it to the
C{L{AuthRequest<openid.consumer.consumer.AuthRequest>}} object
before making the C{checkid_} request to the OpenID provider::
auth_request.addExtension(TeamsRequest(requested=['team']))
2. The OpenID provider extracts the teams extension request from
the OpenID request using C{L{TeamsRequest.fromOpenIDRequest}},
gets the user's approval and team membership, creates a C{L{TeamsResponse}}
object and adds it to the C{id_res} response::
teams_req = TeamsRequest.fromOpenIDRequest(checkid_request)
# [ get the user's approval and team membership, informing the user that
# the groups in teams_response were requested and accepted ]
teams_resp = TeamsResponse.extractResponse(teams_req, group_memberships)
teams_resp.toMessage(openid_response.fields)
3. The relying party uses C{L{TeamsResponse.fromSuccessResponse}} to
exxtract the data from the OpenID response::
teams_resp = TeamsResponse.fromSuccessResponse(success_response)
@var teams_uri: The URI used for the teams extension namespace and XRD Type Value
"""
import logging
from openid.message import registerNamespaceAlias, \
NamespaceAliasRegistrationError
from openid.extension import Extension
__all__ = [
'TeamsRequest',
'TeamsResponse',
'teams_uri',
'supportsTeams',
]
# The namespace for this extension
teams_uri = 'http://ns.launchpad.net/2007/openid-teams'
try:
registerNamespaceAlias(teams_uri, 'lp')
except NamespaceAliasRegistrationError as e:
logging.exception('registerNamespaceAlias(%r, %r) failed: %s' % (teams_uri,
'teams', str(e),))
def supportsTeams(endpoint):
"""Does the given endpoint advertise support for team extension?
@param endpoint: The endpoint object as returned by OpenID discovery
@type endpoint: openid.consumer.discover.OpenIDEndpoint
@returns: Whether an teams extension type was advertised by the endpoint
@rtype: bool
"""
return endpoint.usesExtension(teams_uri)
class TeamsRequest(Extension):
"""An object to hold the state of a teams extension request.
@ivar requested: A list of team names in this teams extension request
@type required: [str]
@group Consumer: requestField, requestFields, getExtensionArgs, addToOpenIDRequest
@group Server: fromOpenIDRequest, parseExtensionArgs
"""
ns_uri = 'http://ns.launchpad.net/2007/openid-teams'
ns_alias = 'lp'
def __init__(self, requested=None):
"""Initialize an empty teams extension request"""
Extension.__init__(self)
self.requested = []
if requested:
self.requestTeams(requested)
def requestedTeams(self):
return self.requested
def fromOpenIDRequest(cls, request):
"""Create a simple teams extension request that contains the
team names that were requested in the OpenID request with the
given arguments
@param request: The OpenID request
@type request: openid.server.CheckIDRequest
@returns: The newly created teams extension request
@rtype: C{L{TeamsRequest}}
"""
self = cls()
# Since we're going to mess with namespace URI mapping, don't
# mutate the object that was passed in.
message = request.message.copy()
args = message.getArgs(self.ns_uri)
self.parseExtensionArgs(args)
return self
fromOpenIDRequest = classmethod(fromOpenIDRequest)
def parseExtensionArgs(self, args):
"""Parse the unqualified teams extension request
parameters and add them to this object.
This method is essentially the inverse of
C{L{getExtensionArgs}}. This method restores the serialized teams
extension team names.
If you are extracting arguments from a standard OpenID
checkid_* request, you probably want to use C{L{fromOpenIDRequest}},
which will extract the teams extension namespace and arguments from the
OpenID request. This method is intended for cases where the
OpenID server needs more control over how the arguments are
parsed than that method provides.
>>> args = message.getArgs(teams_uri)
>>> request.parseExtensionArgs(args)
@param args: The unqualified teams extension arguments
@type args: {str:str}
@returns: None; updates this object
"""
items = args.get('query_membership')
if items:
for team_name in items.split(','):
self.requestTeam(team_name)
def wereTeamsRequested(self):
"""Have any teams been requested?
@rtype: bool
"""
return bool(self.requested)
def __requests__(self, team_name):
"""Was this team in the request team names?"""
return team_name in self.requested
def requestTeam(self, team_name):
"""Request the specified team membership from the OpenID user
@param team_name: the unqualified team name
@type team_name: str
"""
if not team_name in self.requested:
self.requested.append(team_name)
def requestTeams(self, team_names):
"""Add the given list of team names to the request.
@param team_names: The team names to request
@type team_names: [str]
"""
if isinstance(team_names, str):
raise TypeError('Teams should be passed as a list of '
'strings (not %r)' % (type(field_names),))
for team_name in team_names:
self.requestTeam(team_name)
def getExtensionArgs(self):
"""Get a dictionary of unqualified team extension
arguments representing this request.
This method is essentially the inverse of
C{L{parseExtensionArgs}}. This method serializes the team
extension request fields.
@rtype: {str:str}
"""
args = {}
if self.requested:
args['query_membership'] = ','.join(self.requested)
return args
class TeamsResponse(Extension):
"""Represents the data returned in a simple registration response
inside of an OpenID C{id_res} response. This object will be
created by the OpenID server, added to the C{id_res} response
object, and then extracted from the C{id_res} message by the
Consumer.
@ivar data: The simple registration data, keyed by the unqualified
simple registration name of the field (i.e. nickname is keyed
by C{'nickname'})
@ivar ns_uri: The URI under which the simple registration data was
stored in the response message.
@group Server: extractResponse
@group Consumer: fromSuccessResponse
@group Read-only dictionary interface: keys, iterkeys, items, iteritems,
__iter__, get, __getitem__, keys, has_key
"""
ns_uri = 'http://ns.launchpad.net/2007/openid-teams'
ns_alias = 'lp'
def __init__(self, teams=None):
Extension.__init__(self)
if teams is None:
self.teams = []
else:
self.teams = teams
def extractResponse(cls, request, teams):
"""Take a C{L{TeamsRequest}} and a list of groups
the user is member of and create a C{L{TeamsResponse}}
object containing the list of team names that are both
requested and in the membership list of the user.
@param request: The teams extension request object
@type request: TeamsRequest
@param teams: The list of teams the user is a member of
@type teams: [str]
@returns: a teams extension response object
@rtype: TeamsResponse
"""
self = cls()
for team in request.requestedTeams():
if team in teams:
self.teams.append(team)
return self
extractResponse = classmethod(extractResponse)
def fromSuccessResponse(cls, success_response, signed_only=True):
"""Create a C{L{TeamsResponse}} object from a successful OpenID
library response
(C{L{openid.consumer.consumer.SuccessResponse}}) response
message
@param success_response: A SuccessResponse from consumer.complete()
@type success_response: C{L{openid.consumer.consumer.SuccessResponse}}
@param signed_only: Whether to process only data that was
signed in the id_res message from the server.
@type signed_only: bool
@rtype: TeamsResponse
@returns: A teams extension response with the teams the OpenID
provider provided.
"""
self = cls()
if signed_only:
args = success_response.getSignedNS(self.ns_uri)
else:
args = success_response.message.getArgs(self.ns_uri)
if not args:
return None
self.teams = []
items = args['is_member']
if items:
for team_name in items.split(','):
self.teams.append(team_name)
return self
fromSuccessResponse = classmethod(fromSuccessResponse)
def getExtensionArgs(self):
"""Get the fields to put in the teams extension namespace
when adding them to an id_res message.
@see: openid.extension
"""
return {'is_member': ','.join(self.teams)}
|