]> git.openstreetmap.org Git - osqa.git/blob - forum/views/auth.py
ad4785dcef53e6a273702ea9b7d8abe78ddaff86
[osqa.git] / forum / views / auth.py
1 from django.shortcuts import render_to_response, get_object_or_404
2 from django.template import RequestContext
3 from django.core.urlresolvers import reverse
4 from forum.models import User
5 from django.http import HttpResponseRedirect, Http404
6 from forum.http_responses import HttpResponseUnauthorized
7 from django.utils.safestring import mark_safe
8 from django.utils.translation import ugettext as _
9 from django.utils.http import urlquote_plus
10 from forum.views.decorators import login_required
11 from forum.modules import decorate
12 from django.contrib.auth import login, logout
13 from django.http import get_host
14 from forum.actions import SuspendAction
15 from forum.utils import html
16 from forum import settings
17 from writers import manage_pending_data
18 import types
19 import datetime
20 import logging
21
22 from forum.forms import SimpleRegistrationForm, SimpleEmailSubscribeForm, \
23         TemporaryLoginRequestForm, ChangePasswordForm, SetPasswordForm
24 from forum.utils.mail import send_template_email
25
26 from forum.authentication.base import InvalidAuthentication
27 from forum.authentication import AUTH_PROVIDERS
28
29 from forum.models import AuthKeyUserAssociation, ValidationHash, Question, Answer
30 from forum.actions import UserJoinsAction
31
32 def signin_page(request):
33     request.session['on_signin_url'] = request.META.get('HTTP_REFERER', '/')
34     
35     if reverse('auth_signin') == request.session['on_signin_url'].replace(settings.APP_URL, ''):
36         request.session['on_signin_url'] = reverse('index')
37
38     all_providers = [provider.context for provider in AUTH_PROVIDERS.values()]
39
40     sort = lambda c1, c2: c1.weight - c2.weight
41     can_show = lambda c: not request.user.is_authenticated() or c.show_to_logged_in_user
42
43     bigicon_providers = sorted([
44     context for context in all_providers if context.mode == 'BIGICON' and can_show(context)
45     ], sort)
46
47     smallicon_providers = sorted([
48     context for context in all_providers if context.mode == 'SMALLICON' and can_show(context)
49     ], sort)
50
51     top_stackitem_providers = sorted([
52     context for context in all_providers if context.mode == 'TOP_STACK_ITEM' and can_show(context)
53     ], sort)
54
55     stackitem_providers = sorted([
56     context for context in all_providers if context.mode == 'STACK_ITEM' and can_show(context)
57     ], sort)
58
59     try:
60         msg = request.session['auth_error']
61         del request.session['auth_error']
62     except:
63         msg = None
64
65     return render_to_response(
66             'auth/signin.html',
67             {
68             'msg': msg,
69             'all_providers': all_providers,
70             'bigicon_providers': bigicon_providers,
71             'top_stackitem_providers': top_stackitem_providers,
72             'stackitem_providers': stackitem_providers,
73             'smallicon_providers': smallicon_providers,
74             },
75             RequestContext(request))
76
77 def prepare_provider_signin(request, provider):
78     force_email_request = request.REQUEST.get('validate_email', 'yes') == 'yes'
79     request.session['force_email_request'] = force_email_request
80
81     if provider in AUTH_PROVIDERS:
82         provider_class = AUTH_PROVIDERS[provider].consumer
83
84         try:
85             request_url = provider_class.prepare_authentication_request(request,
86                                                                         reverse('auth_provider_done',
87                                                                                 kwargs={'provider': provider}))
88
89             return HttpResponseRedirect(request_url)
90         except NotImplementedError, e:
91             return process_provider_signin(request, provider)
92         except InvalidAuthentication, e:
93             request.session['auth_error'] = e.message
94
95         return HttpResponseRedirect(reverse('auth_signin'))
96     else:
97         raise Http404()
98
99
100 def process_provider_signin(request, provider):
101     if provider in AUTH_PROVIDERS:
102         provider_class = AUTH_PROVIDERS[provider].consumer
103
104         try:
105             assoc_key = provider_class.process_authentication_request(request)
106         except InvalidAuthentication, e:
107             request.session['auth_error'] = e.message
108             return HttpResponseRedirect(reverse('auth_signin'))
109
110         if request.user.is_authenticated():
111             if isinstance(assoc_key, (type, User)):
112                 if request.user != assoc_key:
113                     request.session['auth_error'] = _(
114                             "Sorry, these login credentials belong to anoother user. Plese terminate your current session and try again."
115                             )
116                 else:
117                     request.session['auth_error'] = _("You are already logged in with that user.")
118             else:
119                 try:
120                     assoc = AuthKeyUserAssociation.objects.get(key=assoc_key)
121                     if assoc.user == request.user:
122                         request.session['auth_error'] = _(
123                                 "These login credentials are already associated with your account.")
124                     else:
125                         request.session['auth_error'] = _(
126                                 "Sorry, these login credentials belong to anoother user. Plese terminate your current session and try again."
127                                 )
128                 except:
129                     uassoc = AuthKeyUserAssociation(user=request.user, key=assoc_key, provider=provider)
130                     uassoc.save()
131                     request.user.message_set.create(
132                             message=_('The new credentials are now associated with your account'))
133                     return HttpResponseRedirect(reverse('user_authsettings', args=[request.user.id]))
134
135             return HttpResponseRedirect(reverse('auth_signin'))
136         else:
137             if isinstance(assoc_key, User):
138                 return login_and_forward(request, assoc_key)
139
140         try:
141             assoc = AuthKeyUserAssociation.objects.get(key=assoc_key)
142             user_ = assoc.user
143             return login_and_forward(request, user_)
144         except:
145             request.session['assoc_key'] = assoc_key
146             request.session['auth_provider'] = provider
147             return HttpResponseRedirect(reverse('auth_external_register'))
148
149     return HttpResponseRedirect(reverse('auth_signin'))
150
151 def external_register(request):
152     if request.method == 'POST' and 'bnewaccount' in request.POST:
153         form1 = SimpleRegistrationForm(request.POST)
154         email_feeds_form = SimpleEmailSubscribeForm(request.POST)
155
156         if (form1.is_valid() and email_feeds_form.is_valid()):
157             user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'])
158             user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email']
159             user_.set_unusable_password()
160
161             if User.objects.all().count() == 0:
162                 user_.is_superuser = True
163                 user_.is_staff = True
164
165             user_.save()
166             UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save()
167
168             try:
169                 assoc_key = request.session['assoc_key']
170                 auth_provider = request.session['auth_provider']
171             except:
172                 request.session['auth_error'] = _(
173                         "Oops, something went wrong in the middle of this process. Please try again. Note that you need to have cookies enabled for the authentication to work."
174                         )
175                 logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
176                         ["%s: %s" % (k, v) for k, v in request.META.items()]))
177                 return HttpResponseRedirect(reverse('auth_signin'))
178
179             uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider)
180             uassoc.save()
181
182             if email_feeds_form.cleaned_data['subscribe'] == 'n':
183                 user_.subscription_settings.enable_notifications = False
184                 user_.subscription_settings.save()
185
186             del request.session['assoc_key']
187             del request.session['auth_provider']
188
189             return login_and_forward(request, user_, message=_("A welcome email has been sent to your email address. "))
190     else:
191         auth_provider = request.session.get('auth_provider', None)
192         if not auth_provider:
193             request.session['auth_error'] = _(
194                     "Oops, something went wrong in the middle of this process. Please try again.")
195             logging.error("Missing session data when trying to complete user registration: %s" % ", ".join(
196                     ["%s: %s" % (k, v) for k, v in request.META.items()]))
197             return HttpResponseRedirect(reverse('auth_signin'))
198
199         provider_class = AUTH_PROVIDERS[auth_provider].consumer
200         user_data = provider_class.get_user_data(request.session['assoc_key'])
201
202         if not user_data:
203             user_data = request.session.get('auth_consumer_data', {})
204
205         username = user_data.get('username', '')
206         email = user_data.get('email', '')
207
208         if email:
209             request.session['auth_validated_email'] = email
210
211         form1 = SimpleRegistrationForm(initial={
212         'next': '/',
213         'username': username,
214         'email': email,
215         })
216         email_feeds_form = SimpleEmailSubscribeForm()
217
218     provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context
219
220     return render_to_response('auth/complete.html', {
221     'form1': form1,
222     'email_feeds_form': email_feeds_form,
223     'provider':mark_safe(provider_context.human_name),
224     'login_type':provider_context.id,
225     'gravatar_faq_url':reverse('faq') + '#gravatar',
226     }, context_instance=RequestContext(request))
227
228 def request_temp_login(request):
229     if request.method == 'POST':
230         form = TemporaryLoginRequestForm(request.POST)
231
232         if form.is_valid():
233             users = form.user_cache
234
235             for u in users:
236                 if u.is_suspended():
237                     return forward_suspended_user(request, u, False)
238
239             for u in users:
240                 try:
241                     hash = get_object_or_404(ValidationHash, user=u, type='templogin')
242                     if hash.expiration < datetime.datetime.now():
243                         hash.delete()
244                         return request_temp_login(request)
245                 except:
246                     hash = ValidationHash.objects.create_new(u, 'templogin', [u.id])
247
248                 send_template_email([u], "auth/temp_login_email.html", {'temp_login_code': hash})
249
250                 request.user.message_set.create(message=_("An email has been sent with your temporary login key"))
251
252             return HttpResponseRedirect(reverse('index'))
253     else:
254         form = TemporaryLoginRequestForm()
255
256     return render_to_response(
257             'auth/temp_login_request.html', {'form': form},
258             context_instance=RequestContext(request))
259
260 def temp_signin(request, user, code):
261     user = get_object_or_404(User, id=user)
262
263     if (ValidationHash.objects.validate(code, user, 'templogin', [user.id])):
264         
265         # If the user requests temp_signin he must have forgotten his password. So we mark it as unusable.
266         user.set_unusable_password()
267         user.save()
268         
269         return login_and_forward(request, user, reverse('user_authsettings', kwargs={'id': user.id}),
270                                  _(
271                                          "You are logged in with a temporary access key, please take the time to fix your issue with authentication."
272                                          ))
273     else:
274         raise Http404()
275
276 def send_validation_email(request):
277     if not request.user.is_authenticated():
278         return HttpResponseUnauthorized(request)
279     else:
280         try:
281             hash = ValidationHash.objects.get(user=request.user, type='email')
282             hash.delete()
283             
284             # If we were able to get a previous validation hash we should raise an
285             # Exception immediately. Otherwise new validation hash will not be created
286             # and users will not receive the desired e-mail vaidation link.
287             raise Exception("Validation has already been sent")
288         except:
289             hash = ValidationHash.objects.create_new(request.user, 'email', [request.user.email])
290
291         send_template_email([request.user], "auth/mail_validation.html", {'validation_code': hash})
292         request.user.message_set.create(message=_("A message with an email validation link was just sent to your address."))
293         return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
294
295         
296
297 def validate_email(request, user, code):
298     user = get_object_or_404(User, id=user)
299
300     if (ValidationHash.objects.validate(code, user, 'email', [user.email])):
301         user.email_isvalid = True
302         user.save()
303         return login_and_forward(request, user, reverse('index'), _("Thank you, your email is now validated."))
304     else:
305         return render_to_response('auth/mail_already_validated.html', { 'user' : user }, RequestContext(request))
306
307 def auth_settings(request, id):
308     user_ = get_object_or_404(User, id=id)
309
310     if not (request.user.is_superuser or request.user == user_):
311         return HttpResponseUnauthorized(request)
312
313     auth_keys = user_.auth_keys.all()
314
315     if request.user.is_superuser or (not user_.has_usable_password()):
316         FormClass = SetPasswordForm
317     else:
318         FormClass = ChangePasswordForm
319
320     if request.POST:
321         form = FormClass(request.POST, user=user_)
322         if form.is_valid():
323             is_new_pass = not user_.has_usable_password()
324             user_.set_password(form.cleaned_data['password1'])
325             user_.save()
326
327             if is_new_pass:
328                 request.user.message_set.create(message=_("New password set"))
329                 if not request.user.is_superuser:
330                     form = ChangePasswordForm(user=user_)
331             else:
332                 request.user.message_set.create(message=_("Your password was changed"))
333
334             return HttpResponseRedirect(reverse('user_authsettings', kwargs={'id': user_.id}))
335     else:
336         form = FormClass(user=user_)
337
338     auth_keys_list = []
339
340     for k in auth_keys:
341         provider = AUTH_PROVIDERS.get(k.provider, None)
342
343         if provider is not None:
344             name =  "%s: %s" % (provider.context.human_name, provider.context.readable_key(k))
345         else:
346             from forum.authentication.base import ConsumerTemplateContext
347             "unknown: %s" % ConsumerTemplateContext.readable_key(k)
348
349         auth_keys_list.append({
350         'name': name,
351         'id': k.id
352         })
353
354     return render_to_response('auth/auth_settings.html', {
355     'view_user': user_,
356     "can_view_private": (user_ == request.user) or request.user.is_superuser,
357     'form': form,
358     'has_password': user_.has_usable_password(),
359     'auth_keys': auth_keys_list,
360     'allow_local_auth': AUTH_PROVIDERS.get('local', None),
361     }, context_instance=RequestContext(request))
362
363 def remove_external_provider(request, id):
364     association = get_object_or_404(AuthKeyUserAssociation, id=id)
365     if not (request.user.is_superuser or request.user == association.user):
366         return HttpResponseUnauthorized(request)
367
368     request.user.message_set.create(message=_("You removed the association with %s") % association.provider)
369     association.delete()
370     return HttpResponseRedirect(reverse('user_authsettings', kwargs={'id': association.user.id}))
371
372 def login_and_forward(request, user, forward=None, message=None):
373     if user.is_suspended():
374         return forward_suspended_user(request, user)
375
376     user.backend = "django.contrib.auth.backends.ModelBackend"
377     login(request, user)
378
379     if message is None:
380         message = _("Welcome back %s, you are now logged in") % user.username
381
382     request.user.message_set.create(message=message)
383
384     if not forward:
385         forward = request.session.get('on_signin_url', reverse('index'))
386         
387     pending_data = request.session.get('pending_submission_data', None)
388
389     if pending_data and (user.email_isvalid or pending_data['type'] not in settings.REQUIRE_EMAIL_VALIDATION_TO):
390         submission_time = pending_data['time']
391         if submission_time < datetime.datetime.now() - datetime.timedelta(minutes=int(settings.HOLD_PENDING_POSTS_MINUTES)):
392             del request.session['pending_submission_data']
393         elif submission_time < datetime.datetime.now() - datetime.timedelta(minutes=int(settings.WARN_PENDING_POSTS_MINUTES)):
394             user.message_set.create(message=(_("You have a %s pending submission.") % pending_data['data_name']) + " %s, %s, %s" % (
395                 html.hyperlink(reverse('manage_pending_data', kwargs={'action': _('save')}), _("save it")),
396                 html.hyperlink(reverse('manage_pending_data', kwargs={'action': _('review')}), _("review")),
397                 html.hyperlink(reverse('manage_pending_data', kwargs={'action': _('cancel')}), _("cancel"))
398             ))
399         else:
400             return manage_pending_data(request, _('save'), forward)
401
402     return HttpResponseRedirect(forward)
403
404 def forward_suspended_user(request, user, show_private_msg=True):
405     message = _("Sorry, but this account is suspended")
406     if show_private_msg:
407         msg_type = 'privatemsg'
408     else:
409         msg_type = 'publicmsg'
410
411     suspension = user.suspension
412     if suspension:
413         message += (":<br />" + suspension.extra.get(msg_type, ''))
414
415     request.user.message_set.create(message)
416     return HttpResponseRedirect(reverse('index'))
417
418 @decorate.withfn(login_required)
419 def signout(request):
420     logout(request)
421     return HttpResponseRedirect(reverse('index'))