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