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",
36 "fullname": "real_name"
40 def get_user_url(self, request):
42 return request.POST['openid_identifier']
44 raise NotImplementedError()
46 def prepare_authentication_request(self, request, redirect_to):
47 if not redirect_to.startswith('http://') or redirect_to.startswith('https://'):
48 redirect_to = get_url_host(request) + redirect_to
50 user_url = self.get_user_url(request)
52 if xri.identifierScheme(user_url) == 'XRI' and getattr(
53 settings, 'OPENID_DISALLOW_INAMES', False
55 raise InvalidAuthentication('i-names are not supported')
57 consumer = Consumer(request.session, OsqaOpenIDStore())
60 auth_request = consumer.begin(user_url)
61 except DiscoveryFailure:
62 raise InvalidAuthentication(_('Sorry, but your input is not a valid OpenId'))
64 sreg = getattr(self, 'sreg_attributes', False)
69 for k, attr_dic in sreg.items():
71 s.policy_url = attr_dic
74 for attr_name in attr_dic.keys():
75 s.requestField(field_name=attr_name, required=(k == "required"))
77 auth_request.addExtension(s)
79 ax_schema = getattr(self, 'dataype2ax_schema', False)
81 if ax_schema and request.session.get('force_email_request', True):
82 axr = AXFetchRequest()
83 for data_type, schema in ax_schema.items():
84 if isinstance(schema, tuple):
85 axr.add(AttrInfo(schema[0], required=True, alias=schema[1]))
87 axr.add(AttrInfo(schema, required=True, alias=data_type))
89 auth_request.addExtension(axr)
92 settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
95 return auth_request.redirectURL(trust_root, redirect_to)
97 def process_authentication_request(self, request):
98 consumer = Consumer(request.session, OsqaOpenIDStore())
101 (smart_unicode(k), smart_unicode(v)) for k, v in request.GET.items()
104 #for i in query_dict.items():
107 url = get_url_host(request) + request.path
108 openid_response = consumer.complete(query_dict, url)
110 if openid_response.status == SUCCESS:
114 sreg_attrs = getattr(self, 'sreg_attributes', False)
117 sreg_response = SRegResponse.fromSuccessResponse(openid_response)
121 [all_attrs.update(d) for k,d in sreg_attrs.items() if k != "policy_url"]
123 for attr_name, local_name in all_attrs.items():
124 if attr_name in sreg_response:
125 consumer_data[local_name] = sreg_response[attr_name]
127 ax_schema = getattr(self, 'dataype2ax_schema', False)
130 ax = AXFetchResponse.fromSuccessResponse(openid_response, False)
133 axargs = ax.getExtensionArgs()
135 ax_schema2data_type = dict([(s, t) for t, s in ax_schema.items()])
137 available_types = dict([
138 (ax_schema2data_type[s], re.sub('^type\.', '', n))
139 for n, s in axargs.items() if s in ax_schema2data_type
142 for t, s in available_types.items():
143 if not t in consumer_data:
144 if axargs.get("value.%s.1" % s, None):
145 consumer_data[t] = axargs["value.%s.1" % s]
147 request.session['auth_consumer_data'] = consumer_data
150 return request.GET['openid.identity']
151 elif openid_response.status == CANCEL:
152 raise InvalidAuthentication(_('The OpenId authentication request was canceled'))
153 elif openid_response.status == FAILURE:
154 raise InvalidAuthentication(_('The OpenId authentication failed: ') + openid_response.message)
155 elif openid_response.status == SETUP_NEEDED:
156 raise InvalidAuthentication(_('Setup needed'))
158 raise InvalidAuthentication(_('The OpenId authentication failed with an unknown status: ') + openid_response.status)
160 def get_user_data(self, key):
163 def get_url_host(request):
164 if request.is_secure():
168 host = escape(get_host(request))
169 return '%s://%s' % (protocol, host)
171 def get_full_url(request):
172 return get_url_host(request) + request.get_full_path()