summaryrefslogtreecommitdiff
path: root/tests/auth_tests/client.py
blob: 004101108b981ef4ab0dc44239728c646b8e1fb0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import re

from django.contrib.auth.views import (
    INTERNAL_RESET_SESSION_TOKEN, INTERNAL_RESET_URL_TOKEN,
)
from django.test import Client


def extract_token_from_url(url):
    token_search = re.search(r'/reset/.*/(.+?)/', url)
    if token_search:
        return token_search.group(1)


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/')
    """
    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()
        return url.replace(token, INTERNAL_RESET_URL_TOKEN)

    def get(self, path, *args, **kwargs):
        redirect_url = self._get_password_reset_confirm_redirect_url(path)
        return super(PasswordResetConfirmClient, self).get(redirect_url, *args, **kwargs)

    def post(self, path, *args, **kwargs):
        redirect_url = self._get_password_reset_confirm_redirect_url(path)
        return super(PasswordResetConfirmClient, self).post(redirect_url, *args, **kwargs)