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
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, user_logged_in
22 from forum.models import AuthKeyUserAssociation, ValidationHash, Question, Answer
24 def signin_page(request, action=None):
26 request.session['on_signin_url'] = request.META.get('HTTP_REFERER', '/')
28 request.session['on_signin_action'] = action
29 request.session['on_signin_url'] = reverse('auth_action_signin', kwargs={'action': action})
31 all_providers = [provider.context for provider in AUTH_PROVIDERS.values()]
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
36 bigicon_providers = sorted([
37 context for context in all_providers if context.mode == 'BIGICON' and can_show(context)
40 smallicon_providers = sorted([
41 context for context in all_providers if context.mode == 'SMALLICON' and can_show(context)
44 top_stackitem_providers = sorted([
45 context for context in all_providers if context.mode == 'TOP_STACK_ITEM' and can_show(context)
48 stackitem_providers = sorted([
49 context for context in all_providers if context.mode == 'STACK_ITEM' and can_show(context)
53 msg = request.session['auth_error']
54 del request.session['auth_error']
58 return render_to_response(
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,
68 RequestContext(request))
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
74 if provider in AUTH_PROVIDERS:
75 provider_class = AUTH_PROVIDERS[provider].consumer
78 request_url = provider_class.prepare_authentication_request(request,
79 reverse('auth_provider_done', kwargs={'provider': provider}))
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
87 return HttpResponseRedirect(reverse('auth_signin'))
90 def process_provider_signin(request, provider):
91 if provider in AUTH_PROVIDERS:
92 provider_class = AUTH_PROVIDERS[provider].consumer
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'))
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.")
105 request.session['auth_error'] = _("You are already logged in with that user.")
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.")
112 request.session['auth_error'] = _("Sorry, these login credentials belong to anoother user. Plese terminate your current session and try again.")
114 uassoc = AuthKeyUserAssociation(user=request.user, key=assoc_key, provider=provider)
116 request.user.message_set.create(message=_('The new credentials are now associated with your account'))
117 return HttpResponseRedirect(reverse('user_authsettings'))
119 return HttpResponseRedirect(reverse('auth_signin'))
121 if isinstance(assoc_key, User):
122 return login_and_forward(request, assoc_key)
125 assoc = AuthKeyUserAssociation.objects.get(key=assoc_key)
127 return login_and_forward(request, user_)
129 request.session['assoc_key'] = assoc_key
130 request.session['auth_provider'] = provider
131 return HttpResponseRedirect(reverse('auth_external_register'))
133 return HttpResponseRedirect(reverse('auth_signin'))
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)
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()
145 if User.objects.all().count() == 0:
146 user_.is_superuser = True
150 if not user_.email_isvalid:
151 send_validation_email(user_)
154 assoc_key = request.session['assoc_key']
155 auth_provider = request.session['auth_provider']
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')))
160 uassoc = AuthKeyUserAssociation(user=user_, key=request.session['assoc_key'], provider=request.session['auth_provider'])
163 if email_feeds_form.cleaned_data['subscribe'] == 'n':
164 user_.subscription_settings.enable_notifications = False
165 user_.subscription_settings.save()
167 del request.session['assoc_key']
168 del request.session['auth_provider']
170 if user_.email_isvalid:
171 return login_and_forward(request, user_)
173 return HttpResponseRedirect(reverse('index'))
175 provider_class = AUTH_PROVIDERS[request.session['auth_provider']].consumer
176 user_data = provider_class.get_user_data(request.session['assoc_key'])
178 username = user_data.get('username', '')
179 email = user_data.get('email', '')
182 email = request.session.get('auth_email_request', '')
185 request.session['auth_validated_email'] = email
187 form1 = SimpleRegistrationForm(initial={
189 'username': username,
192 email_feeds_form = SimpleEmailSubscribeForm()
194 provider_context = AUTH_PROVIDERS[request.session['auth_provider']].context
196 return render_to_response('auth/complete.html', {
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))
204 def request_temp_login(request):
205 if request.method == 'POST':
206 form = TemporaryLoginRequestForm(request.POST)
209 user = form.user_cache
212 hash = get_object_or_404(ValidationHash, user=user, type='templogin')
213 if hash.expiration < datetime.datetime.now():
215 return request_temp_login(request)
217 hash = ValidationHash.objects.create_new(user, 'templogin', [user.id])
219 send_email(_("Temporary login link"), [(user.username, user.email)], "auth/temp_login_email.html", {
220 'temp_login_code': hash,
224 request.user.message_set.create(message=_("An email has been sent with your temporary login key"))
226 return HttpResponseRedirect(reverse('index'))
228 form = TemporaryLoginRequestForm()
230 return render_to_response(
231 'auth/temp_login_request.html', {'form': form},
232 context_instance=RequestContext(request))
234 def temp_signin(request, user, code):
235 user = get_object_or_404(User, id=user)
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."))
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,
250 def validate_email(request, user, code):
251 user = get_object_or_404(User, id=user)
253 if (ValidationHash.objects.validate(code, user, 'email', [user.email])):
254 user.email_isvalid = True
256 return login_and_forward(request, user, None, _("Thank you, your email is now validated."))
261 def auth_settings(request):
263 change password view.
266 template: authopenid/changepw.html
269 auth_keys = user_.auth_keys.all()
271 if user_.has_usable_password():
272 FormClass = ChangePasswordForm
274 FormClass = SetPasswordForm
277 form = FormClass(request.POST, user=user_)
279 if user_.has_usable_password():
280 request.user.message_set.create(message=_("Your password was changed"))
282 request.user.message_set.create(message=_("New password set"))
283 FormClass = ChangePasswordForm
285 user_.set_password(form.cleaned_data['password1'])
287 return HttpResponseRedirect(reverse('user_authsettings'))
289 form = FormClass(user=user_)
294 provider = AUTH_PROVIDERS.get(k.provider, None)
296 if provider is not None:
297 name = "%s: %s" % (provider.context.human_name, provider.context.readable_key(k))
299 from forum.authentication.base import ConsumerTemplateContext
300 "unknown: %s" % ConsumerTemplateContext.readable_key(k)
302 auth_keys_list.append({
307 return render_to_response('auth/auth_settings.html', {
309 'has_password': user_.has_usable_password(),
310 'auth_keys': auth_keys_list,
311 }, context_instance=RequestContext(request))
313 def remove_external_provider(request, id):
314 association = get_object_or_404(AuthKeyUserAssociation, id=id)
315 if not association.user == request.user:
317 request.user.message_set.create(message=_("You removed the association with %s") % association.provider)
319 return HttpResponseRedirect(reverse('user_authsettings'))
321 def newquestion_signin_action(user):
322 question = Question.objects.filter(author=user).order_by('-added_at')[0]
323 return question.get_absolute_url()
325 def newanswer_signin_action(user):
326 answer = Answer.objects.filter(author=user).order_by('-added_at')[0]
327 return answer.get_absolute_url()
329 POST_SIGNIN_ACTIONS = {
330 'newquestion': newquestion_signin_action,
331 'newanswer': newanswer_signin_action,
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"
339 user_logged_in.send(user=user,old_session=old_session,sender=None)
342 signin_action = request.session.get('on_signin_action', None)
343 if not signin_action:
344 forward = request.session.get('on_signin_url', None)
347 forward = reverse('index')
350 forward = POST_SIGNIN_ACTIONS[signin_action](user)
352 forward = reverse('index')
355 message = _("Welcome back %s, you are now logged in") % user.username
357 request.user.message_set.create(message=message)
358 return HttpResponseRedirect(forward)
361 def signout(request):
363 signout from the website. Remove openid from session and kill it.
369 return HttpResponseRedirect(reverse('index'))