comparison MoinMoin/userprefs/oid.py @ 2301:35617ed953c4

OpenID preferences (allows adding/removing OpenIDs)
author Johannes Berg <johannes AT sipsolutions DOT net>
date Tue, 10 Jul 2007 19:13:03 +0200
parents
children 4f73af30fd75
comparison
equal deleted inserted replaced
2300:95e57cb59bb0 2301:35617ed953c4
1 # -*- coding: iso-8859-1 -*-
2 """
3 MoinMoin - OpenID preferences
4
5 @copyright: 2007 MoinMoin:JohannesBerg
6 @license: GNU GPL, see COPYING for details.
7 """
8
9 from MoinMoin import wikiutil
10 from MoinMoin.widget import html
11 from MoinMoin.userprefs import UserPrefBase
12 from MoinMoin.auth.openidrp import OpenIDAuth
13 import sha
14 from MoinMoin.util.moinoid import MoinOpenIDStore
15 from openid.consumer import consumer
16 from openid.yadis.discover import DiscoveryFailure
17 from openid.fetchers import HTTPFetchingError
18
19
20 class Settings(UserPrefBase):
21 def __init__(self, request):
22 """ Initialize OpenID settings form. """
23 UserPrefBase.__init__(self, request)
24 self.request = request
25 self._ = request.getText
26 self.cfg = request.cfg
27 self.title = self._("OpenID settings")
28
29 def allowed(self):
30 for authm in self.request.cfg.auth:
31 if isinstance(authm, OpenIDAuth):
32 return True
33 return False
34
35 def _handle_remove(self):
36 _ = self.request.getText
37 openids = self.request.user.openids[:]
38 for oid in self.request.user.openids:
39 name = "rm-%s" % sha.new(oid).hexdigest()
40 if name in self.request.form:
41 openids.remove(oid)
42 if not openids and len(self.request.cfg.auth) == 1:
43 return _("Cannot remove all OpenIDs.")
44 self.request.user.openids = openids
45 self.request.user.save()
46 return _("The selected OpenIDs have been removed.")
47
48 def _handle_add(self):
49 _ = self.request.getText
50 request = self.request
51
52 openid_id = request.form.get('openid_identifier', [''])[0]
53
54 if openid_id in request.user.openids:
55 return _("OpenID is already present.")
56
57 oidconsumer = consumer.Consumer(request.session,
58 MoinOpenIDStore(self.request))
59 try:
60 oidreq = oidconsumer.begin(openid_id)
61 except HTTPFetchingError:
62 return _('Failed to resolve OpenID.')
63 except DiscoveryFailure:
64 return _('OpenID discovery failure, not a valid OpenID.')
65 else:
66 if oidreq is None:
67 return _("No OpenID.")
68
69 qstr = wikiutil.makeQueryString({'action': 'userprefs',
70 'handler': 'oid',
71 'oid.return': '1'})
72 return_to = ''.join([request.getBaseURL(), '?', qstr])
73 trust_root = request.getBaseURL()
74 if oidreq.shouldSendRedirect():
75 redirect_url = oidreq.redirectURL(trust_root, return_to)
76 request.http_redirect(redirect_url)
77 else:
78 form_html = oidreq.formMarkup(trust_root, return_to,
79 form_tag_attrs={'id': 'openid_message'})
80 request.session['openid.prefs.form_html'] = form_html
81
82
83 def _handle_oidreturn(self):
84 request = self.request
85 _ = request.getText
86
87 oidconsumer = consumer.Consumer(request.session,
88 MoinOpenIDStore(request))
89 query = {}
90 for key in request.form:
91 query[key] = request.form[key][0]
92 qstr = wikiutil.makeQueryString({'action': 'userprefs',
93 'handler': 'oid',
94 'oid.return': '1'})
95 return_to = ''.join([request.getBaseURL(), '?', qstr])
96 info = oidconsumer.complete(query, return_to=return_to)
97 if info.status == consumer.FAILURE:
98 return _('OpenID error: %s.') % info.message
99 elif info.status == consumer.CANCEL:
100 return _('Verification canceled.')
101 elif info.status == consumer.SUCCESS:
102 if not info.identity_url in request.user.openids:
103 request.user.openids.append(info.identity_url)
104 request.user.save()
105 return _("OpenID added successfully.")
106 else:
107 return _("OpenID is already present.")
108 else:
109 return _('OpenID failure.')
110
111
112 def handle_form(self):
113 _ = self._
114 form = self.request.form
115
116 if form.has_key('oid.return'):
117 return self._handle_oidreturn()
118
119 if form.has_key('cancel'):
120 return
121
122 if form.has_key('remove'):
123 return self._handle_remove()
124
125 if form.has_key('add'):
126 return self._handle_add()
127
128 return
129
130 def _make_form(self):
131 sn = self.request.getScriptname()
132 pi = self.request.getPathinfo()
133 action = u"%s%s" % (sn, pi)
134 _form = html.FORM(action=action)
135 _form.append(html.INPUT(type="hidden", name="action", value="userprefs"))
136 _form.append(html.INPUT(type="hidden", name="handler", value="oid"))
137 return _form
138
139 def _make_row(self, label, cell, **kw):
140 """ Create a row in the form table.
141 """
142 self._table.append(html.TR().extend([
143 html.TD(**kw).extend([html.B().append(label), ' ']),
144 html.TD().extend(cell),
145 ]))
146
147 def _oidlist(self):
148 _ = self.request.getText
149 form = self._make_form()
150 for oid in self.request.user.openids:
151 name = "rm-%s" % sha.new(oid).hexdigest()
152 form.append(html.INPUT(type="checkbox", name=name, id=name))
153 form.append(html.LABEL(for_=name).append(html.Text(oid)))
154 form.append(html.BR())
155 self._make_row(_("Current OpenIDs"), [form], valign='top')
156 label = _("Remove selected")
157 form.append(html.BR())
158 form.append(html.INPUT(type="submit", name="remove", value=label))
159
160 def _addoidform(self):
161 _ = self.request.getText
162 form = self._make_form()
163 # go back to this page
164 form.append(html.INPUT(type="hidden", name="sub", value="oid"))
165 label = _("Add OpenID")
166 form.append(html.INPUT(type="text", size="32",
167 name="openid_identifier",
168 id="openididentifier"))
169 form.append(html.BR())
170 form.append(html.INPUT(type="submit", name="add", value=label))
171 self._make_row(_('Add OpenID'), [form])
172
173 def create_form(self):
174 """ Create the complete HTML form code. """
175 _ = self._
176
177 ret = html.P()
178 # Use the user interface language and direction
179 lang_attr = self.request.theme.ui_lang_attr()
180 ret.append(html.Raw('<div %s>' % lang_attr))
181 self._table = html.TABLE(border="0")
182 ret.append(self._table)
183 ret.append(html.Raw("</div>"))
184
185 request = self.request
186
187 if 'openid.prefs.form_html' in request.session:
188 txt = _('OpenID verification requires that you click this button:')
189 # create JS to automatically submit the form if possible
190 submitjs = """<script type="text/javascript">
191 <!--//
192 document.getElementById("openid_message").submit();
193 //-->
194 </script>
195 """
196 oidhtml = request.session['openid.prefs.form_html']
197 del request.session['openid.prefs.form_html']
198 return ''.join([txt, oidhtml, submitjs])
199
200 if request.user.openids:
201 self._oidlist()
202 self._addoidform()
203
204 form = self._make_form()
205 label = _("Cancel")
206 form.append(html.INPUT(type="submit", name='cancel', value=label))
207 self._make_row('', [form])
208 return unicode(ret)