]> git.openstreetmap.org Git - osqa.git/blob - forum_modules/openidauth/consumer.py
initial import
[osqa.git] / forum_modules / openidauth / consumer.py
1 from django.utils.html import escape
2 from django.http import get_host
3
4 from forum.authentication.base import AuthenticationConsumer, InvalidAuthentication
5 import settings
6
7 from openid.yadis import xri
8 from openid.consumer.consumer import Consumer, SUCCESS, CANCEL, FAILURE, SETUP_NEEDED
9 from openid.consumer.discover import DiscoveryFailure
10 from openid.extensions.sreg import SRegRequest, SRegResponse
11 from openid.extensions.ax import FetchRequest as AXFetchRequest, AttrInfo, FetchResponse as AXFetchResponse
12 from django.utils.translation import ugettext as _
13
14 from store import OsqaOpenIDStore
15
16 class OpenIdAbstractAuthConsumer(AuthenticationConsumer):
17
18     def get_user_url(self, request):
19         try:
20             return request.POST['openid_identifier']
21         except:
22             raise NotImplementedError()
23
24     def prepare_authentication_request(self, request, redirect_to):
25         if not redirect_to.startswith('http://') or redirect_to.startswith('https://'):
26                     redirect_to =  get_url_host(request) + redirect_to
27
28         user_url = self.get_user_url(request)
29
30         if xri.identifierScheme(user_url) == 'XRI' and getattr(
31             settings, 'OPENID_DISALLOW_INAMES', False
32         ):
33             raise InvalidAuthentication('i-names are not supported')
34
35         consumer = Consumer(request.session, OsqaOpenIDStore())
36
37         try:
38             auth_request = consumer.begin(user_url)
39         except DiscoveryFailure:
40             raise InvalidAuthentication(_('Sorry, but your input is not a valid OpenId'))
41
42         #sreg = getattr(settings, 'OPENID_SREG', False)
43
44         #if sreg:
45         #    s = SRegRequest()
46         #    for sarg in sreg:
47         #        if sarg.lower().lstrip() == "policy_url":
48         #            s.policy_url = sreg[sarg]
49         #        else:
50         #            for v in sreg[sarg].split(','):
51         #                s.requestField(field_name=v.lower().lstrip(), required=(sarg.lower().lstrip() == "required"))
52         #    auth_request.addExtension(s)
53
54         #auth_request.addExtension(SRegRequest(required=['email']))
55
56         if request.session.get('force_email_request', True):
57             axr = AXFetchRequest()
58             axr.add(AttrInfo("http://axschema.org/contact/email", 1, True, "email"))
59             auth_request.addExtension(axr)
60
61         trust_root = getattr(
62             settings, 'OPENID_TRUST_ROOT', get_url_host(request) + '/'
63         )
64
65
66         return auth_request.redirectURL(trust_root, redirect_to)
67
68     def process_authentication_request(self, request):
69         consumer = Consumer(request.session, OsqaOpenIDStore())
70
71         query_dict = dict([
72             (k.encode('utf8'), v.encode('utf8')) for k, v in request.GET.items()
73         ])
74
75         #for i in query_dict.items():
76         #    print "%s : %s" % i
77
78         url = get_url_host(request) + request.path
79         openid_response = consumer.complete(query_dict, url)
80
81         if openid_response.status == SUCCESS:
82             if request.session.get('force_email_request', True):
83                 try:
84                     ax = AXFetchResponse.fromSuccessResponse(openid_response)
85                     email = ax.getExtensionArgs()['value.ext0.1']
86                     request.session['auth_email_request'] = email
87                 except Exception, e:
88                     pass
89
90             return request.GET['openid.identity']
91         elif openid_response.status == CANCEL:
92             raise InvalidAuthentication(_('The OpenId authentication request was canceled'))
93         elif openid_response.status == FAILURE:
94             raise InvalidAuthentication(_('The OpenId authentication failed: ') + openid_response.message)
95         elif openid_response.status == SETUP_NEEDED:
96             raise InvalidAuthentication(_('Setup needed'))
97         else:
98             raise InvalidAuthentication(_('The OpenId authentication failed with an unknown status: ') + openid_response.status)
99
100     def get_user_data(self, key):
101         return {}
102
103 def get_url_host(request):
104     if request.is_secure():
105         protocol = 'https'
106     else:
107         protocol = 'http'
108     host = escape(get_host(request))
109     return '%s://%s' % (protocol, host)
110
111 def get_full_url(request):
112     return get_url_host(request) + request.get_full_path()