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