test_user_management.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. """
  2. This module tests deSEC's user management.
  3. The tests are separated into two categories, where
  4. (a) the client has an associated user account and
  5. (b) does not have an associated user account.
  6. This involves testing five separate endpoints:
  7. (1) Registration endpoint,
  8. (2) Reset password endpoint,
  9. (3) Change email address endpoint,
  10. (4) delete user endpoint, and
  11. (5) verify endpoint.
  12. """
  13. import re
  14. from django.core import mail
  15. from rest_framework import status
  16. from rest_framework.reverse import reverse
  17. from rest_framework.test import APIClient
  18. from api import settings
  19. from desecapi.models import Domain, User
  20. from desecapi.tests.base import DesecTestCase, PublicSuffixMockMixin
  21. class UserManagementClient(APIClient):
  22. def register(self, email, password, **kwargs):
  23. return self.post(reverse('v1:register'), {
  24. 'email': email,
  25. 'password': password,
  26. **kwargs
  27. })
  28. def login_user(self, email, password):
  29. return self.post(reverse('v1:login'), {
  30. 'email': email,
  31. 'password': password,
  32. })
  33. def reset_password(self, email):
  34. return self.post(reverse('v1:account-reset-password'), {
  35. 'email': email,
  36. })
  37. def change_email(self, email, password, **payload):
  38. payload['email'] = email
  39. payload['password'] = password
  40. return self.post(reverse('v1:account-change-email'), payload)
  41. def change_email_token_auth(self, token, **payload):
  42. return self.post(reverse('v1:account-change-email'), payload, HTTP_AUTHORIZATION='Token {}'.format(token))
  43. def delete_account(self, email, password):
  44. return self.post(reverse('v1:account-delete'), {
  45. 'email': email,
  46. 'password': password,
  47. })
  48. def view_account(self, token):
  49. return self.get(reverse('v1:account'), HTTP_AUTHORIZATION='Token {}'.format(token))
  50. def verify(self, url, **kwargs):
  51. return self.post(url, kwargs) if kwargs else self.get(url)
  52. class UserManagementTestCase(DesecTestCase, PublicSuffixMockMixin):
  53. client_class = UserManagementClient
  54. password = None
  55. token = None
  56. def register_user(self, email=None, password=None, **kwargs):
  57. email = email if email is not None else self.random_username()
  58. password = password if password is not None else self.random_password()
  59. return email.strip(), password, self.client.register(email, password, **kwargs)
  60. def login_user(self, email, password):
  61. response = self.client.login_user(email, password)
  62. token = response.data.get('auth_token')
  63. return token, response
  64. def reset_password(self, email):
  65. return self.client.reset_password(email)
  66. def change_email(self, new_email):
  67. return self.client.change_email(self.email, self.password, new_email=new_email)
  68. def delete_account(self, email, password):
  69. return self.client.delete_account(email, password)
  70. def assertContains(self, response, text, count=None, status_code=200, msg_prefix='', html=False):
  71. msg_prefix += '\nResponse: %s' % response.data
  72. super().assertContains(response, text, count, status_code, msg_prefix, html)
  73. def assertPassword(self, email, password):
  74. password = password.strip()
  75. self.assertTrue(User.objects.get(email=email).check_password(password),
  76. 'Expected user password to be "%s" (potentially trimmed), but check failed.' % password)
  77. def assertUserExists(self, email):
  78. try:
  79. User.objects.get(email=email)
  80. except User.DoesNotExist:
  81. self.fail('Expected user %s to exist, but did not.' % email)
  82. def assertUserDoesNotExist(self, email):
  83. # noinspection PyTypeChecker
  84. with self.assertRaises(User.DoesNotExist):
  85. User.objects.get(email=email)
  86. def assertNoEmailSent(self):
  87. self.assertFalse(mail.outbox, "Expected no email to be sent, but %i were sent. First subject line is '%s'." %
  88. (len(mail.outbox), mail.outbox[0].subject if mail.outbox else '<n/a>'))
  89. def assertEmailSent(self, subject_contains='', body_contains='', recipient=None, reset=True, pattern=None):
  90. total = 1
  91. self.assertEqual(len(mail.outbox), total, "Expected %i message in the outbox, but found %i." %
  92. (total, len(mail.outbox)))
  93. email = mail.outbox[-1]
  94. self.assertTrue(subject_contains in email.subject,
  95. "Expected '%s' in the email subject, but found '%s'" %
  96. (subject_contains, email.subject))
  97. self.assertTrue(body_contains in email.body,
  98. "Expected '%s' in the email body, but found '%s'" %
  99. (body_contains, email.body))
  100. if recipient is not None:
  101. if isinstance(recipient, list):
  102. self.assertListEqual(recipient, email.recipients())
  103. else:
  104. self.assertIn(recipient, email.recipients())
  105. body = email.body
  106. if reset:
  107. mail.outbox = []
  108. return body if not pattern else re.search(pattern, body).group(1)
  109. def assertRegistrationEmail(self, recipient, reset=True):
  110. return self.assertEmailSent(
  111. subject_contains='deSEC',
  112. body_contains='Thank you for registering with deSEC!',
  113. recipient=[recipient],
  114. reset=reset,
  115. pattern=r'following link:\s+([^\s]*)',
  116. )
  117. def assertResetPasswordEmail(self, recipient, reset=True):
  118. return self.assertEmailSent(
  119. subject_contains='Password reset',
  120. body_contains='We received a request to reset the password for your deSEC account.',
  121. recipient=[recipient],
  122. reset=reset,
  123. pattern=r'following link:\s+([^\s]*)',
  124. )
  125. def assertChangeEmailVerificationEmail(self, recipient, reset=True):
  126. return self.assertEmailSent(
  127. subject_contains='Confirmation required: Email address change',
  128. body_contains='You requested to change the email address associated',
  129. recipient=[recipient],
  130. reset=reset,
  131. pattern=r'following link:\s+([^\s]*)',
  132. )
  133. def assertChangeEmailNotificationEmail(self, recipient, reset=True):
  134. return self.assertEmailSent(
  135. subject_contains='Account email address changed',
  136. body_contains='We\'re writing to let you know that the email address associated with',
  137. recipient=[recipient],
  138. reset=reset,
  139. )
  140. def assertDeleteAccountEmail(self, recipient, reset=True):
  141. return self.assertEmailSent(
  142. subject_contains='Confirmation required: Delete account',
  143. body_contains='confirm once more',
  144. recipient=[recipient],
  145. reset=reset,
  146. pattern=r'following link:\s+([^\s]*)',
  147. )
  148. def assertRegistrationSuccessResponse(self, response):
  149. return self.assertContains(
  150. response=response,
  151. text="Welcome! Please check your mailbox.",
  152. status_code=status.HTTP_202_ACCEPTED
  153. )
  154. def assertLoginSuccessResponse(self, response):
  155. return self.assertContains(
  156. response=response,
  157. text="auth_token",
  158. status_code=status.HTTP_200_OK
  159. )
  160. def assertRegistrationFailurePasswordRequiredResponse(self, response):
  161. self.assertContains(
  162. response=response,
  163. text="This field may not be blank",
  164. status_code=status.HTTP_400_BAD_REQUEST
  165. )
  166. self.assertEqual(response.data['password'][0].code, 'blank')
  167. def assertRegistrationFailureDomainUnavailableResponse(self, response, domain, reason):
  168. self.assertContains(
  169. response=response,
  170. text=("The requested domain {} could not be registered (reason: {}). "
  171. "Please start over and sign up again.".format(domain, reason)),
  172. status_code=status.HTTP_400_BAD_REQUEST,
  173. msg_prefix=str(response.data)
  174. )
  175. def assertRegistrationVerificationSuccessResponse(self, response):
  176. return self.assertContains(
  177. response=response,
  178. text="Success! Please log in at",
  179. status_code=status.HTTP_200_OK
  180. )
  181. def assertRegistrationWithDomainVerificationSuccessResponse(self, response, domain=None):
  182. if domain and domain.endswith('.dedyn.io'):
  183. text = 'Success! Here is the password'
  184. else:
  185. text = 'Success! Please check the docs for the next steps'
  186. return self.assertContains(
  187. response=response,
  188. text=text,
  189. status_code=status.HTTP_200_OK
  190. )
  191. def assertResetPasswordSuccessResponse(self, response):
  192. return self.assertContains(
  193. response=response,
  194. text="Please check your mailbox for further password reset instructions.",
  195. status_code=status.HTTP_202_ACCEPTED
  196. )
  197. def assertResetPasswordVerificationSuccessResponse(self, response):
  198. return self.assertContains(
  199. response=response,
  200. text="Success! Your password has been changed.",
  201. status_code=status.HTTP_200_OK
  202. )
  203. def assertChangeEmailSuccessResponse(self, response):
  204. return self.assertContains(
  205. response=response,
  206. text="Please check your mailbox to confirm email address change.",
  207. status_code=status.HTTP_202_ACCEPTED
  208. )
  209. def assert401InvalidPasswordResponse(self, response):
  210. return self.assertContains(
  211. response=response,
  212. text="Invalid password.",
  213. status_code=status.HTTP_401_UNAUTHORIZED
  214. )
  215. def assertChangeEmailFailureAddressTakenResponse(self, response):
  216. return self.assertContains(
  217. response=response,
  218. text="You already have another account with this email address.",
  219. status_code=status.HTTP_400_BAD_REQUEST
  220. )
  221. def assertChangeEmailFailureSameAddressResponse(self, response):
  222. return self.assertContains(
  223. response=response,
  224. text="Email address unchanged.",
  225. status_code=status.HTTP_400_BAD_REQUEST
  226. )
  227. def assertChangeEmailVerificationSuccessResponse(self, response):
  228. return self.assertContains(
  229. response=response,
  230. text="Success! Your email address has been changed to",
  231. status_code=status.HTTP_200_OK
  232. )
  233. def assertChangeEmailVerificationFailureChangePasswordResponse(self, response):
  234. return self.assertContains(
  235. response=response,
  236. text="This field is not allowed for action ",
  237. status_code=status.HTTP_400_BAD_REQUEST
  238. )
  239. def assertDeleteAccountSuccessResponse(self, response):
  240. return self.assertContains(
  241. response=response,
  242. text="Please check your mailbox for further account deletion instructions.",
  243. status_code=status.HTTP_202_ACCEPTED
  244. )
  245. def assertDeleteAccountVerificationSuccessResponse(self, response):
  246. return self.assertContains(
  247. response=response,
  248. text="All your data has been deleted. Bye bye, see you soon! <3",
  249. status_code=status.HTTP_200_OK
  250. )
  251. def assertVerificationFailureInvalidCodeResponse(self, response):
  252. return self.assertContains(
  253. response=response,
  254. text="Bad signature.",
  255. status_code=status.HTTP_400_BAD_REQUEST
  256. )
  257. def assertVerificationFailureUnknownUserResponse(self, response):
  258. return self.assertContains(
  259. response=response,
  260. text="This user does not exist.",
  261. status_code=status.HTTP_400_BAD_REQUEST
  262. )
  263. def _test_registration(self, email=None, password=None, **kwargs):
  264. email, password, response = self.register_user(email, password, **kwargs)
  265. self.assertRegistrationSuccessResponse(response)
  266. self.assertUserExists(email)
  267. self.assertFalse(User.objects.get(email=email).is_active)
  268. self.assertPassword(email, password)
  269. confirmation_link = self.assertRegistrationEmail(email)
  270. self.assertRegistrationVerificationSuccessResponse(self.client.verify(confirmation_link))
  271. self.assertTrue(User.objects.get(email=email).is_active)
  272. self.assertPassword(email, password)
  273. return email, password
  274. def _test_registration_with_domain(self, email=None, password=None, domain=None, expect_failure_reason=None):
  275. domain = domain or self.random_domain_name()
  276. email, password, response = self.register_user(email, password, domain=domain)
  277. self.assertRegistrationSuccessResponse(response)
  278. self.assertUserExists(email)
  279. self.assertFalse(User.objects.get(email=email).is_active)
  280. self.assertPassword(email, password)
  281. confirmation_link = self.assertRegistrationEmail(email)
  282. if expect_failure_reason is None:
  283. if domain.endswith('.dedyn.io'):
  284. cm = self.requests_desec_domain_creation_auto_delegation(domain)
  285. else:
  286. cm = self.requests_desec_domain_creation(domain)
  287. with self.assertPdnsRequests(cm[:-1]):
  288. response = self.client.verify(confirmation_link)
  289. self.assertRegistrationWithDomainVerificationSuccessResponse(response, domain)
  290. self.assertTrue(User.objects.get(email=email).is_active)
  291. self.assertPassword(email, password)
  292. self.assertTrue(Domain.objects.filter(name=domain, owner__email=email).exists())
  293. return email, password, domain
  294. else:
  295. domain_exists = Domain.objects.filter(name=domain).exists()
  296. response = self.client.verify(confirmation_link)
  297. self.assertRegistrationFailureDomainUnavailableResponse(response, domain, expect_failure_reason)
  298. self.assertUserDoesNotExist(email)
  299. self.assertEqual(Domain.objects.filter(name=domain).exists(), domain_exists)
  300. def _test_login(self):
  301. token, response = self.login_user(self.email, self.password)
  302. self.assertLoginSuccessResponse(response)
  303. return token
  304. def _test_reset_password(self, email, new_password=None, **kwargs):
  305. new_password = new_password or self.random_password()
  306. self.assertResetPasswordSuccessResponse(self.reset_password(email))
  307. confirmation_link = self.assertResetPasswordEmail(email)
  308. self.assertResetPasswordVerificationSuccessResponse(
  309. self.client.verify(confirmation_link, new_password=new_password, **kwargs))
  310. self.assertPassword(email, new_password)
  311. return new_password
  312. def _test_change_email(self):
  313. old_email = self.email
  314. new_email = ' {} '.format(self.random_username()) # test trimming
  315. self.assertChangeEmailSuccessResponse(self.change_email(new_email))
  316. new_email = new_email.strip()
  317. confirmation_link = self.assertChangeEmailVerificationEmail(new_email)
  318. self.assertChangeEmailVerificationSuccessResponse(self.client.verify(confirmation_link))
  319. self.assertChangeEmailNotificationEmail(old_email)
  320. self.assertUserExists(new_email)
  321. self.assertUserDoesNotExist(old_email)
  322. self.email = new_email
  323. return self.email
  324. def _test_delete_account(self, email, password):
  325. self.assertDeleteAccountSuccessResponse(self.delete_account(email, password))
  326. confirmation_link = self.assertDeleteAccountEmail(email)
  327. self.assertDeleteAccountVerificationSuccessResponse(self.client.verify(confirmation_link))
  328. self.assertUserDoesNotExist(email)
  329. class UserLifeCycleTestCase(UserManagementTestCase):
  330. def test_life_cycle(self):
  331. self.email, self.password = self._test_registration()
  332. self.password = self._test_reset_password(self.email)
  333. mail.outbox = []
  334. self.token = self._test_login()
  335. email = self._test_change_email()
  336. self._test_delete_account(email, self.password)
  337. class NoUserAccountTestCase(UserLifeCycleTestCase):
  338. def test_home(self):
  339. self.assertResponse(self.client.get(reverse('v1:root')), status.HTTP_200_OK)
  340. def test_registration(self):
  341. self._test_registration()
  342. def test_registration_trim_email(self):
  343. user_email = ' {} '.format(self.random_username())
  344. email, new_password = self._test_registration(user_email)
  345. self.assertEqual(email, user_email.strip())
  346. def test_registration_with_domain(self):
  347. PublicSuffixMockMixin.setUpMockPatch(self)
  348. with self.get_psl_context_manager('.'):
  349. _, _, domain = self._test_registration_with_domain()
  350. self._test_registration_with_domain(domain=domain, expect_failure_reason='unique')
  351. self._test_registration_with_domain(domain='töö--', expect_failure_reason='invalid_domain_name')
  352. with self.get_psl_context_manager('co.uk'):
  353. self._test_registration_with_domain(domain='co.uk', expect_failure_reason='name_unavailable')
  354. with self.get_psl_context_manager('dedyn.io'):
  355. self._test_registration_with_domain(domain=self.random_domain_name(suffix='dedyn.io'))
  356. def test_registration_known_account(self):
  357. email, _ = self._test_registration()
  358. self.assertRegistrationSuccessResponse(self.register_user(email, self.random_password())[2])
  359. self.assertNoEmailSent()
  360. def test_registration_password_required(self):
  361. email = self.random_username()
  362. self.assertRegistrationFailurePasswordRequiredResponse(
  363. response=self.register_user(email=email, password='')[2]
  364. )
  365. self.assertNoEmailSent()
  366. self.assertUserDoesNotExist(email)
  367. def test_registration_spam_protection(self):
  368. email = self.random_username()
  369. self.assertRegistrationSuccessResponse(
  370. response=self.register_user(email=email)[2]
  371. )
  372. self.assertRegistrationEmail(email)
  373. for _ in range(5):
  374. self.assertRegistrationSuccessResponse(
  375. response=self.register_user(email=email)[2]
  376. )
  377. self.assertNoEmailSent()
  378. class OtherUserAccountTestCase(UserManagementTestCase):
  379. def setUp(self):
  380. super().setUp()
  381. self.other_email, self.other_password = self._test_registration()
  382. def test_reset_password_unknown_user(self):
  383. self.assertResetPasswordSuccessResponse(
  384. response=self.reset_password(self.random_username())
  385. )
  386. self.assertNoEmailSent()
  387. class HasUserAccountTestCase(UserManagementTestCase):
  388. def __init__(self, methodName: str = ...) -> None:
  389. super().__init__(methodName)
  390. self.email = None
  391. self.password = None
  392. def setUp(self):
  393. super().setUp()
  394. self.email, self.password = self._test_registration()
  395. self.token = self._test_login()
  396. def _start_reset_password(self):
  397. self.assertResetPasswordSuccessResponse(
  398. response=self.reset_password(self.email)
  399. )
  400. return self.assertResetPasswordEmail(self.email)
  401. def _start_change_email(self):
  402. new_email = self.random_username()
  403. self.assertChangeEmailSuccessResponse(
  404. response=self.change_email(new_email)
  405. )
  406. return self.assertChangeEmailVerificationEmail(new_email), new_email
  407. def _start_delete_account(self):
  408. self.assertDeleteAccountSuccessResponse(self.delete_account(self.email, self.password))
  409. return self.assertDeleteAccountEmail(self.email)
  410. def _finish_reset_password(self, confirmation_link, expect_success=True):
  411. new_password = self.random_password()
  412. response = self.client.verify(confirmation_link, new_password=new_password)
  413. if expect_success:
  414. self.assertResetPasswordVerificationSuccessResponse(response=response)
  415. else:
  416. self.assertVerificationFailureInvalidCodeResponse(response)
  417. return new_password
  418. def _finish_change_email(self, confirmation_link, expect_success=True):
  419. response = self.client.verify(confirmation_link)
  420. if expect_success:
  421. self.assertChangeEmailVerificationSuccessResponse(response)
  422. self.assertChangeEmailNotificationEmail(self.email)
  423. else:
  424. self.assertVerificationFailureInvalidCodeResponse(response)
  425. def _finish_delete_account(self, confirmation_link):
  426. self.assertDeleteAccountVerificationSuccessResponse(self.client.verify(confirmation_link))
  427. self.assertUserDoesNotExist(self.email)
  428. def test_view_account(self):
  429. response = self.client.view_account(self.token)
  430. self.assertEqual(response.status_code, 200)
  431. self.assertTrue('created' in response.data)
  432. self.assertEqual(response.data['email'], self.email)
  433. self.assertEqual(response.data['id'], User.objects.get(email=self.email).pk)
  434. self.assertEqual(response.data['limit_domains'], settings.LIMIT_USER_DOMAIN_COUNT_DEFAULT)
  435. def test_view_account_read_only(self):
  436. # Should this test ever be removed (to allow writeable fields), make sure to
  437. # add new tests for each read-only field individually (such as limit_domains)!
  438. for method in [self.client.put, self.client.post, self.client.delete]:
  439. response = method(
  440. reverse('v1:account'),
  441. {'limit_domains': 99},
  442. HTTP_AUTHORIZATION='Token {}'.format(self.token)
  443. )
  444. self.assertResponse(response, status.HTTP_405_METHOD_NOT_ALLOWED)
  445. def test_reset_password(self):
  446. self._test_reset_password(self.email)
  447. def test_reset_password_inactive_user(self):
  448. user = User.objects.get(email=self.email)
  449. user.is_active = False
  450. user.save()
  451. self.assertResetPasswordSuccessResponse(self.reset_password(self.email))
  452. self.assertNoEmailSent()
  453. def test_reset_password_multiple_times(self):
  454. for _ in range(3):
  455. self._test_reset_password(self.email)
  456. mail.outbox = []
  457. def test_reset_password_during_change_email_interleaved(self):
  458. reset_password_verification_code = self._start_reset_password()
  459. change_email_verification_code, new_email = self._start_change_email()
  460. new_password = self._finish_reset_password(reset_password_verification_code)
  461. self._finish_change_email(change_email_verification_code, expect_success=False)
  462. self.assertUserExists(self.email)
  463. self.assertUserDoesNotExist(new_email)
  464. self.assertPassword(self.email, new_password)
  465. def test_reset_password_during_change_email_nested(self):
  466. change_email_verification_code, new_email = self._start_change_email()
  467. reset_password_verification_code = self._start_reset_password()
  468. new_password = self._finish_reset_password(reset_password_verification_code)
  469. self._finish_change_email(change_email_verification_code, expect_success=False)
  470. self.assertUserExists(self.email)
  471. self.assertUserDoesNotExist(new_email)
  472. self.assertPassword(self.email, new_password)
  473. def test_reset_password_validation_unknown_user(self):
  474. confirmation_link = self._start_reset_password()
  475. self._test_delete_account(self.email, self.password)
  476. self.assertVerificationFailureUnknownUserResponse(
  477. response=self.client.verify(confirmation_link)
  478. )
  479. self.assertNoEmailSent()
  480. def test_change_email(self):
  481. self._test_change_email()
  482. def test_change_email_requires_password(self):
  483. # Make sure that the account's email address cannot be changed with a token (password required)
  484. new_email = self.random_username()
  485. response = self.client.change_email_token_auth(self.token, new_email=new_email)
  486. self.assertContains(response, 'You do not have permission', status_code=status.HTTP_403_FORBIDDEN)
  487. self.assertNoEmailSent()
  488. def test_change_email_multiple_times(self):
  489. for _ in range(3):
  490. self._test_change_email()
  491. def test_change_email_user_exists(self):
  492. known_email, _ = self._test_registration()
  493. # We send a verification link to the new email and check account existence only later, upon verification
  494. self.assertChangeEmailSuccessResponse(
  495. response=self.change_email(known_email)
  496. )
  497. def test_change_email_verification_user_exists(self):
  498. new_email = self.random_username()
  499. self.assertChangeEmailSuccessResponse(self.change_email(new_email))
  500. confirmation_link = self.assertChangeEmailVerificationEmail(new_email)
  501. new_email, new_password = self._test_registration(new_email)
  502. self.assertChangeEmailFailureAddressTakenResponse(
  503. response=self.client.verify(confirmation_link)
  504. )
  505. self.assertUserExists(self.email)
  506. self.assertPassword(self.email, self.password)
  507. self.assertUserExists(new_email)
  508. self.assertPassword(new_email, new_password)
  509. def test_change_email_verification_change_password(self):
  510. new_email = self.random_username()
  511. self.assertChangeEmailSuccessResponse(self.change_email(new_email))
  512. confirmation_link = self.assertChangeEmailVerificationEmail(new_email)
  513. response = self.client.verify(confirmation_link, new_password=self.random_password())
  514. self.assertStatus(response, status.HTTP_405_METHOD_NOT_ALLOWED)
  515. def test_change_email_same_email(self):
  516. self.assertChangeEmailFailureSameAddressResponse(
  517. response=self.change_email(self.email)
  518. )
  519. self.assertUserExists(self.email)
  520. def test_change_email_during_reset_password_interleaved(self):
  521. change_email_verification_code, new_email = self._start_change_email()
  522. reset_password_verification_code = self._start_reset_password()
  523. self._finish_change_email(change_email_verification_code)
  524. self._finish_reset_password(reset_password_verification_code, expect_success=False)
  525. self.assertUserExists(new_email)
  526. self.assertUserDoesNotExist(self.email)
  527. self.assertPassword(new_email, self.password)
  528. def test_change_email_during_reset_password_nested(self):
  529. reset_password_verification_code = self._start_reset_password()
  530. change_email_verification_code, new_email = self._start_change_email()
  531. self._finish_change_email(change_email_verification_code)
  532. self._finish_reset_password(reset_password_verification_code, expect_success=False)
  533. self.assertUserExists(new_email)
  534. self.assertUserDoesNotExist(self.email)
  535. self.assertPassword(new_email, self.password)
  536. def test_change_email_nested(self):
  537. verification_code_1, new_email_1 = self._start_change_email()
  538. verification_code_2, new_email_2 = self._start_change_email()
  539. self._finish_change_email(verification_code_2)
  540. self.assertUserDoesNotExist(self.email)
  541. self.assertUserDoesNotExist(new_email_1)
  542. self.assertUserExists(new_email_2)
  543. self._finish_change_email(verification_code_1, expect_success=False)
  544. self.assertUserDoesNotExist(self.email)
  545. self.assertUserDoesNotExist(new_email_1)
  546. self.assertUserExists(new_email_2)
  547. def test_change_email_interleaved(self):
  548. verification_code_1, new_email_1 = self._start_change_email()
  549. verification_code_2, new_email_2 = self._start_change_email()
  550. self._finish_change_email(verification_code_1)
  551. self.assertUserDoesNotExist(self.email)
  552. self.assertUserExists(new_email_1)
  553. self.assertUserDoesNotExist(new_email_2)
  554. self._finish_change_email(verification_code_2, expect_success=False)
  555. self.assertUserDoesNotExist(self.email)
  556. self.assertUserExists(new_email_1)
  557. self.assertUserDoesNotExist(new_email_2)
  558. def test_change_email_validation_unknown_user(self):
  559. confirmation_link, new_email = self._start_change_email()
  560. self._test_delete_account(self.email, self.password)
  561. self.assertVerificationFailureUnknownUserResponse(
  562. response=self.client.verify(confirmation_link)
  563. )
  564. self.assertNoEmailSent()
  565. def test_delete_account_validation_unknown_user(self):
  566. confirmation_link = self._start_delete_account()
  567. self._test_delete_account(self.email, self.password)
  568. self.assertVerificationFailureUnknownUserResponse(
  569. response=self.client.verify(confirmation_link)
  570. )
  571. self.assertNoEmailSent()
  572. def test_reset_password_password_strip(self):
  573. password = ' %s ' % self.random_password()
  574. self._test_reset_password(self.email, password)
  575. self.assertPassword(self.email, password.strip())
  576. self.assertPassword(self.email, password)
  577. def test_reset_password_no_code_override(self):
  578. password = self.random_password()
  579. self._test_reset_password(self.email, password, code='foobar')
  580. self.assertPassword(self.email, password)