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