PageRenderTime 41ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/myewb/apps/account_extra/views.py

https://github.com/gorner/myewb2
Python | 207 lines | 175 code | 25 blank | 7 comment | 37 complexity | 45f4bf90fcb73f6e2d84c1df5617e6fb MD5 | raw file
Possible License(s): Apache-2.0
  1. import re
  2. from django import forms
  3. from django.conf import settings
  4. from django.shortcuts import render_to_response, get_object_or_404
  5. from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponseNotFound, HttpResponse
  6. from django.contrib.auth import authenticate
  7. from django.contrib.auth import login as auth_login
  8. from django.contrib.auth.views import logout as pinaxlogout
  9. from django.contrib.auth.decorators import login_required
  10. from django.contrib.auth.models import User
  11. from django.contrib.auth.forms import PasswordChangeForm
  12. from django.core.urlresolvers import reverse
  13. from django.forms import fields
  14. from django.template import RequestContext
  15. from django.utils.translation import ugettext, ugettext_lazy as _
  16. from account.utils import get_default_redirect
  17. from emailconfirmation.models import EmailAddress, EmailConfirmation
  18. from pinax.apps.account.forms import ResetPasswordKeyForm
  19. from account_extra.forms import EmailLoginForm, EmailSignupForm
  20. from account.models import PasswordReset
  21. from account.views import login as pinaxlogin
  22. from account.views import signup as pinaxsignup
  23. from account.forms import AddEmailForm
  24. from base_groups.models import LogisticalGroup
  25. from siteutils import online_middleware
  26. def login(request, form_class=EmailLoginForm,
  27. template_name="account/login.html", success_url=None,
  28. associate_openid=False, openid_success_url=None, url_required=False):
  29. if not success_url:
  30. success_url = request.GET.get("url", None)
  31. next = request.GET.get("next", None)
  32. return pinaxlogin(request, form_class, template_name, success_url,
  33. associate_openid, openid_success_url, url_required)
  34. def signup(request, form_class=EmailSignupForm,
  35. template_name="account/signup.html", success_url=None,
  36. chapter_slug=None):
  37. if success_url is None:
  38. success_url = get_default_redirect(request)
  39. if request.method == "POST":
  40. form = form_class(request.POST,
  41. chapter=chapter_slug)
  42. if form.is_valid():
  43. username, password = form.save()
  44. if settings.ACCOUNT_EMAIL_VERIFICATION:
  45. return render_to_response("account/verification_sent.html", {
  46. "email": form.cleaned_data["email"],
  47. }, context_instance=RequestContext(request))
  48. else:
  49. user = authenticate(username=username, password=password)
  50. auth_login(request, user)
  51. login_message=ugettext(u"Welcome back, %(name)s") % {
  52. 'name': user.visible_name
  53. }
  54. request.user.message_set.create(message=login_message)
  55. return HttpResponseRedirect(success_url)
  56. else:
  57. form = form_class(chapter=chapter_slug)
  58. return render_to_response(template_name, {
  59. "form": form,
  60. }, context_instance=RequestContext(request))
  61. def logout(request):
  62. online_middleware.remove_user(request)
  63. # TODO: leave a message saying "you've been logged out".
  64. # currently not possible (can't set messages for guest user) but will be
  65. # possible in django 1.2
  66. return pinaxlogout(request, next_page=reverse('home'))
  67. @login_required
  68. def email(request, form_class=AddEmailForm, template_name="account/email.html",
  69. username=None):
  70. if username:
  71. if not request.user.has_module_perms("profiles"):
  72. return HttpResponseForbidden()
  73. else:
  74. user = get_object_or_404(User, username=username)
  75. else:
  76. user = request.user
  77. if request.method == "POST" and request.user.is_authenticated():
  78. if request.POST["action"] == "add":
  79. add_email_form = form_class(user, request.POST)
  80. if add_email_form.is_valid():
  81. add_email_form.save()
  82. add_email_form = form_class() # @@@
  83. else:
  84. add_email_form = form_class(user)
  85. if request.POST["action"] == "send":
  86. email = request.POST["email"]
  87. try:
  88. email_address = EmailAddress.objects.get(
  89. user=user,
  90. email=email,
  91. )
  92. request.user.message_set.create(
  93. message=_("Confirmation email sent to %(email)s") % {
  94. 'email': email,
  95. })
  96. EmailConfirmation.objects.send_confirmation(email_address)
  97. except EmailAddress.DoesNotExist:
  98. pass
  99. elif request.POST["action"] == "remove":
  100. email = request.POST["email"]
  101. try:
  102. email_address = EmailAddress.objects.get(
  103. user=user,
  104. email=email
  105. )
  106. email_address.delete()
  107. request.user.message_set.create(
  108. message=_("Removed email address %(email)s") % {
  109. 'email': email,
  110. })
  111. except EmailAddress.DoesNotExist:
  112. pass
  113. elif request.POST["action"] == "primary":
  114. email = request.POST["email"]
  115. email_address = EmailAddress.objects.get(
  116. user=user,
  117. email=email,
  118. )
  119. email_address.set_as_primary()
  120. else:
  121. add_email_form = form_class()
  122. return render_to_response(template_name, {
  123. "add_email_form": add_email_form,
  124. "other_user": user,
  125. }, context_instance=RequestContext(request))
  126. def silent_signup(request, email):
  127. regex = re.compile(fields.email_re)
  128. if not regex.search(email):
  129. return HttpResponseNotFound() # invalid email
  130. group = get_object_or_404(LogisticalGroup, slug="silent_signup_api")
  131. group.add_email(email)
  132. return HttpResponse("success")
  133. @login_required
  134. def password_change(request, template_name='account/password_change.html',
  135. post_change_redirect=None):
  136. if post_change_redirect is None:
  137. post_change_redirect = reverse('profile_detail', kwargs={'username': request.user.username})
  138. if request.method == "POST":
  139. form = PasswordChangeForm(request.user, request.POST)
  140. if form.is_valid():
  141. result = request.user.set_password(form.cleaned_data['new_password1'])
  142. if not result:
  143. form._errors[forms.forms.NON_FIELD_ERRORS] = ["New password is too simple"]
  144. else:
  145. request.user.save()
  146. request.user.message_set.create(message="Password changed.")
  147. return HttpResponseRedirect(post_change_redirect)
  148. else:
  149. form = PasswordChangeForm(request.user)
  150. return render_to_response(template_name, {
  151. 'password_change_form': form,
  152. }, context_instance=RequestContext(request))
  153. def password_reset_from_key(request, key, form_class=ResetPasswordKeyForm,
  154. template_name="account/password_reset_from_key.html"):
  155. if request.method == "POST":
  156. password_reset_key_form = form_class(request.POST)
  157. if password_reset_key_form.is_valid():
  158. # get the password_reset object
  159. temp_key = password_reset_key_form.cleaned_data.get("temp_key")
  160. password_reset = PasswordReset.objects.filter(temp_key__exact=temp_key, reset=False)
  161. password_reset = password_reset[0] # should always be safe, as form_clean checks this
  162. # now set the new user password
  163. user = User.objects.get(passwordreset__exact=password_reset)
  164. result = user.set_password(password_reset_key_form.cleaned_data['password1'])
  165. if not result:
  166. # unsuccessful
  167. password_reset_key_form._errors[forms.forms.NON_FIELD_ERRORS] = ["Password is too simple"]
  168. else:
  169. user.save()
  170. user.message_set.create(message=ugettext(u"Password successfully changed."))
  171. # change all the password reset records to this person to be true.
  172. for password_reset in PasswordReset.objects.filter(user=user):
  173. password_reset.reset = True
  174. password_reset.save()
  175. user = authenticate(username=user.username, password=password_reset_key_form.cleaned_data['password1'])
  176. auth_login(request, user)
  177. return HttpResponseRedirect(reverse('home'))
  178. else:
  179. password_reset_key_form = form_class(initial={"temp_key": key})
  180. return render_to_response(template_name, {
  181. "form": password_reset_key_form,
  182. }, context_instance=RequestContext(request))