1 # -*- coding: utf-8 -*-
5 from django.utils.encoding import smart_unicode
6 from django.utils.html import escape
7 from django.http import get_host
9 from forum.authentication.base import AuthenticationConsumer, InvalidAuthentication
12 from openid.yadis import xri
13 from openid.consumer.consumer import Consumer, SUCCESS, CANCEL, FAILURE, SETUP_NEEDED
14 from openid.consumer.discover import DiscoveryFailure
15 from openid.extensions.sreg import SRegRequest, SRegResponse
16 from openid.extensions.ax import FetchRequest as AXFetchRequest, AttrInfo, FetchResponse as AXFetchResponse
17 from django.utils.translation import ugettext as _
19 from store import OsqaOpenIDStore
21 class OpenIdAbstractAuthConsumer(AuthenticationConsumer):
24 'username': 'http://axschema.org/namePerson/friendly',
25 'email': 'http://axschema.org/contact/email',
26 #'web': 'http://axschema.org/contact/web/default',
27 #'firstname': 'http://axschema.org/namePerson/first',
28 #'lastname': 'http://axschema.org/namePerson/last',
29 #'birthdate': 'http://axschema.org/birthDate',
35 "nickname": "username"
39 def get_user_url(self, request):
41 return request.POST['openid_identifier']
43 raise NotImplementedError()
45 def prepare_authentication_request(self, request, redirect_to):
46 if not redirect_to.startswith('http://') or redirect_to.startswith('https://'):
47 redirect_to = get_url_host(request) + redirect_to
49 user_url = self.get_user_url(request)
51 if xri.identifierScheme(user_url) == 'XRI' and getattr(
52 settings, 'OPENID_DISALLOW_INAMES', False
54 raise InvalidAuthentication('i-names are not supported')
56 consumer = Consumer(request.session, OsqaOpenIDStore())
59 auth_request = consumer.begin(user_url)
60 except DiscoveryFailure:
61 raise InvalidAuthentication(_('Sorry, but your input is not a valid OpenId'))
63 sreg = getattr(self, 'sreg_attributes', False)
68 for k, attr_dic in sreg.items():
70 s.policy_url = attr_dic
73 for attr_name in attr_dic.keys():
74 s.requestField(field_name=attr_name, required=(k == "required"))
76 auth_request.addExtension(s)
78 ax_schema = getattr(self, 'dataype2ax_schema', False)
80 if ax_schema and request.session.get('force_email_request', True):
81 axr = AXFetchRequest()
82 for data_type, schema in ax_schema.items():
83 if isinstance(schema, tuple):
84 axr.add(AttrInfo(schema[0], required=True, alias=schema[1]))
86 axr.add(AttrInfo(schema, required=True, alias=data_type))
88 auth_request.addExtension(axr)
91 settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
94 return auth_request.redirectURL(trust_root, redirect_to)
96 def process_authentication_request(self, request):
97 consumer = Consumer(request.session, OsqaOpenIDStore())
100 (smart_unicode(k), smart_unicode(v)) for k, v in request.GET.items()
103 #for i in query_dict.items():
106 url = get_url_host(request) + request.path
107 openid_response = consumer.complete(query_dict, url)
109 if openid_response.status == SUCCESS:
113 sreg_attrs = getattr(self, 'sreg_attributes', False)
116 sreg_response = SRegResponse.fromSuccessResponse(openid_response)
120 [all_attrs.update(d) for k,d in sreg_attrs.items() if k != "policy_url"]
122 for attr_name, local_name in all_attrs.items():
123 if attr_name in sreg_response:
124 consumer_data[local_name] = sreg_response[attr_name]
126 ax_schema = getattr(self, 'dataype2ax_schema', False)
129 ax = AXFetchResponse.fromSuccessResponse(openid_response, False)
132 axargs = ax.getExtensionArgs()
134 ax_schema2data_type = dict([(s, t) for t, s in ax_schema.items()])
136 available_types = dict([
137 (ax_schema2data_type[s], re.sub('^type\.', '', n))
138 for n, s in axargs.items() if s in ax_schema2data_type
141 for t, s in available_types.items():
142 if not t in consumer_data:
143 if axargs.get("value.%s.1" % s, None):
144 consumer_data[t] = axargs["value.%s.1" % s]
146 request.session['auth_consumer_data'] = consumer_data
149 return request.GET['openid.identity']
150 elif openid_response.status == CANCEL:
151 raise InvalidAuthentication(_('The OpenId authentication request was canceled'))
152 elif openid_response.status == FAILURE:
153 raise InvalidAuthentication(_('The OpenId authentication failed: ') + openid_response.message)
154 elif openid_response.status == SETUP_NEEDED:
155 raise InvalidAuthentication(_('Setup needed'))
157 raise InvalidAuthentication(_('The OpenId authentication failed with an unknown status: ') + openid_response.status)
159 def get_user_data(self, key):
162 def get_url_host(request):
163 if request.is_secure():
167 host = escape(get_host(request))
168 return '%s://%s' % (protocol, host)
170 def get_full_url(request):
171 return get_url_host(request) + request.get_full_path()