PageRenderTime 385ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/django/contrib/auth/views.py

https://github.com/eric-brechemier/django
Python | 191 lines | 164 code | 16 blank | 11 comment | 22 complexity | 46a197bf77221591888b7969f7cf3cd5 MD5 | raw file
  1. import re
  2. from django.conf import settings
  3. from django.contrib.auth import REDIRECT_FIELD_NAME
  4. # Avoid shadowing the login() view below.
  5. from django.contrib.auth import login as auth_login
  6. from django.contrib.auth.decorators import login_required
  7. from django.contrib.auth.forms import AuthenticationForm
  8. from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm, PasswordChangeForm
  9. from django.contrib.auth.tokens import default_token_generator
  10. from django.views.decorators.csrf import csrf_protect
  11. from django.core.urlresolvers import reverse
  12. from django.shortcuts import render_to_response, get_object_or_404
  13. from django.contrib.sites.models import Site, RequestSite
  14. from django.http import HttpResponseRedirect, Http404
  15. from django.template import RequestContext
  16. from django.utils.http import urlquote, base36_to_int
  17. from django.utils.translation import ugettext as _
  18. from django.contrib.auth.models import User
  19. from django.views.decorators.cache import never_cache
  20. @csrf_protect
  21. @never_cache
  22. def login(request, template_name='registration/login.html',
  23. redirect_field_name=REDIRECT_FIELD_NAME,
  24. authentication_form=AuthenticationForm):
  25. """Displays the login form and handles the login action."""
  26. redirect_to = request.REQUEST.get(redirect_field_name, '')
  27. if request.method == "POST":
  28. form = authentication_form(data=request.POST)
  29. if form.is_valid():
  30. # Light security check -- make sure redirect_to isn't garbage.
  31. if not redirect_to or ' ' in redirect_to:
  32. redirect_to = settings.LOGIN_REDIRECT_URL
  33. # Heavier security check -- redirects to http://example.com should
  34. # not be allowed, but things like /view/?param=http://example.com
  35. # should be allowed. This regex checks if there is a '//' *before* a
  36. # question mark.
  37. elif '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
  38. redirect_to = settings.LOGIN_REDIRECT_URL
  39. # Okay, security checks complete. Log the user in.
  40. auth_login(request, form.get_user())
  41. if request.session.test_cookie_worked():
  42. request.session.delete_test_cookie()
  43. return HttpResponseRedirect(redirect_to)
  44. else:
  45. form = authentication_form(request)
  46. request.session.set_test_cookie()
  47. if Site._meta.installed:
  48. current_site = Site.objects.get_current()
  49. else:
  50. current_site = RequestSite(request)
  51. return render_to_response(template_name, {
  52. 'form': form,
  53. redirect_field_name: redirect_to,
  54. 'site': current_site,
  55. 'site_name': current_site.name,
  56. }, context_instance=RequestContext(request))
  57. def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME):
  58. "Logs out the user and displays 'You are logged out' message."
  59. from django.contrib.auth import logout
  60. logout(request)
  61. if next_page is None:
  62. redirect_to = request.REQUEST.get(redirect_field_name, '')
  63. if redirect_to:
  64. return HttpResponseRedirect(redirect_to)
  65. else:
  66. return render_to_response(template_name, {
  67. 'title': _('Logged out')
  68. }, context_instance=RequestContext(request))
  69. else:
  70. # Redirect to this page until the session has been cleared.
  71. return HttpResponseRedirect(next_page or request.path)
  72. def logout_then_login(request, login_url=None):
  73. "Logs out the user if he is logged in. Then redirects to the log-in page."
  74. if not login_url:
  75. login_url = settings.LOGIN_URL
  76. return logout(request, login_url)
  77. def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
  78. "Redirects the user to the login page, passing the given 'next' page"
  79. if not login_url:
  80. login_url = settings.LOGIN_URL
  81. return HttpResponseRedirect('%s?%s=%s' % (login_url, urlquote(redirect_field_name), urlquote(next)))
  82. # 4 views for password reset:
  83. # - password_reset sends the mail
  84. # - password_reset_done shows a success message for the above
  85. # - password_reset_confirm checks the link the user clicked and
  86. # prompts for a new password
  87. # - password_reset_complete shows a success message for the above
  88. @csrf_protect
  89. def password_reset(request, is_admin_site=False, template_name='registration/password_reset_form.html',
  90. email_template_name='registration/password_reset_email.html',
  91. password_reset_form=PasswordResetForm, token_generator=default_token_generator,
  92. post_reset_redirect=None, from_email=None):
  93. if post_reset_redirect is None:
  94. post_reset_redirect = reverse('django.contrib.auth.views.password_reset_done')
  95. if request.method == "POST":
  96. form = password_reset_form(request.POST)
  97. if form.is_valid():
  98. opts = {}
  99. opts['use_https'] = request.is_secure()
  100. opts['token_generator'] = token_generator
  101. opts['from_email'] = from_email
  102. if is_admin_site:
  103. opts['domain_override'] = request.META['HTTP_HOST']
  104. else:
  105. opts['email_template_name'] = email_template_name
  106. if not Site._meta.installed:
  107. opts['domain_override'] = RequestSite(request).domain
  108. form.save(**opts)
  109. return HttpResponseRedirect(post_reset_redirect)
  110. else:
  111. form = password_reset_form()
  112. return render_to_response(template_name, {
  113. 'form': form,
  114. }, context_instance=RequestContext(request))
  115. def password_reset_done(request, template_name='registration/password_reset_done.html'):
  116. return render_to_response(template_name, context_instance=RequestContext(request))
  117. # Doesn't need csrf_protect since no-one can guess the URL
  118. def password_reset_confirm(request, uidb36=None, token=None, template_name='registration/password_reset_confirm.html',
  119. token_generator=default_token_generator, set_password_form=SetPasswordForm,
  120. post_reset_redirect=None):
  121. """
  122. View that checks the hash in a password reset link and presents a
  123. form for entering a new password.
  124. """
  125. assert uidb36 is not None and token is not None # checked by URLconf
  126. if post_reset_redirect is None:
  127. post_reset_redirect = reverse('django.contrib.auth.views.password_reset_complete')
  128. try:
  129. uid_int = base36_to_int(uidb36)
  130. except ValueError:
  131. raise Http404
  132. user = get_object_or_404(User, id=uid_int)
  133. context_instance = RequestContext(request)
  134. if token_generator.check_token(user, token):
  135. context_instance['validlink'] = True
  136. if request.method == 'POST':
  137. form = set_password_form(user, request.POST)
  138. if form.is_valid():
  139. form.save()
  140. return HttpResponseRedirect(post_reset_redirect)
  141. else:
  142. form = set_password_form(None)
  143. else:
  144. context_instance['validlink'] = False
  145. form = None
  146. context_instance['form'] = form
  147. return render_to_response(template_name, context_instance=context_instance)
  148. def password_reset_complete(request, template_name='registration/password_reset_complete.html'):
  149. return render_to_response(template_name, context_instance=RequestContext(request,
  150. {'login_url': settings.LOGIN_URL}))
  151. @csrf_protect
  152. @login_required
  153. def password_change(request, template_name='registration/password_change_form.html',
  154. post_change_redirect=None, password_change_form=PasswordChangeForm):
  155. if post_change_redirect is None:
  156. post_change_redirect = reverse('django.contrib.auth.views.password_change_done')
  157. if request.method == "POST":
  158. form = password_change_form(user=request.user, data=request.POST)
  159. if form.is_valid():
  160. form.save()
  161. return HttpResponseRedirect(post_change_redirect)
  162. else:
  163. form = password_change_form(user=request.user)
  164. return render_to_response(template_name, {
  165. 'form': form,
  166. }, context_instance=RequestContext(request))
  167. def password_change_done(request, template_name='registration/password_change_done.html'):
  168. return render_to_response(template_name, context_instance=RequestContext(request))