2017-01-13 15:17:54 +01:00
|
|
|
import re
|
|
|
|
|
|
|
|
from django.contrib.auth.views import (
|
2019-05-23 14:18:49 +02:00
|
|
|
INTERNAL_RESET_SESSION_TOKEN,
|
|
|
|
PasswordResetConfirmView,
|
2017-01-13 15:17:54 +01:00
|
|
|
)
|
|
|
|
from django.test import Client
|
|
|
|
|
|
|
|
|
|
|
|
def extract_token_from_url(url):
|
|
|
|
token_search = re.search(r"/reset/.*/(.+?)/", url)
|
|
|
|
if token_search:
|
2020-05-10 22:03:39 +02:00
|
|
|
return token_search[1]
|
2017-01-13 15:17:54 +01:00
|
|
|
|
|
|
|
|
|
|
|
class PasswordResetConfirmClient(Client):
|
|
|
|
"""
|
|
|
|
This client eases testing the password reset flow by emulating the
|
|
|
|
PasswordResetConfirmView's redirect and saving of the reset token in the
|
|
|
|
user's session. This request puts 'my-token' in the session and redirects
|
|
|
|
to '/reset/bla/set-password/':
|
|
|
|
|
|
|
|
>>> client = PasswordResetConfirmClient()
|
|
|
|
>>> client.get('/reset/bla/my-token/')
|
|
|
|
"""
|
2022-02-03 20:24:19 +01:00
|
|
|
|
2019-05-23 14:18:49 +02:00
|
|
|
reset_url_token = PasswordResetConfirmView.reset_url_token
|
|
|
|
|
2017-01-13 15:17:54 +01:00
|
|
|
def _get_password_reset_confirm_redirect_url(self, url):
|
|
|
|
token = extract_token_from_url(url)
|
|
|
|
if not token:
|
|
|
|
return url
|
|
|
|
# Add the token to the session
|
|
|
|
session = self.session
|
|
|
|
session[INTERNAL_RESET_SESSION_TOKEN] = token
|
|
|
|
session.save()
|
2019-05-23 14:18:49 +02:00
|
|
|
return url.replace(token, self.reset_url_token)
|
2017-01-13 15:17:54 +01:00
|
|
|
|
|
|
|
def get(self, path, *args, **kwargs):
|
|
|
|
redirect_url = self._get_password_reset_confirm_redirect_url(path)
|
2017-01-21 14:13:44 +01:00
|
|
|
return super().get(redirect_url, *args, **kwargs)
|
2017-01-13 15:17:54 +01:00
|
|
|
|
|
|
|
def post(self, path, *args, **kwargs):
|
|
|
|
redirect_url = self._get_password_reset_confirm_redirect_url(path)
|
2017-01-21 14:13:44 +01:00
|
|
|
return super().post(redirect_url, *args, **kwargs)
|