test_deprecated_views.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. import datetime
  2. import itertools
  3. import re
  4. from urllib.parse import ParseResult, urlparse
  5. from django.conf import settings
  6. from django.contrib.auth import SESSION_KEY
  7. from django.contrib.auth.forms import (
  8. AuthenticationForm, PasswordChangeForm, SetPasswordForm,
  9. )
  10. from django.contrib.auth.models import User
  11. from django.core import mail
  12. from django.http import QueryDict
  13. from django.test import TestCase, override_settings
  14. from django.test.utils import ignore_warnings, patch_logger
  15. from django.utils.deprecation import RemovedInDjango21Warning
  16. from .models import CustomUser, UUIDUser
  17. from .settings import AUTH_TEMPLATES
  18. @override_settings(
  19. LANGUAGES=[('en', 'English')],
  20. LANGUAGE_CODE='en',
  21. TEMPLATES=AUTH_TEMPLATES,
  22. ROOT_URLCONF='auth_tests.urls_deprecated',
  23. )
  24. class AuthViewsTestCase(TestCase):
  25. """
  26. Helper base class for all the follow test cases.
  27. """
  28. @classmethod
  29. def setUpTestData(cls):
  30. cls.u1 = User.objects.create_user(username='testclient', password='password', email='testclient@example.com')
  31. cls.u3 = User.objects.create_user(username='staff', password='password', email='staffmember@example.com')
  32. def login(self, username='testclient', password='password'):
  33. response = self.client.post('/login/', {
  34. 'username': username,
  35. 'password': password,
  36. })
  37. self.assertIn(SESSION_KEY, self.client.session)
  38. return response
  39. def logout(self):
  40. response = self.client.get('/admin/logout/')
  41. self.assertEqual(response.status_code, 200)
  42. self.assertNotIn(SESSION_KEY, self.client.session)
  43. def assertFormError(self, response, error):
  44. """Assert that error is found in response.context['form'] errors"""
  45. form_errors = list(itertools.chain(*response.context['form'].errors.values()))
  46. self.assertIn(str(error), form_errors)
  47. def assertURLEqual(self, url, expected, parse_qs=False):
  48. """
  49. Given two URLs, make sure all their components (the ones given by
  50. urlparse) are equal, only comparing components that are present in both
  51. URLs.
  52. If `parse_qs` is True, then the querystrings are parsed with QueryDict.
  53. This is useful if you don't want the order of parameters to matter.
  54. Otherwise, the query strings are compared as-is.
  55. """
  56. fields = ParseResult._fields
  57. for attr, x, y in zip(fields, urlparse(url), urlparse(expected)):
  58. if parse_qs and attr == 'query':
  59. x, y = QueryDict(x), QueryDict(y)
  60. if x and y and x != y:
  61. self.fail("%r != %r (%s doesn't match)" % (url, expected, attr))
  62. @ignore_warnings(category=RemovedInDjango21Warning)
  63. class PasswordResetTest(AuthViewsTestCase):
  64. def test_email_not_found(self):
  65. """If the provided email is not registered, don't raise any error but
  66. also don't send any email."""
  67. response = self.client.get('/password_reset/')
  68. self.assertEqual(response.status_code, 200)
  69. response = self.client.post('/password_reset/', {'email': 'not_a_real_email@email.com'})
  70. self.assertEqual(response.status_code, 302)
  71. self.assertEqual(len(mail.outbox), 0)
  72. def test_email_found(self):
  73. "Email is sent if a valid email address is provided for password reset"
  74. response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
  75. self.assertEqual(response.status_code, 302)
  76. self.assertEqual(len(mail.outbox), 1)
  77. self.assertIn("http://", mail.outbox[0].body)
  78. self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email)
  79. # optional multipart text/html email has been added. Make sure original,
  80. # default functionality is 100% the same
  81. self.assertFalse(mail.outbox[0].message().is_multipart())
  82. def test_extra_email_context(self):
  83. """
  84. extra_email_context should be available in the email template context.
  85. """
  86. response = self.client.post(
  87. '/password_reset_extra_email_context/',
  88. {'email': 'staffmember@example.com'},
  89. )
  90. self.assertEqual(response.status_code, 302)
  91. self.assertEqual(len(mail.outbox), 1)
  92. self.assertIn('Email email context: "Hello!"', mail.outbox[0].body)
  93. def test_html_mail_template(self):
  94. """
  95. A multipart email with text/plain and text/html is sent
  96. if the html_email_template parameter is passed to the view
  97. """
  98. response = self.client.post('/password_reset/html_email_template/', {'email': 'staffmember@example.com'})
  99. self.assertEqual(response.status_code, 302)
  100. self.assertEqual(len(mail.outbox), 1)
  101. message = mail.outbox[0].message()
  102. self.assertEqual(len(message.get_payload()), 2)
  103. self.assertTrue(message.is_multipart())
  104. self.assertEqual(message.get_payload(0).get_content_type(), 'text/plain')
  105. self.assertEqual(message.get_payload(1).get_content_type(), 'text/html')
  106. self.assertNotIn('<html>', message.get_payload(0).get_payload())
  107. self.assertIn('<html>', message.get_payload(1).get_payload())
  108. def test_email_found_custom_from(self):
  109. "Email is sent if a valid email address is provided for password reset when a custom from_email is provided."
  110. response = self.client.post('/password_reset_from_email/', {'email': 'staffmember@example.com'})
  111. self.assertEqual(response.status_code, 302)
  112. self.assertEqual(len(mail.outbox), 1)
  113. self.assertEqual("staffmember@example.com", mail.outbox[0].from_email)
  114. # Skip any 500 handler action (like sending more mail...)
  115. @override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True)
  116. def test_poisoned_http_host(self):
  117. "Poisoned HTTP_HOST headers can't be used for reset emails"
  118. # This attack is based on the way browsers handle URLs. The colon
  119. # should be used to separate the port, but if the URL contains an @,
  120. # the colon is interpreted as part of a username for login purposes,
  121. # making 'evil.com' the request domain. Since HTTP_HOST is used to
  122. # produce a meaningful reset URL, we need to be certain that the
  123. # HTTP_HOST header isn't poisoned. This is done as a check when get_host()
  124. # is invoked, but we check here as a practical consequence.
  125. with patch_logger('django.security.DisallowedHost', 'error') as logger_calls:
  126. response = self.client.post(
  127. '/password_reset/',
  128. {'email': 'staffmember@example.com'},
  129. HTTP_HOST='www.example:dr.frankenstein@evil.tld'
  130. )
  131. self.assertEqual(response.status_code, 400)
  132. self.assertEqual(len(mail.outbox), 0)
  133. self.assertEqual(len(logger_calls), 1)
  134. # Skip any 500 handler action (like sending more mail...)
  135. @override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True)
  136. def test_poisoned_http_host_admin_site(self):
  137. "Poisoned HTTP_HOST headers can't be used for reset emails on admin views"
  138. with patch_logger('django.security.DisallowedHost', 'error') as logger_calls:
  139. response = self.client.post(
  140. '/admin_password_reset/',
  141. {'email': 'staffmember@example.com'},
  142. HTTP_HOST='www.example:dr.frankenstein@evil.tld'
  143. )
  144. self.assertEqual(response.status_code, 400)
  145. self.assertEqual(len(mail.outbox), 0)
  146. self.assertEqual(len(logger_calls), 1)
  147. def _test_confirm_start(self):
  148. # Start by creating the email
  149. self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
  150. self.assertEqual(len(mail.outbox), 1)
  151. return self._read_signup_email(mail.outbox[0])
  152. def _read_signup_email(self, email):
  153. urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
  154. self.assertIsNotNone(urlmatch, "No URL found in sent email")
  155. return urlmatch.group(), urlmatch.groups()[0]
  156. def test_confirm_valid(self):
  157. url, path = self._test_confirm_start()
  158. response = self.client.get(path)
  159. # redirect to a 'complete' page:
  160. self.assertContains(response, "Please enter your new password")
  161. def test_confirm_invalid(self):
  162. url, path = self._test_confirm_start()
  163. # Let's munge the token in the path, but keep the same length,
  164. # in case the URLconf will reject a different length.
  165. path = path[:-5] + ("0" * 4) + path[-1]
  166. response = self.client.get(path)
  167. self.assertContains(response, "The password reset link was invalid")
  168. def test_confirm_invalid_user(self):
  169. # We get a 200 response for a nonexistent user, not a 404
  170. response = self.client.get('/reset/123456/1-1/')
  171. self.assertContains(response, "The password reset link was invalid")
  172. def test_confirm_overflow_user(self):
  173. # We get a 200 response for a base36 user id that overflows int
  174. response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/')
  175. self.assertContains(response, "The password reset link was invalid")
  176. def test_confirm_invalid_post(self):
  177. # Same as test_confirm_invalid, but trying
  178. # to do a POST instead.
  179. url, path = self._test_confirm_start()
  180. path = path[:-5] + ("0" * 4) + path[-1]
  181. self.client.post(path, {
  182. 'new_password1': 'anewpassword',
  183. 'new_password2': ' anewpassword',
  184. })
  185. # Check the password has not been changed
  186. u = User.objects.get(email='staffmember@example.com')
  187. self.assertTrue(not u.check_password("anewpassword"))
  188. def test_confirm_complete(self):
  189. url, path = self._test_confirm_start()
  190. response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
  191. # Check the password has been changed
  192. u = User.objects.get(email='staffmember@example.com')
  193. self.assertTrue(u.check_password("anewpassword"))
  194. # Check we can't use the link again
  195. response = self.client.get(path)
  196. self.assertContains(response, "The password reset link was invalid")
  197. def test_confirm_different_passwords(self):
  198. url, path = self._test_confirm_start()
  199. response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'x'})
  200. self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch'])
  201. def test_reset_redirect_default(self):
  202. response = self.client.post('/password_reset/', {'email': 'staffmember@example.com'})
  203. self.assertEqual(response.status_code, 302)
  204. self.assertURLEqual(response.url, '/password_reset/done/')
  205. def test_reset_custom_redirect(self):
  206. response = self.client.post('/password_reset/custom_redirect/', {'email': 'staffmember@example.com'})
  207. self.assertEqual(response.status_code, 302)
  208. self.assertURLEqual(response.url, '/custom/')
  209. def test_reset_custom_redirect_named(self):
  210. response = self.client.post('/password_reset/custom_redirect/named/', {'email': 'staffmember@example.com'})
  211. self.assertEqual(response.status_code, 302)
  212. self.assertURLEqual(response.url, '/password_reset/')
  213. def test_confirm_redirect_default(self):
  214. url, path = self._test_confirm_start()
  215. response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
  216. self.assertEqual(response.status_code, 302)
  217. self.assertURLEqual(response.url, '/reset/done/')
  218. def test_confirm_redirect_custom(self):
  219. url, path = self._test_confirm_start()
  220. path = path.replace('/reset/', '/reset/custom/')
  221. response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
  222. self.assertEqual(response.status_code, 302)
  223. self.assertURLEqual(response.url, '/custom/')
  224. def test_confirm_redirect_custom_named(self):
  225. url, path = self._test_confirm_start()
  226. path = path.replace('/reset/', '/reset/custom/named/')
  227. response = self.client.post(path, {'new_password1': 'anewpassword', 'new_password2': 'anewpassword'})
  228. self.assertEqual(response.status_code, 302)
  229. self.assertURLEqual(response.url, '/password_reset/')
  230. def test_confirm_display_user_from_form(self):
  231. url, path = self._test_confirm_start()
  232. response = self.client.get(path)
  233. # #16919 -- The ``password_reset_confirm`` view should pass the user
  234. # object to the ``SetPasswordForm``, even on GET requests.
  235. # For this test, we render ``{{ form.user }}`` in the template
  236. # ``registration/password_reset_confirm.html`` so that we can test this.
  237. username = User.objects.get(email='staffmember@example.com').username
  238. self.assertContains(response, "Hello, %s." % username)
  239. # However, the view should NOT pass any user object on a form if the
  240. # password reset link was invalid.
  241. response = self.client.get('/reset/zzzzzzzzzzzzz/1-1/')
  242. self.assertContains(response, "Hello, .")
  243. @ignore_warnings(category=RemovedInDjango21Warning)
  244. @override_settings(AUTH_USER_MODEL='auth_tests.CustomUser')
  245. class CustomUserPasswordResetTest(AuthViewsTestCase):
  246. user_email = 'staffmember@example.com'
  247. @classmethod
  248. def setUpTestData(cls):
  249. cls.u1 = CustomUser.custom_objects.create(
  250. email='staffmember@example.com',
  251. date_of_birth=datetime.date(1976, 11, 8),
  252. )
  253. cls.u1.set_password('password')
  254. cls.u1.save()
  255. def _test_confirm_start(self):
  256. # Start by creating the email
  257. response = self.client.post('/password_reset/', {'email': self.user_email})
  258. self.assertEqual(response.status_code, 302)
  259. self.assertEqual(len(mail.outbox), 1)
  260. return self._read_signup_email(mail.outbox[0])
  261. def _read_signup_email(self, email):
  262. urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body)
  263. self.assertIsNotNone(urlmatch, "No URL found in sent email")
  264. return urlmatch.group(), urlmatch.groups()[0]
  265. def test_confirm_valid_custom_user(self):
  266. url, path = self._test_confirm_start()
  267. response = self.client.get(path)
  268. # redirect to a 'complete' page:
  269. self.assertContains(response, "Please enter your new password")
  270. # then submit a new password
  271. response = self.client.post(path, {
  272. 'new_password1': 'anewpassword',
  273. 'new_password2': 'anewpassword',
  274. })
  275. self.assertRedirects(response, '/reset/done/')
  276. @ignore_warnings(category=RemovedInDjango21Warning)
  277. @override_settings(AUTH_USER_MODEL='auth_tests.UUIDUser')
  278. class UUIDUserPasswordResetTest(CustomUserPasswordResetTest):
  279. def _test_confirm_start(self):
  280. # instead of fixture
  281. UUIDUser.objects.create_user(
  282. email=self.user_email,
  283. username='foo',
  284. password='foo',
  285. )
  286. return super()._test_confirm_start()
  287. @ignore_warnings(category=RemovedInDjango21Warning)
  288. class ChangePasswordTest(AuthViewsTestCase):
  289. def fail_login(self, password='password'):
  290. response = self.client.post('/login/', {
  291. 'username': 'testclient',
  292. 'password': password,
  293. })
  294. self.assertFormError(response, AuthenticationForm.error_messages['invalid_login'] % {
  295. 'username': User._meta.get_field('username').verbose_name
  296. })
  297. def logout(self):
  298. self.client.get('/logout/')
  299. def test_password_change_fails_with_invalid_old_password(self):
  300. self.login()
  301. response = self.client.post('/password_change/', {
  302. 'old_password': 'donuts',
  303. 'new_password1': 'password1',
  304. 'new_password2': 'password1',
  305. })
  306. self.assertFormError(response, PasswordChangeForm.error_messages['password_incorrect'])
  307. def test_password_change_fails_with_mismatched_passwords(self):
  308. self.login()
  309. response = self.client.post('/password_change/', {
  310. 'old_password': 'password',
  311. 'new_password1': 'password1',
  312. 'new_password2': 'donuts',
  313. })
  314. self.assertFormError(response, SetPasswordForm.error_messages['password_mismatch'])
  315. def test_password_change_succeeds(self):
  316. self.login()
  317. self.client.post('/password_change/', {
  318. 'old_password': 'password',
  319. 'new_password1': 'password1',
  320. 'new_password2': 'password1',
  321. })
  322. self.fail_login()
  323. self.login(password='password1')
  324. def test_password_change_done_succeeds(self):
  325. self.login()
  326. response = self.client.post('/password_change/', {
  327. 'old_password': 'password',
  328. 'new_password1': 'password1',
  329. 'new_password2': 'password1',
  330. })
  331. self.assertEqual(response.status_code, 302)
  332. self.assertURLEqual(response.url, '/password_change/done/')
  333. @override_settings(LOGIN_URL='/login/')
  334. def test_password_change_done_fails(self):
  335. response = self.client.get('/password_change/done/')
  336. self.assertEqual(response.status_code, 302)
  337. self.assertURLEqual(response.url, '/login/?next=/password_change/done/')
  338. def test_password_change_redirect_default(self):
  339. self.login()
  340. response = self.client.post('/password_change/', {
  341. 'old_password': 'password',
  342. 'new_password1': 'password1',
  343. 'new_password2': 'password1',
  344. })
  345. self.assertEqual(response.status_code, 302)
  346. self.assertURLEqual(response.url, '/password_change/done/')
  347. def test_password_change_redirect_custom(self):
  348. self.login()
  349. response = self.client.post('/password_change/custom/', {
  350. 'old_password': 'password',
  351. 'new_password1': 'password1',
  352. 'new_password2': 'password1',
  353. })
  354. self.assertEqual(response.status_code, 302)
  355. self.assertURLEqual(response.url, '/custom/')
  356. def test_password_change_redirect_custom_named(self):
  357. self.login()
  358. response = self.client.post('/password_change/custom/named/', {
  359. 'old_password': 'password',
  360. 'new_password1': 'password1',
  361. 'new_password2': 'password1',
  362. })
  363. self.assertEqual(response.status_code, 302)
  364. self.assertURLEqual(response.url, '/password_reset/')
  365. @ignore_warnings(category=RemovedInDjango21Warning)
  366. class SessionAuthenticationTests(AuthViewsTestCase):
  367. def test_user_password_change_updates_session(self):
  368. """
  369. #21649 - Ensure contrib.auth.views.password_change updates the user's
  370. session auth hash after a password change so the session isn't logged out.
  371. """
  372. self.login()
  373. response = self.client.post('/password_change/', {
  374. 'old_password': 'password',
  375. 'new_password1': 'password1',
  376. 'new_password2': 'password1',
  377. })
  378. # if the hash isn't updated, retrieving the redirection page will fail.
  379. self.assertRedirects(response, '/password_change/done/')