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
15 from forum.authentication.forms import SimpleRegistrationForm, SimpleEmailSubscribeForm, \
16 TemporaryLoginRequestForm, ChangePasswordForm, SetPasswordForm
17 from forum.utils.mail import send_email
19 from forum.authentication.base import InvalidAuthentication
20 from forum.authentication import AUTH_PROVIDERS
22 from forum.models import AuthKeyUserAssociation, ValidationHash, Question, Answer
23 from forum.actions import UserJoinsAction
25 def signin_page(request, action=None):
27 request.session['on_signin_url'] = request.META.get('HTTP_REFERER', '/')
29 request.session['on_signin_action'] = action
30 request.session['on_signin_url'] = reverse('auth_action_signin', kwargs={'action': action})
32 all_providers = [provider.context for provider in AUTH_PROVIDERS.values()]
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
37 bigicon_providers = sorted([
38 context for context in all_providers if context.mode == 'BIGICON' and can_show(context)
41 smallicon_providers = sorted([
42 context for context in all_providers if context.mode == 'SMALLICON' and can_show(context)
45 top_stackitem_providers = sorted([
46 context for context in all_providers if context.mode == 'TOP_STACK_ITEM' and can_show(context)
49 stackitem_providers = sorted([
50 context for context in all_providers if context.mode == 'STACK_ITEM' and can_show(context)
54 msg = request.session['auth_error']
55 del request.session['auth_error']
59 return render_to_response(
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,
69 RequestContext(request))
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
75 if provider in AUTH_PROVIDERS:
76 provider_class = AUTH_PROVIDERS[provider].consumer
79 request_url = provider_class.prepare_authentication_request(request,
80 reverse('auth_provider_done', kwargs={'provider': provider}))
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
88 return HttpResponseRedirect(reverse('auth_signin'))
91 def process_provider_signin(request, provider):
92 if provider in AUTH_PROVIDERS:
93 provider_class = AUTH_PROVIDERS[provider].consumer
96 assoc_key = provider_class.process_authentication_request(request)
97 except InvalidAuthentication, e:
98 request.session['auth_error'] = e.message
99 return HttpResponseRedirect(reverse('auth_signin'))
101 if request.user.is_authenticated():
102 if isinstance(assoc_key, (type, User)):
103 if request.user != assoc_key:
104 request.session['auth_error'] = _("Sorry, these login credentials belong to anoother user. Plese terminate your current session and try again.")
106 request.session['auth_error'] = _("You are already logged in with that user.")
109 assoc = AuthKeyUserAssociation.objects.get(key=assoc_key)
110 if assoc.user == request.user:
111 request.session['auth_error'] = _("These login credentials are already associated with your account.")
113 request.session['auth_error'] = _("Sorry, these login credentials belong to anoother user. Plese terminate your current session and try again.")
115 uassoc = AuthKeyUserAssociation(user=request.user, key=assoc_key, provider=provider)
117 request.user.message_set.create(message=_('The new credentials are now associated with your account'))
118 return HttpResponseRedirect(reverse('user_authsettings'))
120 return HttpResponseRedirect(reverse('auth_signin'))
122 if isinstance(assoc_key, User):
123 return login_and_forward(request, assoc_key)
126 assoc = AuthKeyUserAssociation.objects.get(key=assoc_key)
128 return login_and_forward(request, user_)
130 request.session['assoc_key'] = assoc_key
131 request.session['auth_provider'] = provider
132 return HttpResponseRedirect(reverse('auth_external_register'))
134 return HttpResponseRedirect(reverse('auth_signin'))
136 def external_register(request):
137 if request.method == 'POST' and 'bnewaccount' in request.POST:
138 form1 = SimpleRegistrationForm(request.POST)
139 email_feeds_form = SimpleEmailSubscribeForm(request.POST)
141 if (form1.is_valid() and email_feeds_form.is_valid()):
142 user_ = User(username=form1.cleaned_data['username'], email=form1.cleaned_data['email'])
143 user_.email_isvalid = request.session.get('auth_validated_email', '') == form1.cleaned_data['email']
144 user_.set_unusable_password()
146 if User.objects.all().count() == 0:
147 user_.is_superuser = True
150 UserJoinsAction(user=user_, ip=request.META['REMOTE_ADDR']).save()
152 if not user_.email_isvalid:
153 send_validation_email(user_)
156 assoc_key = request.session['assoc_key']
157 auth_provider = request.session['auth_provider']
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')))
162 uassoc = AuthKeyUserAssociation(user=user_, key=assoc_key, provider=auth_provider)
165 if email_feeds_form.cleaned_data['subscribe'] == 'n':
166 user_.subscription_settings.enable_notifications = False
167 user_.subscription_settings.save()
169 del request.session['assoc_key']
170 del request.session['auth_provider']
172 return login_and_forward(request, user_)
174 provider_class = AUTH_PROVIDERS[request.session['auth_provider']].consumer
175 user_data = provider_class.get_user_data(request.session['assoc_key'])
178 user_data = request.session.get('auth_consumer_data', {})
180 username = user_data.get('username', '')
181 email = user_data.get('email', '')
184 request.session['auth_validated_email'] = email
186 form1 = SimpleRegistrationForm(initial={
188 'username': username,
191 email_feeds_form = SimpleEmailSubscribeForm()
193 provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context
195 return render_to_response('auth/complete.html', {
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))
203 def request_temp_login(request):
204 if request.method == 'POST':
205 form = TemporaryLoginRequestForm(request.POST)
208 user = form.user_cache
211 hash = get_object_or_404(ValidationHash, user=user, type='templogin')
212 if hash.expiration < datetime.datetime.now():
214 return request_temp_login(request)
216 hash = ValidationHash.objects.create_new(user, 'templogin', [user.id])
218 send_email(_("Temporary login link"), [(user.username, user.email)], "auth/temp_login_email.html", {
219 'temp_login_code': hash,
223 request.user.message_set.create(message=_("An email has been sent with your temporary login key"))
225 return HttpResponseRedirect(reverse('index'))
227 form = TemporaryLoginRequestForm()
229 return render_to_response(
230 'auth/temp_login_request.html', {'form': form},
231 context_instance=RequestContext(request))
233 def temp_signin(request, user, code):
234 user = get_object_or_404(User, id=user)
236 if (ValidationHash.objects.validate(code, user, 'templogin', [user.id])):
237 return login_and_forward(request, user, reverse('user_authsettings'),
238 _("You are logged in with a temporary access key, please take the time to fix your issue with authentication."))
242 def send_validation_email(user):
243 hash = ValidationHash.objects.create_new(user, 'email', [user.email])
244 send_email(_("Email Validation"), [(user.username, user.email)], "auth/email_validation.html", {
245 'validation_code': hash,
249 def validate_email(request, user, code):
250 user = get_object_or_404(User, id=user)
252 if (ValidationHash.objects.validate(code, user, 'email', [user.email])):
253 user.email_isvalid = True
255 return login_and_forward(request, user, None, _("Thank you, your email is now validated."))
260 def auth_settings(request):
262 change password view.
265 template: authopenid/changepw.html
268 auth_keys = user_.auth_keys.all()
270 if user_.has_usable_password():
271 FormClass = ChangePasswordForm
273 FormClass = SetPasswordForm
276 form = FormClass(request.POST, user=user_)
278 if user_.has_usable_password():
279 request.user.message_set.create(message=_("Your password was changed"))
281 request.user.message_set.create(message=_("New password set"))
282 FormClass = ChangePasswordForm
284 user_.set_password(form.cleaned_data['password1'])
286 return HttpResponseRedirect(reverse('user_authsettings'))
288 form = FormClass(user=user_)
293 provider = AUTH_PROVIDERS.get(k.provider, None)
295 if provider is not None:
296 name = "%s: %s" % (provider.context.human_name, provider.context.readable_key(k))
298 from forum.authentication.base import ConsumerTemplateContext
299 "unknown: %s" % ConsumerTemplateContext.readable_key(k)
301 auth_keys_list.append({
306 return render_to_response('auth/auth_settings.html', {
308 'has_password': user_.has_usable_password(),
309 'auth_keys': auth_keys_list,
310 }, context_instance=RequestContext(request))
312 def remove_external_provider(request, id):
313 association = get_object_or_404(AuthKeyUserAssociation, id=id)
314 if not association.user == request.user:
315 return HttpResponseForbidden()
316 request.user.message_set.create(message=_("You removed the association with %s") % association.provider)
318 return HttpResponseRedirect(reverse('user_authsettings'))
320 def newquestion_signin_action(user):
321 question = Question.objects.filter(author=user).order_by('-added_at')[0]
322 return question.get_absolute_url()
324 def newanswer_signin_action(user):
325 answer = Answer.objects.filter(author=user).order_by('-added_at')[0]
326 return answer.get_absolute_url()
328 POST_SIGNIN_ACTIONS = {
329 'newquestion': newquestion_signin_action,
330 'newanswer': newanswer_signin_action,
333 def login_and_forward(request, user, forward=None, message=None):
334 old_session = request.session.session_key
335 user.backend = "django.contrib.auth.backends.ModelBackend"
338 temp_data = request.session.pop('temp_node_data', None)
340 request.POST = temp_data
341 node_type = request.session.pop('temp_node_type')
343 if node_type == "question":
344 from forum.views.writers import ask
346 elif node_type == "answer":
347 from forum.views.writers import answer
348 return answer(request, request.session.pop('temp_question_id'))
351 signin_action = request.session.get('on_signin_action', None)
352 if not signin_action:
353 forward = request.session.get('on_signin_url', None)
356 forward = reverse('index')
359 forward = POST_SIGNIN_ACTIONS[signin_action](user)
361 forward = reverse('index')
364 message = _("Welcome back %s, you are now logged in") % user.username
366 request.user.message_set.create(message=message)
367 return HttpResponseRedirect(forward)
370 def signout(request):
372 signout from the website. Remove openid from session and kill it.
378 return HttpResponseRedirect(reverse('index'))