You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. from urllib.parse import urlparse, urlunparse
  2. from django.conf import settings
  3. # Avoid shadowing the login() and logout() views below.
  4. from django.contrib.auth import (
  5. REDIRECT_FIELD_NAME, get_user_model, login as auth_login,
  6. logout as auth_logout, update_session_auth_hash,
  7. )
  8. from django.contrib.auth.decorators import login_required
  9. from django.contrib.auth.forms import (
  10. AuthenticationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm,
  11. )
  12. from django.contrib.auth.tokens import default_token_generator
  13. from django.contrib.sites.shortcuts import get_current_site
  14. from django.core.exceptions import ValidationError
  15. from django.http import HttpResponseRedirect, QueryDict
  16. from django.shortcuts import resolve_url
  17. from django.urls import reverse_lazy
  18. from django.utils.decorators import method_decorator
  19. from django.utils.http import is_safe_url, urlsafe_base64_decode
  20. from django.utils.translation import gettext_lazy as _
  21. from django.views.decorators.cache import never_cache
  22. from django.views.decorators.csrf import csrf_protect
  23. from django.views.decorators.debug import sensitive_post_parameters
  24. from django.views.generic.base import TemplateView
  25. from django.views.generic.edit import FormView
  26. UserModel = get_user_model()
  27. class SuccessURLAllowedHostsMixin:
  28. success_url_allowed_hosts = set()
  29. def get_success_url_allowed_hosts(self):
  30. return {self.request.get_host(), *self.success_url_allowed_hosts}
  31. class LoginView(SuccessURLAllowedHostsMixin, FormView):
  32. """
  33. Display the login form and handle the login action.
  34. """
  35. form_class = AuthenticationForm
  36. authentication_form = None
  37. redirect_field_name = REDIRECT_FIELD_NAME
  38. template_name = 'registration/login.html'
  39. redirect_authenticated_user = False
  40. extra_context = None
  41. @method_decorator(sensitive_post_parameters())
  42. @method_decorator(csrf_protect)
  43. @method_decorator(never_cache)
  44. def dispatch(self, request, *args, **kwargs):
  45. if self.redirect_authenticated_user and self.request.user.is_authenticated:
  46. redirect_to = self.get_success_url()
  47. if redirect_to == self.request.path:
  48. raise ValueError(
  49. "Redirection loop for authenticated user detected. Check that "
  50. "your LOGIN_REDIRECT_URL doesn't point to a login page."
  51. )
  52. return HttpResponseRedirect(redirect_to)
  53. return super().dispatch(request, *args, **kwargs)
  54. def get_success_url(self):
  55. url = self.get_redirect_url()
  56. return url or resolve_url(settings.LOGIN_REDIRECT_URL)
  57. def get_redirect_url(self):
  58. """Return the user-originating redirect URL if it's safe."""
  59. redirect_to = self.request.POST.get(
  60. self.redirect_field_name,
  61. self.request.GET.get(self.redirect_field_name, '')
  62. )
  63. url_is_safe = is_safe_url(
  64. url=redirect_to,
  65. allowed_hosts=self.get_success_url_allowed_hosts(),
  66. require_https=self.request.is_secure(),
  67. )
  68. return redirect_to if url_is_safe else ''
  69. def get_form_class(self):
  70. return self.authentication_form or self.form_class
  71. def get_form_kwargs(self):
  72. kwargs = super().get_form_kwargs()
  73. kwargs['request'] = self.request
  74. return kwargs
  75. def form_valid(self, form):
  76. """Security check complete. Log the user in."""
  77. auth_login(self.request, form.get_user())
  78. return HttpResponseRedirect(self.get_success_url())
  79. def get_context_data(self, **kwargs):
  80. context = super().get_context_data(**kwargs)
  81. current_site = get_current_site(self.request)
  82. context.update({
  83. self.redirect_field_name: self.get_redirect_url(),
  84. 'site': current_site,
  85. 'site_name': current_site.name,
  86. **(self.extra_context or {})
  87. })
  88. return context
  89. class LogoutView(SuccessURLAllowedHostsMixin, TemplateView):
  90. """
  91. Log out the user and display the 'You are logged out' message.
  92. """
  93. next_page = None
  94. redirect_field_name = REDIRECT_FIELD_NAME
  95. template_name = 'registration/logged_out.html'
  96. extra_context = None
  97. @method_decorator(never_cache)
  98. def dispatch(self, request, *args, **kwargs):
  99. auth_logout(request)
  100. next_page = self.get_next_page()
  101. if next_page:
  102. # Redirect to this page until the session has been cleared.
  103. return HttpResponseRedirect(next_page)
  104. return super().dispatch(request, *args, **kwargs)
  105. def post(self, request, *args, **kwargs):
  106. """Logout may be done via POST."""
  107. return self.get(request, *args, **kwargs)
  108. def get_next_page(self):
  109. if self.next_page is not None:
  110. next_page = resolve_url(self.next_page)
  111. elif settings.LOGOUT_REDIRECT_URL:
  112. next_page = resolve_url(settings.LOGOUT_REDIRECT_URL)
  113. else:
  114. next_page = self.next_page
  115. if (self.redirect_field_name in self.request.POST or
  116. self.redirect_field_name in self.request.GET):
  117. next_page = self.request.POST.get(
  118. self.redirect_field_name,
  119. self.request.GET.get(self.redirect_field_name)
  120. )
  121. url_is_safe = is_safe_url(
  122. url=next_page,
  123. allowed_hosts=self.get_success_url_allowed_hosts(),
  124. require_https=self.request.is_secure(),
  125. )
  126. # Security check -- Ensure the user-originating redirection URL is
  127. # safe.
  128. if not url_is_safe:
  129. next_page = self.request.path
  130. return next_page
  131. def get_context_data(self, **kwargs):
  132. context = super().get_context_data(**kwargs)
  133. current_site = get_current_site(self.request)
  134. context.update({
  135. 'site': current_site,
  136. 'site_name': current_site.name,
  137. 'title': _('Logged out'),
  138. **(self.extra_context or {})
  139. })
  140. return context
  141. def logout_then_login(request, login_url=None):
  142. """
  143. Log out the user if they are logged in. Then redirect to the login page.
  144. """
  145. login_url = resolve_url(login_url or settings.LOGIN_URL)
  146. return LogoutView.as_view(next_page=login_url)(request)
  147. def redirect_to_login(next, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
  148. """
  149. Redirect the user to the login page, passing the given 'next' page.
  150. """
  151. resolved_url = resolve_url(login_url or settings.LOGIN_URL)
  152. login_url_parts = list(urlparse(resolved_url))
  153. if redirect_field_name:
  154. querystring = QueryDict(login_url_parts[4], mutable=True)
  155. querystring[redirect_field_name] = next
  156. login_url_parts[4] = querystring.urlencode(safe='/')
  157. return HttpResponseRedirect(urlunparse(login_url_parts))
  158. # Class-based password reset views
  159. # - PasswordResetView sends the mail
  160. # - PasswordResetDoneView shows a success message for the above
  161. # - PasswordResetConfirmView checks the link the user clicked and
  162. # prompts for a new password
  163. # - PasswordResetCompleteView shows a success message for the above
  164. class PasswordContextMixin:
  165. extra_context = None
  166. def get_context_data(self, **kwargs):
  167. context = super().get_context_data(**kwargs)
  168. context.update({
  169. 'title': self.title,
  170. **(self.extra_context or {})
  171. })
  172. return context
  173. class PasswordResetView(PasswordContextMixin, FormView):
  174. email_template_name = 'registration/password_reset_email.html'
  175. extra_email_context = None
  176. form_class = PasswordResetForm
  177. from_email = None
  178. html_email_template_name = None
  179. subject_template_name = 'registration/password_reset_subject.txt'
  180. success_url = reverse_lazy('password_reset_done')
  181. template_name = 'registration/password_reset_form.html'
  182. title = _('Password reset')
  183. token_generator = default_token_generator
  184. @method_decorator(csrf_protect)
  185. def dispatch(self, *args, **kwargs):
  186. return super().dispatch(*args, **kwargs)
  187. def form_valid(self, form):
  188. opts = {
  189. 'use_https': self.request.is_secure(),
  190. 'token_generator': self.token_generator,
  191. 'from_email': self.from_email,
  192. 'email_template_name': self.email_template_name,
  193. 'subject_template_name': self.subject_template_name,
  194. 'request': self.request,
  195. 'html_email_template_name': self.html_email_template_name,
  196. 'extra_email_context': self.extra_email_context,
  197. }
  198. form.save(**opts)
  199. return super().form_valid(form)
  200. INTERNAL_RESET_URL_TOKEN = 'set-password'
  201. INTERNAL_RESET_SESSION_TOKEN = '_password_reset_token'
  202. class PasswordResetDoneView(PasswordContextMixin, TemplateView):
  203. template_name = 'registration/password_reset_done.html'
  204. title = _('Password reset sent')
  205. class PasswordResetConfirmView(PasswordContextMixin, FormView):
  206. form_class = SetPasswordForm
  207. post_reset_login = False
  208. post_reset_login_backend = None
  209. success_url = reverse_lazy('password_reset_complete')
  210. template_name = 'registration/password_reset_confirm.html'
  211. title = _('Enter new password')
  212. token_generator = default_token_generator
  213. @method_decorator(sensitive_post_parameters())
  214. @method_decorator(never_cache)
  215. def dispatch(self, *args, **kwargs):
  216. assert 'uidb64' in kwargs and 'token' in kwargs
  217. self.validlink = False
  218. self.user = self.get_user(kwargs['uidb64'])
  219. if self.user is not None:
  220. token = kwargs['token']
  221. if token == INTERNAL_RESET_URL_TOKEN:
  222. session_token = self.request.session.get(INTERNAL_RESET_SESSION_TOKEN)
  223. if self.token_generator.check_token(self.user, session_token):
  224. # If the token is valid, display the password reset form.
  225. self.validlink = True
  226. return super().dispatch(*args, **kwargs)
  227. else:
  228. if self.token_generator.check_token(self.user, token):
  229. # Store the token in the session and redirect to the
  230. # password reset form at a URL without the token. That
  231. # avoids the possibility of leaking the token in the
  232. # HTTP Referer header.
  233. self.request.session[INTERNAL_RESET_SESSION_TOKEN] = token
  234. redirect_url = self.request.path.replace(token, INTERNAL_RESET_URL_TOKEN)
  235. return HttpResponseRedirect(redirect_url)
  236. # Display the "Password reset unsuccessful" page.
  237. return self.render_to_response(self.get_context_data())
  238. def get_user(self, uidb64):
  239. try:
  240. # urlsafe_base64_decode() decodes to bytestring
  241. uid = urlsafe_base64_decode(uidb64).decode()
  242. user = UserModel._default_manager.get(pk=uid)
  243. except (TypeError, ValueError, OverflowError, UserModel.DoesNotExist, ValidationError):
  244. user = None
  245. return user
  246. def get_form_kwargs(self):
  247. kwargs = super().get_form_kwargs()
  248. kwargs['user'] = self.user
  249. return kwargs
  250. def form_valid(self, form):
  251. user = form.save()
  252. del self.request.session[INTERNAL_RESET_SESSION_TOKEN]
  253. if self.post_reset_login:
  254. auth_login(self.request, user, self.post_reset_login_backend)
  255. return super().form_valid(form)
  256. def get_context_data(self, **kwargs):
  257. context = super().get_context_data(**kwargs)
  258. if self.validlink:
  259. context['validlink'] = True
  260. else:
  261. context.update({
  262. 'form': None,
  263. 'title': _('Password reset unsuccessful'),
  264. 'validlink': False,
  265. })
  266. return context
  267. class PasswordResetCompleteView(PasswordContextMixin, TemplateView):
  268. template_name = 'registration/password_reset_complete.html'
  269. title = _('Password reset complete')
  270. def get_context_data(self, **kwargs):
  271. context = super().get_context_data(**kwargs)
  272. context['login_url'] = resolve_url(settings.LOGIN_URL)
  273. return context
  274. class PasswordChangeView(PasswordContextMixin, FormView):
  275. form_class = PasswordChangeForm
  276. success_url = reverse_lazy('password_change_done')
  277. template_name = 'registration/password_change_form.html'
  278. title = _('Password change')
  279. @method_decorator(sensitive_post_parameters())
  280. @method_decorator(csrf_protect)
  281. @method_decorator(login_required)
  282. def dispatch(self, *args, **kwargs):
  283. return super().dispatch(*args, **kwargs)
  284. def get_form_kwargs(self):
  285. kwargs = super().get_form_kwargs()
  286. kwargs['user'] = self.request.user
  287. return kwargs
  288. def form_valid(self, form):
  289. form.save()
  290. # Updating the password logs out all other sessions for the user
  291. # except the current one.
  292. update_session_auth_hash(self.request, form.user)
  293. return super().form_valid(form)
  294. class PasswordChangeDoneView(PasswordContextMixin, TemplateView):
  295. template_name = 'registration/password_change_done.html'
  296. title = _('Password change successful')
  297. @method_decorator(login_required)
  298. def dispatch(self, *args, **kwargs):
  299. return super().dispatch(*args, **kwargs)