| 1 |
import json |
| 2 |
from http import HTTPStatus |
| 3 |
|
| 4 |
from django.contrib.auth import get_user_model |
| 5 |
from django.contrib.auth.models import AnonymousUser |
| 6 |
from django.core import mail |
| 7 |
from django.test import TestCase |
| 8 |
from django.test.utils import override_settings |
| 9 |
from django.urls import reverse, reverse_lazy |
| 10 |
from django.utils.http import urlencode |
| 11 |
|
| 12 |
import pytest |
| 13 |
from pytest_django.asserts import assertRedirects, assertTemplateUsed |
| 14 |
|
| 15 |
from allauth.account import app_settings |
| 16 |
from allauth.account.forms import ResetPasswordForm, default_token_generator |
| 17 |
from allauth.account.models import EmailAddress |
| 18 |
from allauth.account.utils import user_pk_to_url_str |
| 19 |
|
| 20 |
|
| 21 |
@pytest.fixture |
| 22 |
def password_reset_url(): |
| 23 |
def f(user): |
| 24 |
temp_key = default_token_generator.make_token(user) |
| 25 |
uid = user_pk_to_url_str(user) |
| 26 |
return reverse( |
| 27 |
"account_reset_password_from_key", kwargs={"uidb36": uid, "key": temp_key} |
| 28 |
) |
| 29 |
|
| 30 |
return f |
| 31 |
|
| 32 |
|
| 33 |
@pytest.mark.django_db |
| 34 |
def test_reset_password_unknown_account(client, settings): |
| 35 |
settings.ACCOUNT_PREVENT_ENUMERATION = True |
| 36 |
resp = client.post( |
| 37 |
reverse("account_reset_password"), |
| 38 |
data={"email": "[email protected]"}, |
| 39 |
follow=True, |
| 40 |
) |
| 41 |
assert len(mail.outbox) == 1 |
| 42 |
assert mail.outbox[0].to == ["[email protected]"] |
| 43 |
assert resp.redirect_chain == [ |
| 44 |
(reverse("account_reset_password_done"), HTTPStatus.FOUND) |
| 45 |
] |
| 46 |
|
| 47 |
|
| 48 |
@pytest.mark.django_db |
| 49 |
def test_reset_password_unknown_account_disabled(client, settings): |
| 50 |
settings.ACCOUNT_PREVENT_ENUMERATION = True |
| 51 |
settings.ACCOUNT_EMAIL_UNKNOWN_ACCOUNTS = False |
| 52 |
client.post( |
| 53 |
reverse("account_reset_password"), |
| 54 |
data={"email": "[email protected]"}, |
| 55 |
) |
| 56 |
assert len(mail.outbox) == 0 |
| 57 |
|
| 58 |
|
| 59 |
@pytest.mark.parametrize( |
| 60 |
"query,expected_location", |
| 61 |
[("", reverse_lazy("account_reset_password_done")), ("?next=/foo", "/foo")], |
| 62 |
) |
| 63 |
def test_reset_password_next_url(client, user, query, expected_location): |
| 64 |
resp = client.post( |
| 65 |
reverse("account_reset_password") + query, |
| 66 |
data={"email": user.email}, |
| 67 |
) |
| 68 |
assert resp["location"] == expected_location |
| 69 |
|
| 70 |
|
| 71 |
@override_settings( |
| 72 |
ACCOUNT_PREVENT_ENUMERATION=False, |
| 73 |
ACCOUNT_DEFAULT_HTTP_PROTOCOL="https", |
| 74 |
ACCOUNT_EMAIL_VERIFICATION=app_settings.EmailVerificationMethod.MANDATORY, |
| 75 |
ACCOUNT_LOGIN_METHODS={app_settings.AuthenticationMethod.USERNAME}, |
| 76 |
ACCOUNT_SIGNUP_FORM_CLASS=None, |
| 77 |
ACCOUNT_EMAIL_SUBJECT_PREFIX=None, |
| 78 |
LOGIN_REDIRECT_URL="/accounts/profile/", |
| 79 |
ACCOUNT_SIGNUP_REDIRECT_URL="/accounts/welcome/", |
| 80 |
ACCOUNT_ADAPTER="allauth.account.adapter.DefaultAccountAdapter", |
| 81 |
ACCOUNT_USERNAME_REQUIRED=True, |
| 82 |
ACCOUNT_EMAIL_NOTIFICATIONS=True, |
| 83 |
) |
| 84 |
class ResetPasswordTests(TestCase): |
| 85 |
def test_user_email_not_sent_inactive_user(self): |
| 86 |
User = get_user_model() |
| 87 |
User.objects.create_user( |
| 88 |
"mike123", "[email protected]", "test123", is_active=False |
| 89 |
) |
| 90 |
data = {"email": "[email protected]"} |
| 91 |
form = ResetPasswordForm(data) |
| 92 |
self.assertFalse(form.is_valid()) |
| 93 |
|
| 94 |
def test_password_reset_get(self): |
| 95 |
resp = self.client.get(reverse("account_reset_password")) |
| 96 |
self.assertTemplateUsed(resp, "account/password_reset.html") |
| 97 |
|
| 98 |
def test_set_password_not_allowed(self): |
| 99 |
user = self._create_user_and_login(True) |
| 100 |
pwd = "!*123i1uwn12W23" |
| 101 |
self.assertFalse(user.check_password(pwd)) |
| 102 |
resp = self.client.post( |
| 103 |
reverse("account_set_password"), |
| 104 |
data={"password1": pwd, "password2": pwd}, |
| 105 |
) |
| 106 |
user.refresh_from_db() |
| 107 |
self.assertFalse(user.check_password(pwd)) |
| 108 |
self.assertTrue(user.has_usable_password()) |
| 109 |
self.assertEqual(resp.status_code, HTTPStatus.FOUND) |
| 110 |
|
| 111 |
def test_password_forgotten_username_hint(self): |
| 112 |
user = self._request_new_password() |
| 113 |
body = mail.outbox[0].body |
| 114 |
assert user.username in body |
| 115 |
|
| 116 |
@override_settings(ACCOUNT_LOGIN_METHODS={app_settings.AuthenticationMethod.EMAIL}) |
| 117 |
def test_password_forgotten_no_username_hint(self): |
| 118 |
user = self._request_new_password() |
| 119 |
body = mail.outbox[0].body |
| 120 |
assert user.username not in body |
| 121 |
|
| 122 |
def _request_new_password(self): |
| 123 |
user = get_user_model().objects.create( |
| 124 |
username="john", email="[email protected]", is_active=True |
| 125 |
) |
| 126 |
user.set_password("doe") |
| 127 |
user.save() |
| 128 |
self.client.post( |
| 129 |
reverse("account_reset_password"), |
| 130 |
data={"email": "[email protected]"}, |
| 131 |
) |
| 132 |
self.assertEqual(len(mail.outbox), 1) |
| 133 |
self.assertEqual(mail.outbox[0].to, ["[email protected]"]) |
| 134 |
return user |
| 135 |
|
| 136 |
def test_password_reset_flow_with_empty_session(self): |
| 137 |
""" |
| 138 |
Test the password reset flow when the session is empty: |
| 139 |
requesting a new password, receiving the reset link via email, |
| 140 |
following the link, getting redirected to the |
| 141 |
new link (without the token) |
| 142 |
Copying the link and using it in a DIFFERENT client (Browser/Device). |
| 143 |
""" |
| 144 |
# Request new password |
| 145 |
self._request_new_password() |
| 146 |
body = mail.outbox[0].body |
| 147 |
self.assertGreater(body.find("https://"), 0) |
| 148 |
|
| 149 |
# Extract URL for `password_reset_from_key` view |
| 150 |
url = body[body.find("/accounts/password/reset/") :].split()[0] |
| 151 |
resp = self.client.get(url) |
| 152 |
|
| 153 |
reset_pass_url = resp.url |
| 154 |
|
| 155 |
# Accessing the url via a different session |
| 156 |
resp = self.client_class().get(reset_pass_url) |
| 157 |
|
| 158 |
# We should receive the token_fail context_data |
| 159 |
self.assertTemplateUsed( |
| 160 |
resp, |
| 161 |
f"account/password_reset_from_key.{app_settings.TEMPLATE_EXTENSION}", |
| 162 |
) |
| 163 |
|
| 164 |
self.assertTrue(resp.context_data["token_fail"]) |
| 165 |
|
| 166 |
@override_settings(ACCOUNT_LOGIN_METHODS={app_settings.AuthenticationMethod.EMAIL}) |
| 167 |
def test_password_reset_flow_with_another_user_logged_in(self): |
| 168 |
""" |
| 169 |
Tests the password reset flow: if User B requested a password |
| 170 |
reset earlier and now User A is logged in, User B now clicks on |
| 171 |
the link, ensure User A is logged out before continuing. |
| 172 |
""" |
| 173 |
# Request new password |
| 174 |
self._request_new_password() |
| 175 |
body = mail.outbox[0].body |
| 176 |
self.assertGreater(body.find("https://"), 0) |
| 177 |
|
| 178 |
user2 = self._create_user(username="john2", email="[email protected]") |
| 179 |
EmailAddress.objects.create( |
| 180 |
user=user2, email=user2.email, primary=True, verified=True |
| 181 |
) |
| 182 |
resp = self.client.post( |
| 183 |
reverse("account_login"), |
| 184 |
{ |
| 185 |
"login": user2.email, |
| 186 |
"password": "doe", |
| 187 |
}, |
| 188 |
) |
| 189 |
self.assertEqual(user2, resp.context["user"]) |
| 190 |
|
| 191 |
# Extract URL for `password_reset_from_key` view and access it |
| 192 |
url = body[body.find("/accounts/password/reset/") :].split()[0] |
| 193 |
resp = self.client.get(url) |
| 194 |
# Follow the redirect the actual password reset page with the key |
| 195 |
# hidden. |
| 196 |
url = resp.url |
| 197 |
resp = self.client.get(url) |
| 198 |
self.assertTemplateUsed( |
| 199 |
resp, f"account/password_reset_from_key.{app_settings.TEMPLATE_EXTENSION}" |
| 200 |
) |
| 201 |
self.assertFalse("token_fail" in resp.context_data) |
| 202 |
|
| 203 |
# Reset the password |
| 204 |
resp = self.client.post( |
| 205 |
url, {"password1": "newpass123", "password2": "newpass123"}, follow=True |
| 206 |
) |
| 207 |
self.assertRedirects(resp, reverse("account_reset_password_from_key_done")) |
| 208 |
|
| 209 |
self.assertNotEqual(user2, resp.context["user"]) |
| 210 |
self.assertEqual(AnonymousUser(), resp.context["user"]) |
| 211 |
|
| 212 |
def test_password_reset_flow_with_email_changed(self): |
| 213 |
""" |
| 214 |
Test that the password reset token is invalidated if |
| 215 |
the user email address was changed. |
| 216 |
""" |
| 217 |
user = self._request_new_password() |
| 218 |
body = mail.outbox[0].body |
| 219 |
self.assertGreater(body.find("https://"), 0) |
| 220 |
EmailAddress.objects.create(user=user, email="[email protected]") |
| 221 |
# Extract URL for `password_reset_from_key` view |
| 222 |
url = body[body.find("/accounts/password/reset/") :].split()[0] |
| 223 |
resp = self.client.get(url) |
| 224 |
self.assertTemplateUsed( |
| 225 |
resp, |
| 226 |
f"account/password_reset_from_key.{app_settings.TEMPLATE_EXTENSION}", |
| 227 |
) |
| 228 |
self.assertTrue("token_fail" in resp.context_data) |
| 229 |
|
| 230 |
@override_settings(ACCOUNT_LOGIN_ON_PASSWORD_RESET=True) |
| 231 |
def test_password_reset_ACCOUNT_LOGIN_ON_PASSWORD_RESET(self): |
| 232 |
user = self._request_new_password() |
| 233 |
body = mail.outbox[0].body |
| 234 |
url = body[body.find("/accounts/password/reset/") :].split()[0] |
| 235 |
resp = self.client.get(url) |
| 236 |
# Follow the redirect the actual password reset page with the key |
| 237 |
# hidden. |
| 238 |
resp = self.client.post( |
| 239 |
resp.url, {"password1": "newpass123", "password2": "newpass123"} |
| 240 |
) |
| 241 |
self.assertTrue(user.is_authenticated) |
| 242 |
# EmailVerificationMethod.MANDATORY sends us to the confirm-email page |
| 243 |
self.assertRedirects(resp, "/accounts/confirm-email/") |
| 244 |
|
| 245 |
def _create_user(self, username="john", password="doe", **kwargs): |
| 246 |
user = get_user_model().objects.create( |
| 247 |
username=username, is_active=True, **kwargs |
| 248 |
) |
| 249 |
if password: |
| 250 |
user.set_password(password) |
| 251 |
else: |
| 252 |
user.set_unusable_password() |
| 253 |
user.save() |
| 254 |
return user |
| 255 |
|
| 256 |
def _create_user_and_login(self, usable_password=True): |
| 257 |
password = "doe" if usable_password else False |
| 258 |
user = self._create_user(password=password) |
| 259 |
self.client.force_login(user) |
| 260 |
return user |
| 261 |
|
| 262 |
|
| 263 |
def test_password_reset_flow(client, user, mailoutbox, settings): |
| 264 |
""" |
| 265 |
Tests the password reset flow: requesting a new password, |
| 266 |
receiving the reset link via email and finally resetting the |
| 267 |
password to a new value. |
| 268 |
""" |
| 269 |
settings.ACCOUNT_EMAIL_NOTIFICATIONS = True |
| 270 |
|
| 271 |
# Request new password |
| 272 |
client.post( |
| 273 |
reverse("account_reset_password"), |
| 274 |
data={"email": user.email}, |
| 275 |
) |
| 276 |
assert len(mail.outbox) == 1 |
| 277 |
assert mailoutbox[0].to == [user.email] |
| 278 |
body = mailoutbox[0].body |
| 279 |
assert body.find("http://") > 0 |
| 280 |
|
| 281 |
# Extract URL for `password_reset_from_key` view and access it |
| 282 |
url = body[body.find("/accounts/password/reset/") :].split()[0] |
| 283 |
resp = client.get(url) |
| 284 |
# Follow the redirect the actual password reset page with the key |
| 285 |
# hidden. |
| 286 |
url = resp.url |
| 287 |
resp = client.get(url) |
| 288 |
assertTemplateUsed( |
| 289 |
resp, |
| 290 |
f"account/password_reset_from_key.{app_settings.TEMPLATE_EXTENSION}", |
| 291 |
) |
| 292 |
assert "token_fail" not in resp.context_data |
| 293 |
|
| 294 |
# Reset the password |
| 295 |
resp = client.post(url, {"password1": "newpass123", "password2": "newpass123"}) |
| 296 |
assertRedirects(resp, reverse("account_reset_password_from_key_done")) |
| 297 |
assert "Your password has been reset" in mailoutbox[-1].body |
| 298 |
|
| 299 |
# Check the new password is in effect |
| 300 |
user = get_user_model().objects.get(pk=user.pk) |
| 301 |
assert user.check_password("newpass123") |
| 302 |
|
| 303 |
# Trying to reset the password against the same URL (or any other |
| 304 |
# invalid/obsolete URL) returns a bad token response |
| 305 |
resp = client.post(url, {"password1": "newpass123", "password2": "newpass123"}) |
| 306 |
assertTemplateUsed( |
| 307 |
resp, |
| 308 |
f"account/password_reset_from_key.{app_settings.TEMPLATE_EXTENSION}", |
| 309 |
) |
| 310 |
assert resp.context_data["token_fail"] |
| 311 |
|
| 312 |
# Same should happen when accessing the page directly |
| 313 |
response = client.get(url) |
| 314 |
assertTemplateUsed( |
| 315 |
response, |
| 316 |
f"account/password_reset_from_key.{app_settings.TEMPLATE_EXTENSION}", |
| 317 |
) |
| 318 |
assert response.context_data["token_fail"] |
| 319 |
|
| 320 |
# When in XHR views, it should respond with a 400 bad request |
| 321 |
# code, and the response body should contain the JSON-encoded |
| 322 |
# error from the adapter |
| 323 |
response = client.post( |
| 324 |
url, |
| 325 |
{"password1": "newpass123", "password2": "newpass123"}, |
| 326 |
HTTP_X_REQUESTED_WITH="XMLHttpRequest", |
| 327 |
) |
| 328 |
assert response.status_code == HTTPStatus.BAD_REQUEST |
| 329 |
data = json.loads(response.content.decode("utf8")) |
| 330 |
assert "invalid" in data["form"]["errors"][0] |
| 331 |
|
| 332 |
|
| 333 |
@pytest.mark.parametrize( |
| 334 |
"next_url,expected_location", |
| 335 |
[(None, reverse_lazy("account_reset_password_from_key_done")), ("/foo", "/foo")], |
| 336 |
) |
| 337 |
def test_reset_password_from_key_next_url( |
| 338 |
user, client, password_factory, next_url, expected_location, password_reset_url |
| 339 |
): |
| 340 |
url = password_reset_url(user) |
| 341 |
query = "" |
| 342 |
if next_url: |
| 343 |
query = f"?{urlencode({'next': next_url})}" |
| 344 |
resp = client.get(url + query) |
| 345 |
assert resp.status_code == HTTPStatus.FOUND |
| 346 |
assert ( |
| 347 |
resp["location"] |
| 348 |
== reverse( |
| 349 |
"account_reset_password_from_key", |
| 350 |
kwargs={"uidb36": user_pk_to_url_str(user), "key": "set-password"}, |
| 351 |
) |
| 352 |
+ query |
| 353 |
) |
| 354 |
password = password_factory() |
| 355 |
data = {"password1": password, "password2": password} |
| 356 |
if next_url: |
| 357 |
data["next"] = next_url |
| 358 |
resp = client.post(resp["location"], data) |
| 359 |
assert resp.status_code == HTTPStatus.FOUND |
| 360 |
assert resp["location"] == expected_location |