client.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import re
  2. from django.contrib.auth.views import (
  3. INTERNAL_RESET_SESSION_TOKEN, INTERNAL_RESET_URL_TOKEN,
  4. )
  5. from django.test import Client
  6. def extract_token_from_url(url):
  7. token_search = re.search(r'/reset/.*/(.+?)/', url)
  8. if token_search:
  9. return token_search.group(1)
  10. class PasswordResetConfirmClient(Client):
  11. """
  12. This client eases testing the password reset flow by emulating the
  13. PasswordResetConfirmView's redirect and saving of the reset token in the
  14. user's session. This request puts 'my-token' in the session and redirects
  15. to '/reset/bla/set-password/':
  16. >>> client = PasswordResetConfirmClient()
  17. >>> client.get('/reset/bla/my-token/')
  18. """
  19. def _get_password_reset_confirm_redirect_url(self, url):
  20. token = extract_token_from_url(url)
  21. if not token:
  22. return url
  23. # Add the token to the session
  24. session = self.session
  25. session[INTERNAL_RESET_SESSION_TOKEN] = token
  26. session.save()
  27. return url.replace(token, INTERNAL_RESET_URL_TOKEN)
  28. def get(self, path, *args, **kwargs):
  29. redirect_url = self._get_password_reset_confirm_redirect_url(path)
  30. return super().get(redirect_url, *args, **kwargs)
  31. def post(self, path, *args, **kwargs):
  32. redirect_url = self._get_password_reset_confirm_redirect_url(path)
  33. return super().post(redirect_url, *args, **kwargs)