| 1 |
import datetime |
| 2 |
import itertools |
| 3 |
import re |
| 4 |
from importlib import import_module |
| 5 |
from unittest import mock |
| 6 |
from urllib.parse import quote, urljoin |
| 7 |
|
| 8 |
from django.apps import apps |
| 9 |
from django.conf import settings |
| 10 |
from django.contrib.admin.models import LogEntry |
| 11 |
from django.contrib.auth import BACKEND_SESSION_KEY, REDIRECT_FIELD_NAME, SESSION_KEY |
| 12 |
from django.contrib.auth.forms import ( |
| 13 |
AuthenticationForm, |
| 14 |
PasswordChangeForm, |
| 15 |
SetPasswordForm, |
| 16 |
) |
| 17 |
from django.contrib.auth.models import Permission, User |
| 18 |
from django.contrib.auth.views import ( |
| 19 |
INTERNAL_RESET_SESSION_TOKEN, |
| 20 |
LoginView, |
| 21 |
RedirectURLMixin, |
| 22 |
logout_then_login, |
| 23 |
redirect_to_login, |
| 24 |
) |
| 25 |
from django.contrib.contenttypes.models import ContentType |
| 26 |
from django.contrib.messages import Message |
| 27 |
from django.contrib.messages.test import MessagesTestMixin |
| 28 |
from django.contrib.sessions.middleware import SessionMiddleware |
| 29 |
from django.contrib.sites.requests import RequestSite |
| 30 |
from django.core import mail |
| 31 |
from django.core.exceptions import ImproperlyConfigured |
| 32 |
from django.db import connection |
| 33 |
from django.http import HttpRequest, HttpResponse |
| 34 |
from django.middleware.csrf import CsrfViewMiddleware, get_token |
| 35 |
from django.test import Client, TestCase, modify_settings, override_settings |
| 36 |
from django.test.client import RedirectCycleError |
| 37 |
from django.urls import NoReverseMatch, reverse, reverse_lazy |
| 38 |
from django.utils.http import urlsafe_base64_encode |
| 39 |
|
| 40 |
from .client import PasswordResetConfirmClient |
| 41 |
from .models import CustomUser, CustomUserCompositePrimaryKey, UUIDUser |
| 42 |
from .settings import AUTH_TEMPLATES |
| 43 |
|
| 44 |
|
| 45 |
class RedirectURLMixinTests(TestCase): |
| 46 |
@override_settings(ROOT_URLCONF="auth_tests.urls") |
| 47 |
def test_get_default_redirect_url_next_page(self): |
| 48 |
class RedirectURLView(RedirectURLMixin): |
| 49 |
next_page = "/custom/" |
| 50 |
|
| 51 |
self.assertEqual(RedirectURLView().get_default_redirect_url(), "/custom/") |
| 52 |
|
| 53 |
def test_get_default_redirect_url_no_next_page(self): |
| 54 |
msg = "No URL to redirect to. Provide a next_page." |
| 55 |
with self.assertRaisesMessage(ImproperlyConfigured, msg): |
| 56 |
RedirectURLMixin().get_default_redirect_url() |
| 57 |
|
| 58 |
|
| 59 |
@override_settings( |
| 60 |
LANGUAGES=[("en", "English")], |
| 61 |
LANGUAGE_CODE="en", |
| 62 |
TEMPLATES=AUTH_TEMPLATES, |
| 63 |
ROOT_URLCONF="auth_tests.urls", |
| 64 |
) |
| 65 |
class AuthViewsTestCase(TestCase): |
| 66 |
""" |
| 67 |
Helper base class for the test classes that follow. |
| 68 |
""" |
| 69 |
|
| 70 |
@classmethod |
| 71 |
def setUpTestData(cls): |
| 72 |
cls.u1 = User.objects.create_user( |
| 73 |
username="testclient", password="password", email="[email protected]" |
| 74 |
) |
| 75 |
cls.u3 = User.objects.create_user( |
| 76 |
username="staff", password="password", email="[email protected]" |
| 77 |
) |
| 78 |
|
| 79 |
def login(self, username="testclient", password="password", url="/login/"): |
| 80 |
response = self.client.post( |
| 81 |
url, |
| 82 |
{ |
| 83 |
"username": username, |
| 84 |
"password": password, |
| 85 |
}, |
| 86 |
) |
| 87 |
self.assertIn(SESSION_KEY, self.client.session) |
| 88 |
return response |
| 89 |
|
| 90 |
def logout(self): |
| 91 |
response = self.client.post("/admin/logout/") |
| 92 |
self.assertEqual(response.status_code, 200) |
| 93 |
self.assertNotIn(SESSION_KEY, self.client.session) |
| 94 |
|
| 95 |
def assertFormError(self, response, error): |
| 96 |
"""Assert that error is found in response.context['form'] errors""" |
| 97 |
form_errors = list(itertools.chain(*response.context["form"].errors.values())) |
| 98 |
self.assertIn(str(error), form_errors) |
| 99 |
|
| 100 |
|
| 101 |
@override_settings(ROOT_URLCONF="django.contrib.auth.urls") |
| 102 |
class AuthViewNamedURLTests(AuthViewsTestCase): |
| 103 |
def test_named_urls(self): |
| 104 |
"Named URLs should be reversible" |
| 105 |
expected_named_urls = [ |
| 106 |
("login", [], {}), |
| 107 |
("logout", [], {}), |
| 108 |
("password_change", [], {}), |
| 109 |
("password_change_done", [], {}), |
| 110 |
("password_reset", [], {}), |
| 111 |
("password_reset_done", [], {}), |
| 112 |
( |
| 113 |
"password_reset_confirm", |
| 114 |
[], |
| 115 |
{ |
| 116 |
"uidb64": "aaaaaaa", |
| 117 |
"token": "1111-aaaaa", |
| 118 |
}, |
| 119 |
), |
| 120 |
("password_reset_complete", [], {}), |
| 121 |
] |
| 122 |
for name, args, kwargs in expected_named_urls: |
| 123 |
with self.subTest(name=name): |
| 124 |
try: |
| 125 |
reverse(name, args=args, kwargs=kwargs) |
| 126 |
except NoReverseMatch: |
| 127 |
self.fail( |
| 128 |
"Reversal of url named '%s' failed with NoReverseMatch" % name |
| 129 |
) |
| 130 |
|
| 131 |
|
| 132 |
class PasswordResetTest(AuthViewsTestCase): |
| 133 |
def setUp(self): |
| 134 |
self.client = PasswordResetConfirmClient() |
| 135 |
|
| 136 |
def test_email_not_found(self): |
| 137 |
"""If the provided email is not registered, don't raise any error but |
| 138 |
also don't send any email.""" |
| 139 |
response = self.client.get("/password_reset/") |
| 140 |
self.assertEqual(response.status_code, 200) |
| 141 |
response = self.client.post( |
| 142 |
"/password_reset/", {"email": "[email protected]"} |
| 143 |
) |
| 144 |
self.assertEqual(response.status_code, 302) |
| 145 |
self.assertEqual(len(mail.outbox), 0) |
| 146 |
|
| 147 |
def test_email_found(self): |
| 148 |
"Email is sent if a valid email address is provided for password reset" |
| 149 |
response = self.client.post( |
| 150 |
"/password_reset/", {"email": "[email protected]"} |
| 151 |
) |
| 152 |
self.assertEqual(response.status_code, 302) |
| 153 |
self.assertEqual(len(mail.outbox), 1) |
| 154 |
self.assertIn("http://", mail.outbox[0].body) |
| 155 |
self.assertEqual(settings.DEFAULT_FROM_EMAIL, mail.outbox[0].from_email) |
| 156 |
# optional multipart text/html email has been added. Make sure original, |
| 157 |
# default functionality is 100% the same |
| 158 |
self.assertFalse(mail.outbox[0].message().is_multipart()) |
| 159 |
|
| 160 |
def test_extra_email_context(self): |
| 161 |
""" |
| 162 |
extra_email_context should be available in the email template context. |
| 163 |
""" |
| 164 |
response = self.client.post( |
| 165 |
"/password_reset_extra_email_context/", |
| 166 |
{"email": "[email protected]"}, |
| 167 |
) |
| 168 |
self.assertEqual(response.status_code, 302) |
| 169 |
self.assertEqual(len(mail.outbox), 1) |
| 170 |
self.assertIn('Email email context: "Hello!"', mail.outbox[0].body) |
| 171 |
self.assertIn("http://custom.example.com/reset/", mail.outbox[0].body) |
| 172 |
|
| 173 |
def test_html_mail_template(self): |
| 174 |
""" |
| 175 |
A multipart email with text/plain and text/html is sent |
| 176 |
if the html_email_template parameter is passed to the view |
| 177 |
""" |
| 178 |
response = self.client.post( |
| 179 |
"/password_reset/html_email_template/", {"email": "[email protected]"} |
| 180 |
) |
| 181 |
self.assertEqual(response.status_code, 302) |
| 182 |
self.assertEqual(len(mail.outbox), 1) |
| 183 |
message = mail.outbox[0].message() |
| 184 |
self.assertEqual(len(message.get_payload()), 2) |
| 185 |
self.assertTrue(message.is_multipart()) |
| 186 |
self.assertEqual(message.get_payload(0).get_content_type(), "text/plain") |
| 187 |
self.assertEqual(message.get_payload(1).get_content_type(), "text/html") |
| 188 |
self.assertNotIn("<html>", message.get_payload(0).get_payload()) |
| 189 |
self.assertIn("<html>", message.get_payload(1).get_payload()) |
| 190 |
|
| 191 |
def test_email_found_custom_from(self): |
| 192 |
""" |
| 193 |
Email is sent if a valid email address is provided for password reset |
| 194 |
when a custom from_email is provided. |
| 195 |
""" |
| 196 |
response = self.client.post( |
| 197 |
"/password_reset_from_email/", {"email": "[email protected]"} |
| 198 |
) |
| 199 |
self.assertEqual(response.status_code, 302) |
| 200 |
self.assertEqual(len(mail.outbox), 1) |
| 201 |
self.assertEqual("[email protected]", mail.outbox[0].from_email) |
| 202 |
|
| 203 |
# Skip any 500 handler action (like sending more mail...) |
| 204 |
@override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) |
| 205 |
def test_poisoned_http_host(self): |
| 206 |
"Poisoned HTTP_HOST headers can't be used for reset emails" |
| 207 |
# This attack is based on the way browsers handle URLs. The colon |
| 208 |
# should be used to separate the port, but if the URL contains an @, |
| 209 |
# the colon is interpreted as part of a username for login purposes, |
| 210 |
# making 'evil.com' the request domain. Since HTTP_HOST is used to |
| 211 |
# produce a meaningful reset URL, we need to be certain that the |
| 212 |
# HTTP_HOST header isn't poisoned. This is done as a check when get_host() |
| 213 |
# is invoked, but we check here as a practical consequence. |
| 214 |
with self.assertLogs("django.security.DisallowedHost", "ERROR"): |
| 215 |
response = self.client.post( |
| 216 |
"/password_reset/", |
| 217 |
{"email": "[email protected]"}, |
| 218 |
headers={"host": "www.example:[email protected]"}, |
| 219 |
) |
| 220 |
self.assertEqual(response.status_code, 400) |
| 221 |
self.assertEqual(len(mail.outbox), 0) |
| 222 |
|
| 223 |
# Skip any 500 handler action (like sending more mail...) |
| 224 |
@override_settings(DEBUG_PROPAGATE_EXCEPTIONS=True) |
| 225 |
def test_poisoned_http_host_admin_site(self): |
| 226 |
"Poisoned HTTP_HOST headers can't be used for reset emails on admin views" |
| 227 |
with self.assertLogs("django.security.DisallowedHost", "ERROR"): |
| 228 |
response = self.client.post( |
| 229 |
"/admin_password_reset/", |
| 230 |
{"email": "[email protected]"}, |
| 231 |
headers={"host": "www.example:[email protected]"}, |
| 232 |
) |
| 233 |
self.assertEqual(response.status_code, 400) |
| 234 |
self.assertEqual(len(mail.outbox), 0) |
| 235 |
|
| 236 |
def _test_confirm_start(self): |
| 237 |
# Start by creating the email |
| 238 |
self.client.post("/password_reset/", {"email": "[email protected]"}) |
| 239 |
self.assertEqual(len(mail.outbox), 1) |
| 240 |
return self._read_signup_email(mail.outbox[0]) |
| 241 |
|
| 242 |
def _read_signup_email(self, email): |
| 243 |
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) |
| 244 |
self.assertIsNotNone(urlmatch, "No URL found in sent email") |
| 245 |
return urlmatch[0], urlmatch[1] |
| 246 |
|
| 247 |
def test_confirm_valid(self): |
| 248 |
url, path = self._test_confirm_start() |
| 249 |
response = self.client.get(path) |
| 250 |
# redirect to a 'complete' page: |
| 251 |
self.assertContains(response, "Please enter your new password") |
| 252 |
|
| 253 |
def test_confirm_invalid(self): |
| 254 |
url, path = self._test_confirm_start() |
| 255 |
# Let's munge the token in the path, but keep the same length, |
| 256 |
# in case the URLconf will reject a different length. |
| 257 |
path = path[:-5] + ("0" * 4) + path[-1] |
| 258 |
|
| 259 |
response = self.client.get(path) |
| 260 |
self.assertContains(response, "The password reset link was invalid") |
| 261 |
|
| 262 |
def test_confirm_invalid_user(self): |
| 263 |
# A nonexistent user returns a 200 response, not a 404. |
| 264 |
response = self.client.get("/reset/123456/1-1/") |
| 265 |
self.assertContains(response, "The password reset link was invalid") |
| 266 |
|
| 267 |
def test_confirm_overflow_user(self): |
| 268 |
# A base36 user id that overflows int returns a 200 response. |
| 269 |
response = self.client.get("/reset/zzzzzzzzzzzzz/1-1/") |
| 270 |
self.assertContains(response, "The password reset link was invalid") |
| 271 |
|
| 272 |
def test_confirm_invalid_post(self): |
| 273 |
# Same as test_confirm_invalid, but trying to do a POST instead. |
| 274 |
url, path = self._test_confirm_start() |
| 275 |
path = path[:-5] + ("0" * 4) + path[-1] |
| 276 |
|
| 277 |
self.client.post( |
| 278 |
path, |
| 279 |
{ |
| 280 |
"new_password1": "anewpassword", |
| 281 |
"new_password2": " anewpassword", |
| 282 |
}, |
| 283 |
) |
| 284 |
# Check the password has not been changed |
| 285 |
u = User.objects.get(email="[email protected]") |
| 286 |
self.assertTrue(not u.check_password("anewpassword")) |
| 287 |
|
| 288 |
def test_confirm_invalid_hash(self): |
| 289 |
"""A POST with an invalid token is rejected.""" |
| 290 |
u = User.objects.get(email="[email protected]") |
| 291 |
original_password = u.password |
| 292 |
url, path = self._test_confirm_start() |
| 293 |
path_parts = path.split("-") |
| 294 |
path_parts[-1] = ("0") * 20 + "/" |
| 295 |
path = "-".join(path_parts) |
| 296 |
|
| 297 |
response = self.client.post( |
| 298 |
path, |
| 299 |
{ |
| 300 |
"new_password1": "anewpassword", |
| 301 |
"new_password2": "anewpassword", |
| 302 |
}, |
| 303 |
) |
| 304 |
self.assertIs(response.context["validlink"], False) |
| 305 |
u.refresh_from_db() |
| 306 |
self.assertEqual(original_password, u.password) # password hasn't changed |
| 307 |
|
| 308 |
def test_confirm_complete(self): |
| 309 |
url, path = self._test_confirm_start() |
| 310 |
response = self.client.post( |
| 311 |
path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} |
| 312 |
) |
| 313 |
# Check the password has been changed |
| 314 |
u = User.objects.get(email="[email protected]") |
| 315 |
self.assertTrue(u.check_password("anewpassword")) |
| 316 |
# The reset token is deleted from the session. |
| 317 |
self.assertNotIn(INTERNAL_RESET_SESSION_TOKEN, self.client.session) |
| 318 |
|
| 319 |
# Check we can't use the link again |
| 320 |
response = self.client.get(path) |
| 321 |
self.assertContains(response, "The password reset link was invalid") |
| 322 |
|
| 323 |
def test_confirm_different_passwords(self): |
| 324 |
url, path = self._test_confirm_start() |
| 325 |
response = self.client.post( |
| 326 |
path, {"new_password1": "anewpassword", "new_password2": "x"} |
| 327 |
) |
| 328 |
self.assertFormError( |
| 329 |
response, SetPasswordForm.error_messages["password_mismatch"] |
| 330 |
) |
| 331 |
|
| 332 |
def test_reset_redirect_default(self): |
| 333 |
response = self.client.post( |
| 334 |
"/password_reset/", {"email": "[email protected]"} |
| 335 |
) |
| 336 |
self.assertRedirects( |
| 337 |
response, "/password_reset/done/", fetch_redirect_response=False |
| 338 |
) |
| 339 |
|
| 340 |
def test_reset_custom_redirect(self): |
| 341 |
response = self.client.post( |
| 342 |
"/password_reset/custom_redirect/", {"email": "[email protected]"} |
| 343 |
) |
| 344 |
self.assertRedirects(response, "/custom/", fetch_redirect_response=False) |
| 345 |
|
| 346 |
def test_reset_custom_redirect_named(self): |
| 347 |
response = self.client.post( |
| 348 |
"/password_reset/custom_redirect/named/", |
| 349 |
{"email": "[email protected]"}, |
| 350 |
) |
| 351 |
self.assertRedirects( |
| 352 |
response, "/password_reset/", fetch_redirect_response=False |
| 353 |
) |
| 354 |
|
| 355 |
def test_confirm_redirect_default(self): |
| 356 |
url, path = self._test_confirm_start() |
| 357 |
response = self.client.post( |
| 358 |
path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} |
| 359 |
) |
| 360 |
self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) |
| 361 |
|
| 362 |
def test_confirm_redirect_custom(self): |
| 363 |
url, path = self._test_confirm_start() |
| 364 |
path = path.replace("/reset/", "/reset/custom/") |
| 365 |
response = self.client.post( |
| 366 |
path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} |
| 367 |
) |
| 368 |
self.assertRedirects(response, "/custom/", fetch_redirect_response=False) |
| 369 |
|
| 370 |
def test_confirm_redirect_custom_named(self): |
| 371 |
url, path = self._test_confirm_start() |
| 372 |
path = path.replace("/reset/", "/reset/custom/named/") |
| 373 |
response = self.client.post( |
| 374 |
path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} |
| 375 |
) |
| 376 |
self.assertRedirects( |
| 377 |
response, "/password_reset/", fetch_redirect_response=False |
| 378 |
) |
| 379 |
|
| 380 |
def test_confirm_custom_reset_url_token(self): |
| 381 |
url, path = self._test_confirm_start() |
| 382 |
path = path.replace("/reset/", "/reset/custom/token/") |
| 383 |
self.client.reset_url_token = "set-passwordcustom" |
| 384 |
response = self.client.post( |
| 385 |
path, |
| 386 |
{"new_password1": "anewpassword", "new_password2": "anewpassword"}, |
| 387 |
) |
| 388 |
self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) |
| 389 |
|
| 390 |
def test_confirm_login_post_reset(self): |
| 391 |
url, path = self._test_confirm_start() |
| 392 |
path = path.replace("/reset/", "/reset/post_reset_login/") |
| 393 |
response = self.client.post( |
| 394 |
path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} |
| 395 |
) |
| 396 |
self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) |
| 397 |
self.assertIn(SESSION_KEY, self.client.session) |
| 398 |
|
| 399 |
@override_settings( |
| 400 |
AUTHENTICATION_BACKENDS=[ |
| 401 |
"django.contrib.auth.backends.ModelBackend", |
| 402 |
"django.contrib.auth.backends.AllowAllUsersModelBackend", |
| 403 |
] |
| 404 |
) |
| 405 |
def test_confirm_login_post_reset_custom_backend(self): |
| 406 |
# This backend is specified in the URL pattern. |
| 407 |
backend = "django.contrib.auth.backends.AllowAllUsersModelBackend" |
| 408 |
url, path = self._test_confirm_start() |
| 409 |
path = path.replace("/reset/", "/reset/post_reset_login_custom_backend/") |
| 410 |
response = self.client.post( |
| 411 |
path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} |
| 412 |
) |
| 413 |
self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) |
| 414 |
self.assertIn(SESSION_KEY, self.client.session) |
| 415 |
self.assertEqual(self.client.session[BACKEND_SESSION_KEY], backend) |
| 416 |
|
| 417 |
def test_confirm_login_post_reset_already_logged_in(self): |
| 418 |
url, path = self._test_confirm_start() |
| 419 |
path = path.replace("/reset/", "/reset/post_reset_login/") |
| 420 |
self.login() |
| 421 |
response = self.client.post( |
| 422 |
path, {"new_password1": "anewpassword", "new_password2": "anewpassword"} |
| 423 |
) |
| 424 |
self.assertRedirects(response, "/reset/done/", fetch_redirect_response=False) |
| 425 |
self.assertIn(SESSION_KEY, self.client.session) |
| 426 |
|
| 427 |
def test_confirm_display_user_from_form(self): |
| 428 |
url, path = self._test_confirm_start() |
| 429 |
response = self.client.get(path) |
| 430 |
# The password_reset_confirm() view passes the user object to the |
| 431 |
# SetPasswordForm``, even on GET requests (#16919). For this test, |
| 432 |
# {{ form.user }}`` is rendered in the template |
| 433 |
# registration/password_reset_confirm.html. |
| 434 |
username = User.objects.get(email="[email protected]").username |
| 435 |
self.assertContains(response, "Hello, %s." % username) |
| 436 |
# However, the view should NOT pass any user object on a form if the |
| 437 |
# password reset link was invalid. |
| 438 |
response = self.client.get("/reset/zzzzzzzzzzzzz/1-1/") |
| 439 |
self.assertContains(response, "Hello, .") |
| 440 |
|
| 441 |
def test_confirm_link_redirects_to_set_password_page(self): |
| 442 |
url, path = self._test_confirm_start() |
| 443 |
# Don't use PasswordResetConfirmClient (self.client) here which |
| 444 |
# automatically fetches the redirect page. |
| 445 |
client = Client() |
| 446 |
response = client.get(path) |
| 447 |
token = response.resolver_match.kwargs["token"] |
| 448 |
uuidb64 = response.resolver_match.kwargs["uidb64"] |
| 449 |
self.assertRedirects(response, "/reset/%s/set-password/" % uuidb64) |
| 450 |
self.assertEqual(client.session["_password_reset_token"], token) |
| 451 |
|
| 452 |
def test_confirm_custom_reset_url_token_link_redirects_to_set_password_page(self): |
| 453 |
url, path = self._test_confirm_start() |
| 454 |
path = path.replace("/reset/", "/reset/custom/token/") |
| 455 |
client = Client() |
| 456 |
response = client.get(path) |
| 457 |
token = response.resolver_match.kwargs["token"] |
| 458 |
uuidb64 = response.resolver_match.kwargs["uidb64"] |
| 459 |
self.assertRedirects( |
| 460 |
response, "/reset/custom/token/%s/set-passwordcustom/" % uuidb64 |
| 461 |
) |
| 462 |
self.assertEqual(client.session["_password_reset_token"], token) |
| 463 |
|
| 464 |
def test_invalid_link_if_going_directly_to_the_final_reset_password_url(self): |
| 465 |
url, path = self._test_confirm_start() |
| 466 |
_, uuidb64, _ = path.strip("/").split("/") |
| 467 |
response = Client().get("/reset/%s/set-password/" % uuidb64) |
| 468 |
self.assertContains(response, "The password reset link was invalid") |
| 469 |
|
| 470 |
def test_missing_kwargs(self): |
| 471 |
msg = "The URL path must contain 'uidb64' and 'token' parameters." |
| 472 |
with self.assertRaisesMessage(ImproperlyConfigured, msg): |
| 473 |
self.client.get("/reset/missing_parameters/") |
| 474 |
|
| 475 |
@modify_settings( |
| 476 |
MIDDLEWARE={"append": "django.contrib.auth.middleware.LoginRequiredMiddleware"} |
| 477 |
) |
| 478 |
def test_access_under_login_required_middleware(self): |
| 479 |
reset_urls = [ |
| 480 |
reverse("password_reset"), |
| 481 |
reverse("password_reset_done"), |
| 482 |
reverse("password_reset_confirm", kwargs={"uidb64": "abc", "token": "def"}), |
| 483 |
reverse("password_reset_complete"), |
| 484 |
] |
| 485 |
|
| 486 |
for url in reset_urls: |
| 487 |
with self.subTest(url=url): |
| 488 |
response = self.client.get(url) |
| 489 |
self.assertEqual(response.status_code, 200) |
| 490 |
|
| 491 |
response = self.client.post( |
| 492 |
"/password_reset/", {"email": "[email protected]"} |
| 493 |
) |
| 494 |
self.assertRedirects( |
| 495 |
response, "/password_reset/done/", fetch_redirect_response=False |
| 496 |
) |
| 497 |
|
| 498 |
|
| 499 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") |
| 500 |
class CustomUserPasswordResetTest(AuthViewsTestCase): |
| 501 |
user_email = "[email protected]" |
| 502 |
|
| 503 |
@classmethod |
| 504 |
def setUpTestData(cls): |
| 505 |
cls.u1 = CustomUser.custom_objects.create( |
| 506 |
email="[email protected]", |
| 507 |
date_of_birth=datetime.date(1976, 11, 8), |
| 508 |
) |
| 509 |
cls.u1.set_password("password") |
| 510 |
cls.u1.save() |
| 511 |
|
| 512 |
def setUp(self): |
| 513 |
self.client = PasswordResetConfirmClient() |
| 514 |
|
| 515 |
def _test_confirm_start(self): |
| 516 |
# Start by creating the email |
| 517 |
response = self.client.post("/password_reset/", {"email": self.user_email}) |
| 518 |
self.assertEqual(response.status_code, 302) |
| 519 |
self.assertEqual(len(mail.outbox), 1) |
| 520 |
return self._read_signup_email(mail.outbox[0]) |
| 521 |
|
| 522 |
def _read_signup_email(self, email): |
| 523 |
urlmatch = re.search(r"https?://[^/]*(/.*reset/\S*)", email.body) |
| 524 |
self.assertIsNotNone(urlmatch, "No URL found in sent email") |
| 525 |
return urlmatch[0], urlmatch[1] |
| 526 |
|
| 527 |
def test_confirm_valid_custom_user(self): |
| 528 |
url, path = self._test_confirm_start() |
| 529 |
response = self.client.get(path) |
| 530 |
# redirect to a 'complete' page: |
| 531 |
self.assertContains(response, "Please enter your new password") |
| 532 |
# then submit a new password |
| 533 |
response = self.client.post( |
| 534 |
path, |
| 535 |
{ |
| 536 |
"new_password1": "anewpassword", |
| 537 |
"new_password2": "anewpassword", |
| 538 |
}, |
| 539 |
) |
| 540 |
self.assertRedirects(response, "/reset/done/") |
| 541 |
|
| 542 |
|
| 543 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserCompositePrimaryKey") |
| 544 |
class CustomUserCompositePrimaryKeyPasswordResetTest(CustomUserPasswordResetTest): |
| 545 |
@classmethod |
| 546 |
def setUpTestData(cls): |
| 547 |
cls.u1 = CustomUserCompositePrimaryKey.custom_objects.create( |
| 548 |
email="[email protected]", |
| 549 |
date_of_birth=datetime.date(1976, 11, 8), |
| 550 |
) |
| 551 |
cls.u1.set_password("password") |
| 552 |
cls.u1.save() |
| 553 |
|
| 554 |
|
| 555 |
@override_settings(AUTH_USER_MODEL="auth_tests.UUIDUser") |
| 556 |
class UUIDUserPasswordResetTest(CustomUserPasswordResetTest): |
| 557 |
def _test_confirm_start(self): |
| 558 |
# instead of fixture |
| 559 |
UUIDUser.objects.create_user( |
| 560 |
email=self.user_email, |
| 561 |
username="foo", |
| 562 |
password="foo", |
| 563 |
) |
| 564 |
return super()._test_confirm_start() |
| 565 |
|
| 566 |
def test_confirm_invalid_uuid(self): |
| 567 |
"""A uidb64 that decodes to a non-UUID doesn't crash.""" |
| 568 |
_, path = self._test_confirm_start() |
| 569 |
invalid_uidb64 = urlsafe_base64_encode(b"INVALID_UUID") |
| 570 |
first, _uuidb64_, second = path.strip("/").split("/") |
| 571 |
response = self.client.get( |
| 572 |
"/" + "/".join((first, invalid_uidb64, second)) + "/" |
| 573 |
) |
| 574 |
self.assertContains(response, "The password reset link was invalid") |
| 575 |
|
| 576 |
|
| 577 |
class ChangePasswordTest(AuthViewsTestCase): |
| 578 |
def fail_login(self): |
| 579 |
response = self.client.post( |
| 580 |
"/login/", |
| 581 |
{ |
| 582 |
"username": "testclient", |
| 583 |
"password": "password", |
| 584 |
}, |
| 585 |
) |
| 586 |
self.assertFormError( |
| 587 |
response, |
| 588 |
AuthenticationForm.error_messages["invalid_login"] |
| 589 |
% {"username": User._meta.get_field("username").verbose_name}, |
| 590 |
) |
| 591 |
|
| 592 |
def logout(self): |
| 593 |
self.client.post("/logout/") |
| 594 |
|
| 595 |
def test_password_change_fails_with_invalid_old_password(self): |
| 596 |
self.login() |
| 597 |
response = self.client.post( |
| 598 |
"/password_change/", |
| 599 |
{ |
| 600 |
"old_password": "donuts", |
| 601 |
"new_password1": "password1", |
| 602 |
"new_password2": "password1", |
| 603 |
}, |
| 604 |
) |
| 605 |
self.assertFormError( |
| 606 |
response, PasswordChangeForm.error_messages["password_incorrect"] |
| 607 |
) |
| 608 |
|
| 609 |
def test_password_change_fails_with_mismatched_passwords(self): |
| 610 |
self.login() |
| 611 |
response = self.client.post( |
| 612 |
"/password_change/", |
| 613 |
{ |
| 614 |
"old_password": "password", |
| 615 |
"new_password1": "password1", |
| 616 |
"new_password2": "donuts", |
| 617 |
}, |
| 618 |
) |
| 619 |
self.assertFormError( |
| 620 |
response, SetPasswordForm.error_messages["password_mismatch"] |
| 621 |
) |
| 622 |
|
| 623 |
def test_password_change_succeeds(self): |
| 624 |
self.login() |
| 625 |
self.client.post( |
| 626 |
"/password_change/", |
| 627 |
{ |
| 628 |
"old_password": "password", |
| 629 |
"new_password1": "password1", |
| 630 |
"new_password2": "password1", |
| 631 |
}, |
| 632 |
) |
| 633 |
self.fail_login() |
| 634 |
self.login(password="password1") |
| 635 |
|
| 636 |
def test_password_change_done_succeeds(self): |
| 637 |
self.login() |
| 638 |
response = self.client.post( |
| 639 |
"/password_change/", |
| 640 |
{ |
| 641 |
"old_password": "password", |
| 642 |
"new_password1": "password1", |
| 643 |
"new_password2": "password1", |
| 644 |
}, |
| 645 |
) |
| 646 |
self.assertRedirects( |
| 647 |
response, "/password_change/done/", fetch_redirect_response=False |
| 648 |
) |
| 649 |
|
| 650 |
@override_settings(LOGIN_URL="/login/") |
| 651 |
def test_password_change_done_fails(self): |
| 652 |
response = self.client.get("/password_change/done/") |
| 653 |
self.assertRedirects( |
| 654 |
response, |
| 655 |
"/login/?next=/password_change/done/", |
| 656 |
fetch_redirect_response=False, |
| 657 |
) |
| 658 |
|
| 659 |
def test_password_change_redirect_default(self): |
| 660 |
self.login() |
| 661 |
response = self.client.post( |
| 662 |
"/password_change/", |
| 663 |
{ |
| 664 |
"old_password": "password", |
| 665 |
"new_password1": "password1", |
| 666 |
"new_password2": "password1", |
| 667 |
}, |
| 668 |
) |
| 669 |
self.assertRedirects( |
| 670 |
response, "/password_change/done/", fetch_redirect_response=False |
| 671 |
) |
| 672 |
|
| 673 |
def test_password_change_redirect_custom(self): |
| 674 |
self.login() |
| 675 |
response = self.client.post( |
| 676 |
"/password_change/custom/", |
| 677 |
{ |
| 678 |
"old_password": "password", |
| 679 |
"new_password1": "password1", |
| 680 |
"new_password2": "password1", |
| 681 |
}, |
| 682 |
) |
| 683 |
self.assertRedirects(response, "/custom/", fetch_redirect_response=False) |
| 684 |
|
| 685 |
def test_password_change_redirect_custom_named(self): |
| 686 |
self.login() |
| 687 |
response = self.client.post( |
| 688 |
"/password_change/custom/named/", |
| 689 |
{ |
| 690 |
"old_password": "password", |
| 691 |
"new_password1": "password1", |
| 692 |
"new_password2": "password1", |
| 693 |
}, |
| 694 |
) |
| 695 |
self.assertRedirects( |
| 696 |
response, "/password_reset/", fetch_redirect_response=False |
| 697 |
) |
| 698 |
|
| 699 |
@modify_settings( |
| 700 |
MIDDLEWARE={"append": "django.contrib.auth.middleware.LoginRequiredMiddleware"} |
| 701 |
) |
| 702 |
def test_access_under_login_required_middleware(self): |
| 703 |
response = self.client.post( |
| 704 |
"/password_change/", |
| 705 |
{ |
| 706 |
"old_password": "password", |
| 707 |
"new_password1": "password1", |
| 708 |
"new_password2": "password1", |
| 709 |
}, |
| 710 |
) |
| 711 |
self.assertRedirects( |
| 712 |
response, |
| 713 |
settings.LOGIN_URL + "?next=/password_change/", |
| 714 |
fetch_redirect_response=False, |
| 715 |
) |
| 716 |
|
| 717 |
self.login() |
| 718 |
|
| 719 |
response = self.client.post( |
| 720 |
"/password_change/", |
| 721 |
{ |
| 722 |
"old_password": "password", |
| 723 |
"new_password1": "password1", |
| 724 |
"new_password2": "password1", |
| 725 |
}, |
| 726 |
) |
| 727 |
self.assertRedirects( |
| 728 |
response, "/password_change/done/", fetch_redirect_response=False |
| 729 |
) |
| 730 |
|
| 731 |
|
| 732 |
class SessionAuthenticationTests(AuthViewsTestCase): |
| 733 |
def test_user_password_change_updates_session(self): |
| 734 |
""" |
| 735 |
#21649 - Ensure contrib.auth.views.password_change updates the user's |
| 736 |
session auth hash after a password change so the session isn't logged out. |
| 737 |
""" |
| 738 |
self.login() |
| 739 |
original_session_key = self.client.session.session_key |
| 740 |
response = self.client.post( |
| 741 |
"/password_change/", |
| 742 |
{ |
| 743 |
"old_password": "password", |
| 744 |
"new_password1": "password1", |
| 745 |
"new_password2": "password1", |
| 746 |
}, |
| 747 |
) |
| 748 |
# if the hash isn't updated, retrieving the redirection page will fail. |
| 749 |
self.assertRedirects(response, "/password_change/done/") |
| 750 |
# The session key is rotated. |
| 751 |
self.assertNotEqual(original_session_key, self.client.session.session_key) |
| 752 |
|
| 753 |
|
| 754 |
class LoginTest(AuthViewsTestCase): |
| 755 |
def test_current_site_in_context_after_login(self): |
| 756 |
response = self.client.get(reverse("login")) |
| 757 |
self.assertEqual(response.status_code, 200) |
| 758 |
if apps.is_installed("django.contrib.sites"): |
| 759 |
Site = apps.get_model("sites.Site") |
| 760 |
site = Site.objects.get_current() |
| 761 |
self.assertEqual(response.context["site"], site) |
| 762 |
self.assertEqual(response.context["site_name"], site.name) |
| 763 |
else: |
| 764 |
self.assertIsInstance(response.context["site"], RequestSite) |
| 765 |
self.assertIsInstance(response.context["form"], AuthenticationForm) |
| 766 |
|
| 767 |
def test_security_check(self): |
| 768 |
login_url = reverse("login") |
| 769 |
|
| 770 |
# These URLs should not pass the security check. |
| 771 |
bad_urls = ( |
| 772 |
"http://example.com", |
| 773 |
"http:///example.com", |
| 774 |
"https://example.com", |
| 775 |
"ftp://example.com", |
| 776 |
"///example.com", |
| 777 |
"//example.com", |
| 778 |
'javascript:alert("XSS")', |
| 779 |
) |
| 780 |
for bad_url in bad_urls: |
| 781 |
with self.subTest(bad_url=bad_url): |
| 782 |
nasty_url = "%(url)s?%(next)s=%(bad_url)s" % { |
| 783 |
"url": login_url, |
| 784 |
"next": REDIRECT_FIELD_NAME, |
| 785 |
"bad_url": quote(bad_url), |
| 786 |
} |
| 787 |
response = self.client.post( |
| 788 |
nasty_url, |
| 789 |
{ |
| 790 |
"username": "testclient", |
| 791 |
"password": "password", |
| 792 |
}, |
| 793 |
) |
| 794 |
self.assertEqual(response.status_code, 302) |
| 795 |
self.assertNotIn( |
| 796 |
bad_url, response.url, "%s should be blocked" % bad_url |
| 797 |
) |
| 798 |
|
| 799 |
# These URLs should pass the security check. |
| 800 |
good_urls = ( |
| 801 |
"/view/?param=http://example.com", |
| 802 |
"/view/?param=https://example.com", |
| 803 |
"/view?param=ftp://example.com", |
| 804 |
"view/?param=//example.com", |
| 805 |
"https://testserver/", |
| 806 |
"HTTPS://testserver/", |
| 807 |
"//testserver/", |
| 808 |
"/url%20with%20spaces/", |
| 809 |
) |
| 810 |
for good_url in good_urls: |
| 811 |
with self.subTest(good_url=good_url): |
| 812 |
safe_url = "%(url)s?%(next)s=%(good_url)s" % { |
| 813 |
"url": login_url, |
| 814 |
"next": REDIRECT_FIELD_NAME, |
| 815 |
"good_url": quote(good_url), |
| 816 |
} |
| 817 |
response = self.client.post( |
| 818 |
safe_url, |
| 819 |
{ |
| 820 |
"username": "testclient", |
| 821 |
"password": "password", |
| 822 |
}, |
| 823 |
) |
| 824 |
self.assertEqual(response.status_code, 302) |
| 825 |
self.assertIn(good_url, response.url, "%s should be allowed" % good_url) |
| 826 |
|
| 827 |
def test_security_check_https(self): |
| 828 |
login_url = reverse("login") |
| 829 |
non_https_next_url = "http://testserver/path" |
| 830 |
not_secured_url = "%(url)s?%(next)s=%(next_url)s" % { |
| 831 |
"url": login_url, |
| 832 |
"next": REDIRECT_FIELD_NAME, |
| 833 |
"next_url": quote(non_https_next_url), |
| 834 |
} |
| 835 |
post_data = { |
| 836 |
"username": "testclient", |
| 837 |
"password": "password", |
| 838 |
} |
| 839 |
response = self.client.post(not_secured_url, post_data, secure=True) |
| 840 |
self.assertEqual(response.status_code, 302) |
| 841 |
self.assertNotEqual(response.url, non_https_next_url) |
| 842 |
self.assertEqual(response.url, settings.LOGIN_REDIRECT_URL) |
| 843 |
|
| 844 |
def test_login_form_contains_request(self): |
| 845 |
# The custom authentication form for this login requires a request to |
| 846 |
# initialize it. |
| 847 |
response = self.client.post( |
| 848 |
"/custom_request_auth_login/", |
| 849 |
{ |
| 850 |
"username": "testclient", |
| 851 |
"password": "password", |
| 852 |
}, |
| 853 |
) |
| 854 |
# The login was successful. |
| 855 |
self.assertRedirects( |
| 856 |
response, settings.LOGIN_REDIRECT_URL, fetch_redirect_response=False |
| 857 |
) |
| 858 |
|
| 859 |
def test_login_csrf_rotate(self): |
| 860 |
""" |
| 861 |
Makes sure that a login rotates the currently-used CSRF token. |
| 862 |
""" |
| 863 |
|
| 864 |
def get_response(request): |
| 865 |
return HttpResponse() |
| 866 |
|
| 867 |
# Do a GET to establish a CSRF token |
| 868 |
# The test client isn't used here as it's a test for middleware. |
| 869 |
req = HttpRequest() |
| 870 |
CsrfViewMiddleware(get_response).process_view(req, LoginView.as_view(), (), {}) |
| 871 |
# get_token() triggers CSRF token inclusion in the response |
| 872 |
get_token(req) |
| 873 |
resp = CsrfViewMiddleware(LoginView.as_view())(req) |
| 874 |
csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None) |
| 875 |
token1 = csrf_cookie.coded_value |
| 876 |
|
| 877 |
# Prepare the POST request |
| 878 |
req = HttpRequest() |
| 879 |
req.COOKIES[settings.CSRF_COOKIE_NAME] = token1 |
| 880 |
req.method = "POST" |
| 881 |
req.POST = { |
| 882 |
"username": "testclient", |
| 883 |
"password": "password", |
| 884 |
"csrfmiddlewaretoken": token1, |
| 885 |
} |
| 886 |
|
| 887 |
# Use POST request to log in |
| 888 |
SessionMiddleware(get_response).process_request(req) |
| 889 |
CsrfViewMiddleware(get_response).process_view(req, LoginView.as_view(), (), {}) |
| 890 |
req.META["SERVER_NAME"] = ( |
| 891 |
"testserver" # Required to have redirect work in login view |
| 892 |
) |
| 893 |
req.META["SERVER_PORT"] = 80 |
| 894 |
resp = CsrfViewMiddleware(LoginView.as_view())(req) |
| 895 |
csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None) |
| 896 |
token2 = csrf_cookie.coded_value |
| 897 |
|
| 898 |
# Check the CSRF token switched |
| 899 |
self.assertNotEqual(token1, token2) |
| 900 |
|
| 901 |
def test_session_key_flushed_on_login(self): |
| 902 |
""" |
| 903 |
To avoid reusing another user's session, ensure a new, empty session is |
| 904 |
created if the existing session corresponds to a different authenticated |
| 905 |
user. |
| 906 |
""" |
| 907 |
self.login() |
| 908 |
original_session_key = self.client.session.session_key |
| 909 |
|
| 910 |
self.login(username="staff") |
| 911 |
self.assertNotEqual(original_session_key, self.client.session.session_key) |
| 912 |
|
| 913 |
def test_session_key_flushed_on_login_after_password_change(self): |
| 914 |
""" |
| 915 |
As above, but same user logging in after a password change. |
| 916 |
""" |
| 917 |
self.login() |
| 918 |
original_session_key = self.client.session.session_key |
| 919 |
|
| 920 |
# If no password change, session key should not be flushed. |
| 921 |
self.login() |
| 922 |
self.assertEqual(original_session_key, self.client.session.session_key) |
| 923 |
|
| 924 |
user = User.objects.get(username="testclient") |
| 925 |
user.set_password("foobar") |
| 926 |
user.save() |
| 927 |
|
| 928 |
self.login(password="foobar") |
| 929 |
self.assertNotEqual(original_session_key, self.client.session.session_key) |
| 930 |
|
| 931 |
def test_login_session_without_hash_session_key(self): |
| 932 |
""" |
| 933 |
Session without django.contrib.auth.HASH_SESSION_KEY should login |
| 934 |
without an exception. |
| 935 |
""" |
| 936 |
user = User.objects.get(username="testclient") |
| 937 |
engine = import_module(settings.SESSION_ENGINE) |
| 938 |
session = engine.SessionStore() |
| 939 |
session[SESSION_KEY] = user.id |
| 940 |
session.save() |
| 941 |
original_session_key = session.session_key |
| 942 |
self.client.cookies[settings.SESSION_COOKIE_NAME] = original_session_key |
| 943 |
|
| 944 |
self.login() |
| 945 |
self.assertNotEqual(original_session_key, self.client.session.session_key) |
| 946 |
|
| 947 |
def test_login_get_default_redirect_url(self): |
| 948 |
response = self.login(url="/login/get_default_redirect_url/") |
| 949 |
self.assertRedirects(response, "/custom/", fetch_redirect_response=False) |
| 950 |
|
| 951 |
def test_login_next_page(self): |
| 952 |
response = self.login(url="/login/next_page/") |
| 953 |
self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) |
| 954 |
|
| 955 |
def test_login_named_next_page_named(self): |
| 956 |
response = self.login(url="/login/next_page/named/") |
| 957 |
self.assertRedirects( |
| 958 |
response, "/password_reset/", fetch_redirect_response=False |
| 959 |
) |
| 960 |
|
| 961 |
@override_settings(LOGIN_REDIRECT_URL="/custom/") |
| 962 |
def test_login_next_page_overrides_login_redirect_url_setting(self): |
| 963 |
response = self.login(url="/login/next_page/") |
| 964 |
self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) |
| 965 |
|
| 966 |
def test_login_redirect_url_overrides_next_page(self): |
| 967 |
response = self.login(url="/login/next_page/?next=/test/") |
| 968 |
self.assertRedirects(response, "/test/", fetch_redirect_response=False) |
| 969 |
|
| 970 |
def test_login_redirect_url_overrides_get_default_redirect_url(self): |
| 971 |
response = self.login(url="/login/get_default_redirect_url/?next=/test/") |
| 972 |
self.assertRedirects(response, "/test/", fetch_redirect_response=False) |
| 973 |
|
| 974 |
@modify_settings( |
| 975 |
MIDDLEWARE={"append": "django.contrib.auth.middleware.LoginRequiredMiddleware"} |
| 976 |
) |
| 977 |
def test_access_under_login_required_middleware(self): |
| 978 |
response = self.client.get(reverse("login")) |
| 979 |
self.assertEqual(response.status_code, 200) |
| 980 |
|
| 981 |
|
| 982 |
class LoginURLSettings(AuthViewsTestCase): |
| 983 |
"""Tests for settings.LOGIN_URL.""" |
| 984 |
|
| 985 |
def assertLoginURLEquals(self, url): |
| 986 |
response = self.client.get("/login_required/") |
| 987 |
self.assertRedirects(response, url, fetch_redirect_response=False) |
| 988 |
|
| 989 |
@override_settings(LOGIN_URL="/login/") |
| 990 |
def test_standard_login_url(self): |
| 991 |
self.assertLoginURLEquals("/login/?next=/login_required/") |
| 992 |
|
| 993 |
@override_settings(LOGIN_URL="login") |
| 994 |
def test_named_login_url(self): |
| 995 |
self.assertLoginURLEquals("/login/?next=/login_required/") |
| 996 |
|
| 997 |
@override_settings(LOGIN_URL="http://remote.example.com/login") |
| 998 |
def test_remote_login_url(self): |
| 999 |
quoted_next = quote("http://testserver/login_required/") |
| 1000 |
expected = "http://remote.example.com/login?next=%s" % quoted_next |
| 1001 |
self.assertLoginURLEquals(expected) |
| 1002 |
|
| 1003 |
@override_settings(LOGIN_URL="https:///login/") |
| 1004 |
def test_https_login_url(self): |
| 1005 |
quoted_next = quote("http://testserver/login_required/") |
| 1006 |
expected = "https:///login/?next=%s" % quoted_next |
| 1007 |
self.assertLoginURLEquals(expected) |
| 1008 |
|
| 1009 |
@override_settings(LOGIN_URL="/login/?pretty=1") |
| 1010 |
def test_login_url_with_querystring(self): |
| 1011 |
self.assertLoginURLEquals("/login/?pretty=1&next=/login_required/") |
| 1012 |
|
| 1013 |
@override_settings(LOGIN_URL="http://remote.example.com/login/?next=/default/") |
| 1014 |
def test_remote_login_url_with_next_querystring(self): |
| 1015 |
quoted_next = quote("http://testserver/login_required/") |
| 1016 |
expected = "http://remote.example.com/login/?next=%s" % quoted_next |
| 1017 |
self.assertLoginURLEquals(expected) |
| 1018 |
|
| 1019 |
@override_settings(LOGIN_URL=reverse_lazy("login")) |
| 1020 |
def test_lazy_login_url(self): |
| 1021 |
self.assertLoginURLEquals("/login/?next=/login_required/") |
| 1022 |
|
| 1023 |
|
| 1024 |
class LoginRedirectUrlTest(AuthViewsTestCase): |
| 1025 |
"""Tests for settings.LOGIN_REDIRECT_URL.""" |
| 1026 |
|
| 1027 |
def assertLoginRedirectURLEqual(self, url): |
| 1028 |
response = self.login() |
| 1029 |
self.assertRedirects(response, url, fetch_redirect_response=False) |
| 1030 |
|
| 1031 |
def test_default(self): |
| 1032 |
self.assertLoginRedirectURLEqual("/accounts/profile/") |
| 1033 |
|
| 1034 |
@override_settings(LOGIN_REDIRECT_URL="/custom/") |
| 1035 |
def test_custom(self): |
| 1036 |
self.assertLoginRedirectURLEqual("/custom/") |
| 1037 |
|
| 1038 |
@override_settings(LOGIN_REDIRECT_URL="password_reset") |
| 1039 |
def test_named(self): |
| 1040 |
self.assertLoginRedirectURLEqual("/password_reset/") |
| 1041 |
|
| 1042 |
@override_settings(LOGIN_REDIRECT_URL="http://remote.example.com/welcome/") |
| 1043 |
def test_remote(self): |
| 1044 |
self.assertLoginRedirectURLEqual("http://remote.example.com/welcome/") |
| 1045 |
|
| 1046 |
|
| 1047 |
class RedirectToLoginTests(AuthViewsTestCase): |
| 1048 |
"""Tests for the redirect_to_login view""" |
| 1049 |
|
| 1050 |
@override_settings(LOGIN_URL=reverse_lazy("login")) |
| 1051 |
def test_redirect_to_login_with_lazy(self): |
| 1052 |
login_redirect_response = redirect_to_login(next="/else/where/") |
| 1053 |
expected = "/login/?next=/else/where/" |
| 1054 |
self.assertEqual(expected, login_redirect_response.url) |
| 1055 |
|
| 1056 |
@override_settings(LOGIN_URL=reverse_lazy("login")) |
| 1057 |
def test_redirect_to_login_with_lazy_and_unicode(self): |
| 1058 |
login_redirect_response = redirect_to_login(next="/else/where/झ/") |
| 1059 |
expected = "/login/?next=/else/where/%E0%A4%9D/" |
| 1060 |
self.assertEqual(expected, login_redirect_response.url) |
| 1061 |
|
| 1062 |
|
| 1063 |
class LogoutThenLoginTests(AuthViewsTestCase): |
| 1064 |
"""Tests for the logout_then_login view""" |
| 1065 |
|
| 1066 |
def confirm_logged_out(self): |
| 1067 |
self.assertNotIn(SESSION_KEY, self.client.session) |
| 1068 |
|
| 1069 |
@override_settings(LOGIN_URL="/login/") |
| 1070 |
def test_default_logout_then_login(self): |
| 1071 |
self.login() |
| 1072 |
req = HttpRequest() |
| 1073 |
req.method = "POST" |
| 1074 |
csrf_token = get_token(req) |
| 1075 |
req.COOKIES[settings.CSRF_COOKIE_NAME] = csrf_token |
| 1076 |
req.POST = {"csrfmiddlewaretoken": csrf_token} |
| 1077 |
req.META["SERVER_NAME"] = "testserver" |
| 1078 |
req.META["SERVER_PORT"] = 80 |
| 1079 |
req.session = self.client.session |
| 1080 |
response = logout_then_login(req) |
| 1081 |
self.confirm_logged_out() |
| 1082 |
self.assertRedirects(response, "/login/", fetch_redirect_response=False) |
| 1083 |
|
| 1084 |
def test_logout_then_login_with_custom_login(self): |
| 1085 |
self.login() |
| 1086 |
req = HttpRequest() |
| 1087 |
req.method = "POST" |
| 1088 |
csrf_token = get_token(req) |
| 1089 |
req.COOKIES[settings.CSRF_COOKIE_NAME] = csrf_token |
| 1090 |
req.POST = {"csrfmiddlewaretoken": csrf_token} |
| 1091 |
req.META["SERVER_NAME"] = "testserver" |
| 1092 |
req.META["SERVER_PORT"] = 80 |
| 1093 |
req.session = self.client.session |
| 1094 |
response = logout_then_login(req, login_url="/custom/") |
| 1095 |
self.confirm_logged_out() |
| 1096 |
self.assertRedirects(response, "/custom/", fetch_redirect_response=False) |
| 1097 |
|
| 1098 |
@override_settings(LOGIN_URL="/login/") |
| 1099 |
def test_default_logout_then_login_get(self): |
| 1100 |
self.login() |
| 1101 |
req = HttpRequest() |
| 1102 |
req.method = "GET" |
| 1103 |
req.META["SERVER_NAME"] = "testserver" |
| 1104 |
req.META["SERVER_PORT"] = 80 |
| 1105 |
req.session = self.client.session |
| 1106 |
response = logout_then_login(req) |
| 1107 |
self.assertEqual(response.status_code, 405) |
| 1108 |
|
| 1109 |
|
| 1110 |
class LoginRedirectAuthenticatedUser(AuthViewsTestCase): |
| 1111 |
dont_redirect_url = "/login/redirect_authenticated_user_default/" |
| 1112 |
do_redirect_url = "/login/redirect_authenticated_user/" |
| 1113 |
|
| 1114 |
def test_default(self): |
| 1115 |
"""Stay on the login page by default.""" |
| 1116 |
self.login() |
| 1117 |
response = self.client.get(self.dont_redirect_url) |
| 1118 |
self.assertEqual(response.status_code, 200) |
| 1119 |
self.assertEqual(response.context["next"], "") |
| 1120 |
|
| 1121 |
def test_guest(self): |
| 1122 |
"""If not logged in, stay on the same page.""" |
| 1123 |
response = self.client.get(self.do_redirect_url) |
| 1124 |
self.assertEqual(response.status_code, 200) |
| 1125 |
|
| 1126 |
def test_redirect(self): |
| 1127 |
"""If logged in, go to default redirected URL.""" |
| 1128 |
self.login() |
| 1129 |
response = self.client.get(self.do_redirect_url) |
| 1130 |
self.assertRedirects( |
| 1131 |
response, "/accounts/profile/", fetch_redirect_response=False |
| 1132 |
) |
| 1133 |
|
| 1134 |
@override_settings(LOGIN_REDIRECT_URL="/custom/") |
| 1135 |
def test_redirect_url(self): |
| 1136 |
"""If logged in, go to custom redirected URL.""" |
| 1137 |
self.login() |
| 1138 |
response = self.client.get(self.do_redirect_url) |
| 1139 |
self.assertRedirects(response, "/custom/", fetch_redirect_response=False) |
| 1140 |
|
| 1141 |
def test_redirect_param(self): |
| 1142 |
"""If next is specified as a GET parameter, go there.""" |
| 1143 |
self.login() |
| 1144 |
url = self.do_redirect_url + "?next=/custom_next/" |
| 1145 |
response = self.client.get(url) |
| 1146 |
self.assertRedirects(response, "/custom_next/", fetch_redirect_response=False) |
| 1147 |
|
| 1148 |
def test_redirect_loop(self): |
| 1149 |
""" |
| 1150 |
Detect a redirect loop if LOGIN_REDIRECT_URL is not correctly set, |
| 1151 |
with and without custom parameters. |
| 1152 |
""" |
| 1153 |
self.login() |
| 1154 |
msg = ( |
| 1155 |
"Redirection loop for authenticated user detected. Check that " |
| 1156 |
"your LOGIN_REDIRECT_URL doesn't point to a login page." |
| 1157 |
) |
| 1158 |
with self.settings(LOGIN_REDIRECT_URL=self.do_redirect_url): |
| 1159 |
with self.assertRaisesMessage(ValueError, msg): |
| 1160 |
self.client.get(self.do_redirect_url) |
| 1161 |
|
| 1162 |
url = self.do_redirect_url + "?bla=2" |
| 1163 |
with self.assertRaisesMessage(ValueError, msg): |
| 1164 |
self.client.get(url) |
| 1165 |
|
| 1166 |
def test_permission_required_not_logged_in(self): |
| 1167 |
# Not logged in ... |
| 1168 |
with self.settings(LOGIN_URL=self.do_redirect_url): |
| 1169 |
# redirected to login. |
| 1170 |
response = self.client.get("/permission_required_redirect/", follow=True) |
| 1171 |
self.assertEqual(response.status_code, 200) |
| 1172 |
# exception raised. |
| 1173 |
response = self.client.get("/permission_required_exception/", follow=True) |
| 1174 |
self.assertEqual(response.status_code, 403) |
| 1175 |
# redirected to login. |
| 1176 |
response = self.client.get( |
| 1177 |
"/login_and_permission_required_exception/", follow=True |
| 1178 |
) |
| 1179 |
self.assertEqual(response.status_code, 200) |
| 1180 |
|
| 1181 |
def test_permission_required_logged_in(self): |
| 1182 |
self.login() |
| 1183 |
# Already logged in... |
| 1184 |
with self.settings(LOGIN_URL=self.do_redirect_url): |
| 1185 |
# redirect loop encountered. |
| 1186 |
with self.assertRaisesMessage( |
| 1187 |
RedirectCycleError, "Redirect loop detected." |
| 1188 |
): |
| 1189 |
self.client.get("/permission_required_redirect/", follow=True) |
| 1190 |
# exception raised. |
| 1191 |
response = self.client.get("/permission_required_exception/", follow=True) |
| 1192 |
self.assertEqual(response.status_code, 403) |
| 1193 |
# exception raised. |
| 1194 |
response = self.client.get( |
| 1195 |
"/login_and_permission_required_exception/", follow=True |
| 1196 |
) |
| 1197 |
self.assertEqual(response.status_code, 403) |
| 1198 |
|
| 1199 |
|
| 1200 |
class LoginSuccessURLAllowedHostsTest(AuthViewsTestCase): |
| 1201 |
def test_success_url_allowed_hosts_same_host(self): |
| 1202 |
response = self.client.post( |
| 1203 |
"/login/allowed_hosts/", |
| 1204 |
{ |
| 1205 |
"username": "testclient", |
| 1206 |
"password": "password", |
| 1207 |
"next": "https://testserver/home", |
| 1208 |
}, |
| 1209 |
) |
| 1210 |
self.assertIn(SESSION_KEY, self.client.session) |
| 1211 |
self.assertRedirects( |
| 1212 |
response, "https://testserver/home", fetch_redirect_response=False |
| 1213 |
) |
| 1214 |
|
| 1215 |
def test_success_url_allowed_hosts_safe_host(self): |
| 1216 |
response = self.client.post( |
| 1217 |
"/login/allowed_hosts/", |
| 1218 |
{ |
| 1219 |
"username": "testclient", |
| 1220 |
"password": "password", |
| 1221 |
"next": "https://otherserver/home", |
| 1222 |
}, |
| 1223 |
) |
| 1224 |
self.assertIn(SESSION_KEY, self.client.session) |
| 1225 |
self.assertRedirects( |
| 1226 |
response, "https://otherserver/home", fetch_redirect_response=False |
| 1227 |
) |
| 1228 |
|
| 1229 |
def test_success_url_allowed_hosts_unsafe_host(self): |
| 1230 |
response = self.client.post( |
| 1231 |
"/login/allowed_hosts/", |
| 1232 |
{ |
| 1233 |
"username": "testclient", |
| 1234 |
"password": "password", |
| 1235 |
"next": "https://evil/home", |
| 1236 |
}, |
| 1237 |
) |
| 1238 |
self.assertIn(SESSION_KEY, self.client.session) |
| 1239 |
self.assertRedirects( |
| 1240 |
response, "/accounts/profile/", fetch_redirect_response=False |
| 1241 |
) |
| 1242 |
|
| 1243 |
|
| 1244 |
class LogoutTest(AuthViewsTestCase): |
| 1245 |
def confirm_logged_out(self): |
| 1246 |
self.assertNotIn(SESSION_KEY, self.client.session) |
| 1247 |
|
| 1248 |
def test_logout_default(self): |
| 1249 |
"Logout without next_page option renders the default template" |
| 1250 |
self.login() |
| 1251 |
response = self.client.post("/logout/") |
| 1252 |
self.assertContains(response, "Logged out") |
| 1253 |
self.confirm_logged_out() |
| 1254 |
|
| 1255 |
def test_logout_with_post(self): |
| 1256 |
self.login() |
| 1257 |
response = self.client.post("/logout/") |
| 1258 |
self.assertContains(response, "Logged out") |
| 1259 |
self.confirm_logged_out() |
| 1260 |
|
| 1261 |
def test_14377(self): |
| 1262 |
# Bug 14377 |
| 1263 |
self.login() |
| 1264 |
response = self.client.post("/logout/") |
| 1265 |
self.assertIn("site", response.context) |
| 1266 |
|
| 1267 |
def test_logout_doesnt_cache(self): |
| 1268 |
""" |
| 1269 |
The logout() view should send "no-cache" headers for reasons described |
| 1270 |
in #25490. |
| 1271 |
""" |
| 1272 |
response = self.client.post("/logout/") |
| 1273 |
self.assertIn("no-store", response.headers["Cache-Control"]) |
| 1274 |
|
| 1275 |
def test_logout_with_overridden_redirect_url(self): |
| 1276 |
# Bug 11223 |
| 1277 |
self.login() |
| 1278 |
response = self.client.post("/logout/next_page/") |
| 1279 |
self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) |
| 1280 |
|
| 1281 |
response = self.client.post("/logout/next_page/?next=/login/") |
| 1282 |
self.assertRedirects(response, "/login/", fetch_redirect_response=False) |
| 1283 |
|
| 1284 |
self.confirm_logged_out() |
| 1285 |
|
| 1286 |
def test_logout_with_next_page_specified(self): |
| 1287 |
"Logout with next_page option given redirects to specified resource" |
| 1288 |
self.login() |
| 1289 |
response = self.client.post("/logout/next_page/") |
| 1290 |
self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) |
| 1291 |
self.confirm_logged_out() |
| 1292 |
|
| 1293 |
def test_logout_with_redirect_argument(self): |
| 1294 |
"Logout with query string redirects to specified resource" |
| 1295 |
self.login() |
| 1296 |
response = self.client.post("/logout/?next=/login/") |
| 1297 |
self.assertRedirects(response, "/login/", fetch_redirect_response=False) |
| 1298 |
self.confirm_logged_out() |
| 1299 |
|
| 1300 |
def test_logout_with_custom_redirect_argument(self): |
| 1301 |
"Logout with custom query string redirects to specified resource" |
| 1302 |
self.login() |
| 1303 |
response = self.client.post("/logout/custom_query/?follow=/somewhere/") |
| 1304 |
self.assertRedirects(response, "/somewhere/", fetch_redirect_response=False) |
| 1305 |
self.confirm_logged_out() |
| 1306 |
|
| 1307 |
def test_logout_with_named_redirect(self): |
| 1308 |
"Logout resolves names or URLs passed as next_page." |
| 1309 |
self.login() |
| 1310 |
response = self.client.post("/logout/next_page/named/") |
| 1311 |
self.assertRedirects( |
| 1312 |
response, "/password_reset/", fetch_redirect_response=False |
| 1313 |
) |
| 1314 |
self.confirm_logged_out() |
| 1315 |
|
| 1316 |
def test_success_url_allowed_hosts_same_host(self): |
| 1317 |
self.login() |
| 1318 |
response = self.client.post("/logout/allowed_hosts/?next=https://testserver/") |
| 1319 |
self.assertRedirects( |
| 1320 |
response, "https://testserver/", fetch_redirect_response=False |
| 1321 |
) |
| 1322 |
self.confirm_logged_out() |
| 1323 |
|
| 1324 |
def test_success_url_allowed_hosts_safe_host(self): |
| 1325 |
self.login() |
| 1326 |
response = self.client.post("/logout/allowed_hosts/?next=https://otherserver/") |
| 1327 |
self.assertRedirects( |
| 1328 |
response, "https://otherserver/", fetch_redirect_response=False |
| 1329 |
) |
| 1330 |
self.confirm_logged_out() |
| 1331 |
|
| 1332 |
def test_success_url_allowed_hosts_unsafe_host(self): |
| 1333 |
self.login() |
| 1334 |
response = self.client.post("/logout/allowed_hosts/?next=https://evil/") |
| 1335 |
self.assertRedirects( |
| 1336 |
response, "/logout/allowed_hosts/", fetch_redirect_response=False |
| 1337 |
) |
| 1338 |
self.confirm_logged_out() |
| 1339 |
|
| 1340 |
def test_security_check(self): |
| 1341 |
logout_url = reverse("logout") |
| 1342 |
|
| 1343 |
# These URLs should not pass the security check. |
| 1344 |
bad_urls = ( |
| 1345 |
"http://example.com", |
| 1346 |
"http:///example.com", |
| 1347 |
"https://example.com", |
| 1348 |
"ftp://example.com", |
| 1349 |
"///example.com", |
| 1350 |
"//example.com", |
| 1351 |
'javascript:alert("XSS")', |
| 1352 |
) |
| 1353 |
for bad_url in bad_urls: |
| 1354 |
with self.subTest(bad_url=bad_url): |
| 1355 |
nasty_url = "%(url)s?%(next)s=%(bad_url)s" % { |
| 1356 |
"url": logout_url, |
| 1357 |
"next": REDIRECT_FIELD_NAME, |
| 1358 |
"bad_url": quote(bad_url), |
| 1359 |
} |
| 1360 |
self.login() |
| 1361 |
response = self.client.post(nasty_url) |
| 1362 |
self.assertEqual(response.status_code, 302) |
| 1363 |
self.assertNotIn( |
| 1364 |
bad_url, response.url, "%s should be blocked" % bad_url |
| 1365 |
) |
| 1366 |
self.confirm_logged_out() |
| 1367 |
|
| 1368 |
# These URLs should pass the security check. |
| 1369 |
good_urls = ( |
| 1370 |
"/view/?param=http://example.com", |
| 1371 |
"/view/?param=https://example.com", |
| 1372 |
"/view?param=ftp://example.com", |
| 1373 |
"view/?param=//example.com", |
| 1374 |
"https://testserver/", |
| 1375 |
"HTTPS://testserver/", |
| 1376 |
"//testserver/", |
| 1377 |
"/url%20with%20spaces/", |
| 1378 |
) |
| 1379 |
for good_url in good_urls: |
| 1380 |
with self.subTest(good_url=good_url): |
| 1381 |
safe_url = "%(url)s?%(next)s=%(good_url)s" % { |
| 1382 |
"url": logout_url, |
| 1383 |
"next": REDIRECT_FIELD_NAME, |
| 1384 |
"good_url": quote(good_url), |
| 1385 |
} |
| 1386 |
self.login() |
| 1387 |
response = self.client.post(safe_url) |
| 1388 |
self.assertEqual(response.status_code, 302) |
| 1389 |
self.assertIn(good_url, response.url, "%s should be allowed" % good_url) |
| 1390 |
self.confirm_logged_out() |
| 1391 |
|
| 1392 |
def test_security_check_https(self): |
| 1393 |
logout_url = reverse("logout") |
| 1394 |
non_https_next_url = "http://testserver/" |
| 1395 |
url = "%(url)s?%(next)s=%(next_url)s" % { |
| 1396 |
"url": logout_url, |
| 1397 |
"next": REDIRECT_FIELD_NAME, |
| 1398 |
"next_url": quote(non_https_next_url), |
| 1399 |
} |
| 1400 |
self.login() |
| 1401 |
response = self.client.post(url, secure=True) |
| 1402 |
self.assertRedirects(response, logout_url, fetch_redirect_response=False) |
| 1403 |
self.confirm_logged_out() |
| 1404 |
|
| 1405 |
def test_logout_preserve_language(self): |
| 1406 |
"""Language is preserved after logout.""" |
| 1407 |
self.login() |
| 1408 |
self.client.post("/setlang/", {"language": "pl"}) |
| 1409 |
self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "pl") |
| 1410 |
self.client.post("/logout/") |
| 1411 |
self.assertEqual(self.client.cookies[settings.LANGUAGE_COOKIE_NAME].value, "pl") |
| 1412 |
|
| 1413 |
@override_settings(LOGOUT_REDIRECT_URL="/custom/") |
| 1414 |
def test_logout_redirect_url_setting(self): |
| 1415 |
self.login() |
| 1416 |
response = self.client.post("/logout/") |
| 1417 |
self.assertRedirects(response, "/custom/", fetch_redirect_response=False) |
| 1418 |
|
| 1419 |
@override_settings(LOGOUT_REDIRECT_URL="/custom/") |
| 1420 |
def test_logout_redirect_url_setting_allowed_hosts_unsafe_host(self): |
| 1421 |
self.login() |
| 1422 |
response = self.client.post("/logout/allowed_hosts/?next=https://evil/") |
| 1423 |
self.assertRedirects(response, "/custom/", fetch_redirect_response=False) |
| 1424 |
|
| 1425 |
@override_settings(LOGOUT_REDIRECT_URL="logout") |
| 1426 |
def test_logout_redirect_url_named_setting(self): |
| 1427 |
self.login() |
| 1428 |
response = self.client.post("/logout/") |
| 1429 |
self.assertContains(response, "Logged out") |
| 1430 |
self.confirm_logged_out() |
| 1431 |
|
| 1432 |
@modify_settings( |
| 1433 |
MIDDLEWARE={"append": "django.contrib.auth.middleware.LoginRequiredMiddleware"} |
| 1434 |
) |
| 1435 |
def test_access_under_login_required_middleware(self): |
| 1436 |
response = self.client.post("/logout/") |
| 1437 |
self.assertRedirects( |
| 1438 |
response, |
| 1439 |
settings.LOGIN_URL + "?next=/logout/", |
| 1440 |
fetch_redirect_response=False, |
| 1441 |
) |
| 1442 |
|
| 1443 |
self.login() |
| 1444 |
|
| 1445 |
response = self.client.post("/logout/") |
| 1446 |
self.assertEqual(response.status_code, 200) |
| 1447 |
|
| 1448 |
|
| 1449 |
def get_perm(Model, perm): |
| 1450 |
ct = ContentType.objects.get_for_model(Model) |
| 1451 |
return Permission.objects.get(content_type=ct, codename=perm) |
| 1452 |
|
| 1453 |
|
| 1454 |
# Redirect in test_user_change_password will fail if session auth hash |
| 1455 |
# isn't updated after password change (#21649) |
| 1456 |
@override_settings( |
| 1457 |
ROOT_URLCONF="auth_tests.urls_admin", |
| 1458 |
PASSWORD_HASHERS=["django.contrib.auth.hashers.MD5PasswordHasher"], |
| 1459 |
) |
| 1460 |
class ChangelistTests(MessagesTestMixin, AuthViewsTestCase): |
| 1461 |
@classmethod |
| 1462 |
def setUpTestData(cls): |
| 1463 |
super().setUpTestData() |
| 1464 |
# Make me a superuser before logging in. |
| 1465 |
User.objects.filter(username="testclient").update( |
| 1466 |
is_staff=True, is_superuser=True |
| 1467 |
) |
| 1468 |
|
| 1469 |
def setUp(self): |
| 1470 |
self.login() |
| 1471 |
# Get the latest last_login value. |
| 1472 |
self.admin = User.objects.get(pk=self.u1.pk) |
| 1473 |
|
| 1474 |
def get_user_data(self, user): |
| 1475 |
return { |
| 1476 |
"username": user.username, |
| 1477 |
"password": user.password, |
| 1478 |
"email": user.email, |
| 1479 |
"is_active": user.is_active, |
| 1480 |
"is_staff": user.is_staff, |
| 1481 |
"is_superuser": user.is_superuser, |
| 1482 |
"last_login_0": user.last_login.strftime("%Y-%m-%d"), |
| 1483 |
"last_login_1": user.last_login.strftime("%H:%M:%S"), |
| 1484 |
"initial-last_login_0": user.last_login.strftime("%Y-%m-%d"), |
| 1485 |
"initial-last_login_1": user.last_login.strftime("%H:%M:%S"), |
| 1486 |
"date_joined_0": user.date_joined.strftime("%Y-%m-%d"), |
| 1487 |
"date_joined_1": user.date_joined.strftime("%H:%M:%S"), |
| 1488 |
"initial-date_joined_0": user.date_joined.strftime("%Y-%m-%d"), |
| 1489 |
"initial-date_joined_1": user.date_joined.strftime("%H:%M:%S"), |
| 1490 |
"first_name": user.first_name, |
| 1491 |
"last_name": user.last_name, |
| 1492 |
} |
| 1493 |
|
| 1494 |
# #20078 - users shouldn't be allowed to guess password hashes via |
| 1495 |
# repeated password__startswith queries. |
| 1496 |
def test_changelist_disallows_password_lookups(self): |
| 1497 |
# A lookup that tries to filter on password isn't OK |
| 1498 |
with self.assertLogs("django.security.DisallowedModelAdminLookup", "ERROR"): |
| 1499 |
response = self.client.get( |
| 1500 |
reverse("auth_test_admin:auth_user_changelist") |
| 1501 |
+ "?password__startswith=sha1$" |
| 1502 |
) |
| 1503 |
self.assertEqual(response.status_code, 400) |
| 1504 |
|
| 1505 |
def test_user_change_email(self): |
| 1506 |
data = self.get_user_data(self.admin) |
| 1507 |
data["email"] = "new_" + data["email"] |
| 1508 |
response = self.client.post( |
| 1509 |
reverse("auth_test_admin:auth_user_change", args=(self.admin.pk,)), data |
| 1510 |
) |
| 1511 |
self.assertRedirects(response, reverse("auth_test_admin:auth_user_changelist")) |
| 1512 |
row = LogEntry.objects.latest("id") |
| 1513 |
self.assertEqual(row.get_change_message(), "Changed Email address.") |
| 1514 |
|
| 1515 |
def test_user_not_change(self): |
| 1516 |
response = self.client.post( |
| 1517 |
reverse("auth_test_admin:auth_user_change", args=(self.admin.pk,)), |
| 1518 |
self.get_user_data(self.admin), |
| 1519 |
) |
| 1520 |
self.assertRedirects(response, reverse("auth_test_admin:auth_user_changelist")) |
| 1521 |
row = LogEntry.objects.latest("id") |
| 1522 |
self.assertEqual(row.get_change_message(), "No fields changed.") |
| 1523 |
|
| 1524 |
def test_user_with_usable_password_change_password(self): |
| 1525 |
user_change_url = reverse( |
| 1526 |
"auth_test_admin:auth_user_change", args=(self.admin.pk,) |
| 1527 |
) |
| 1528 |
password_change_url = reverse( |
| 1529 |
"auth_test_admin:auth_user_password_change", args=(self.admin.pk,) |
| 1530 |
) |
| 1531 |
|
| 1532 |
response = self.client.get(user_change_url) |
| 1533 |
# Test the link inside password field help_text. |
| 1534 |
rel_link = re.search( |
| 1535 |
r'<a class="button" href="([^"]*)">Reset password</a>', |
| 1536 |
response.text, |
| 1537 |
)[1] |
| 1538 |
self.assertEqual(urljoin(user_change_url, rel_link), password_change_url) |
| 1539 |
|
| 1540 |
response = self.client.get(password_change_url) |
| 1541 |
# Test the form title with original (usable) password |
| 1542 |
self.assertContains( |
| 1543 |
response, f"<h1>Change password: {self.admin.username}</h1>" |
| 1544 |
) |
| 1545 |
# Breadcrumb. |
| 1546 |
self.assertContains( |
| 1547 |
response, f"{self.admin.username}</a>\n› Change password" |
| 1548 |
) |
| 1549 |
# Submit buttons |
| 1550 |
self.assertContains(response, '<input type="submit" name="set-password"') |
| 1551 |
self.assertContains(response, '<input type="submit" name="unset-password"') |
| 1552 |
|
| 1553 |
# Password change. |
| 1554 |
response = self.client.post( |
| 1555 |
password_change_url, |
| 1556 |
{ |
| 1557 |
"password1": "password1", |
| 1558 |
"password2": "password1", |
| 1559 |
}, |
| 1560 |
) |
| 1561 |
self.assertRedirects(response, user_change_url) |
| 1562 |
self.assertMessages( |
| 1563 |
response, [Message(level=25, message="Password changed successfully.")] |
| 1564 |
) |
| 1565 |
row = LogEntry.objects.latest("id") |
| 1566 |
self.assertEqual(row.get_change_message(), "Changed password.") |
| 1567 |
self.logout() |
| 1568 |
self.login(password="password1") |
| 1569 |
|
| 1570 |
# Disable password-based authentication without proper submit button. |
| 1571 |
response = self.client.post( |
| 1572 |
password_change_url, |
| 1573 |
{ |
| 1574 |
"password1": "password1", |
| 1575 |
"password2": "password1", |
| 1576 |
"usable_password": "false", |
| 1577 |
}, |
| 1578 |
) |
| 1579 |
self.assertRedirects(response, password_change_url) |
| 1580 |
self.assertMessages( |
| 1581 |
response, |
| 1582 |
[ |
| 1583 |
Message( |
| 1584 |
level=40, |
| 1585 |
message="Conflicting form data submitted. Please try again.", |
| 1586 |
) |
| 1587 |
], |
| 1588 |
) |
| 1589 |
# No password change yet. |
| 1590 |
self.login(password="password1") |
| 1591 |
|
| 1592 |
# Disable password-based authentication with proper submit button. |
| 1593 |
response = self.client.post( |
| 1594 |
password_change_url, |
| 1595 |
{ |
| 1596 |
"password1": "password1", |
| 1597 |
"password2": "password1", |
| 1598 |
"usable_password": "false", |
| 1599 |
"unset-password": 1, |
| 1600 |
}, |
| 1601 |
) |
| 1602 |
self.assertRedirects(response, user_change_url) |
| 1603 |
self.assertMessages( |
| 1604 |
response, |
| 1605 |
[Message(level=25, message="Password-based authentication was disabled.")], |
| 1606 |
) |
| 1607 |
row = LogEntry.objects.latest("id") |
| 1608 |
self.assertEqual(row.get_change_message(), "Changed password.") |
| 1609 |
self.logout() |
| 1610 |
# Password-based authentication was disabled. |
| 1611 |
with self.assertRaises(AssertionError): |
| 1612 |
self.login(password="password1") |
| 1613 |
self.admin.refresh_from_db() |
| 1614 |
self.assertIs(self.admin.has_usable_password(), False) |
| 1615 |
|
| 1616 |
def test_user_with_unusable_password_change_password(self): |
| 1617 |
# Test for title with unusable password with a test user |
| 1618 |
test_user = User.objects.get(email="[email protected]") |
| 1619 |
test_user.set_unusable_password() |
| 1620 |
test_user.save() |
| 1621 |
user_change_url = reverse( |
| 1622 |
"auth_test_admin:auth_user_change", args=(test_user.pk,) |
| 1623 |
) |
| 1624 |
password_change_url = reverse( |
| 1625 |
"auth_test_admin:auth_user_password_change", args=(test_user.pk,) |
| 1626 |
) |
| 1627 |
|
| 1628 |
response = self.client.get(user_change_url) |
| 1629 |
# Test the link inside password field help_text. |
| 1630 |
rel_link = re.search( |
| 1631 |
r'<a class="button" href="([^"]*)">Set password</a>', |
| 1632 |
response.text, |
| 1633 |
)[1] |
| 1634 |
self.assertEqual(urljoin(user_change_url, rel_link), password_change_url) |
| 1635 |
|
| 1636 |
response = self.client.get(password_change_url) |
| 1637 |
# Test the form title with original (usable) password |
| 1638 |
self.assertContains(response, f"<h1>Set password: {test_user.username}</h1>") |
| 1639 |
# Breadcrumb. |
| 1640 |
self.assertContains( |
| 1641 |
response, f"{test_user.username}</a>\n› Set password" |
| 1642 |
) |
| 1643 |
# Submit buttons |
| 1644 |
self.assertContains(response, '<input type="submit" name="set-password"') |
| 1645 |
self.assertNotContains(response, '<input type="submit" name="unset-password"') |
| 1646 |
|
| 1647 |
response = self.client.post( |
| 1648 |
password_change_url, |
| 1649 |
{ |
| 1650 |
"password1": "password1", |
| 1651 |
"password2": "password1", |
| 1652 |
}, |
| 1653 |
) |
| 1654 |
self.assertRedirects(response, user_change_url) |
| 1655 |
self.assertMessages( |
| 1656 |
response, [Message(level=25, message="Password changed successfully.")] |
| 1657 |
) |
| 1658 |
row = LogEntry.objects.latest("id") |
| 1659 |
self.assertEqual(row.get_change_message(), "Changed password.") |
| 1660 |
|
| 1661 |
def test_user_change_different_user_password(self): |
| 1662 |
u = User.objects.get(email="[email protected]") |
| 1663 |
response = self.client.post( |
| 1664 |
reverse("auth_test_admin:auth_user_password_change", args=(u.pk,)), |
| 1665 |
{ |
| 1666 |
"password1": "password1", |
| 1667 |
"password2": "password1", |
| 1668 |
}, |
| 1669 |
) |
| 1670 |
self.assertRedirects( |
| 1671 |
response, reverse("auth_test_admin:auth_user_change", args=(u.pk,)) |
| 1672 |
) |
| 1673 |
row = LogEntry.objects.latest("id") |
| 1674 |
self.assertEqual(row.user_id, self.admin.pk) |
| 1675 |
self.assertEqual(row.object_id, str(u.pk)) |
| 1676 |
self.assertEqual(row.get_change_message(), "Changed password.") |
| 1677 |
|
| 1678 |
def test_password_change_bad_url(self): |
| 1679 |
response = self.client.get( |
| 1680 |
reverse("auth_test_admin:auth_user_password_change", args=("foobar",)) |
| 1681 |
) |
| 1682 |
self.assertEqual(response.status_code, 404) |
| 1683 |
|
| 1684 |
@mock.patch("django.contrib.auth.admin.UserAdmin.has_change_permission") |
| 1685 |
def test_user_change_password_passes_user_to_has_change_permission( |
| 1686 |
self, has_change_permission |
| 1687 |
): |
| 1688 |
url = reverse( |
| 1689 |
"auth_test_admin:auth_user_password_change", args=(self.admin.pk,) |
| 1690 |
) |
| 1691 |
self.client.post(url, {"password1": "password1", "password2": "password1"}) |
| 1692 |
(_request, user), _kwargs = has_change_permission.call_args |
| 1693 |
self.assertEqual(user.pk, self.admin.pk) |
| 1694 |
|
| 1695 |
def test_view_user_password_is_readonly(self): |
| 1696 |
u = User.objects.get(username="testclient") |
| 1697 |
u.is_superuser = False |
| 1698 |
u.save() |
| 1699 |
original_password = u.password |
| 1700 |
u.user_permissions.add(get_perm(User, "view_user")) |
| 1701 |
response = self.client.get( |
| 1702 |
reverse("auth_test_admin:auth_user_change", args=(u.pk,)), |
| 1703 |
) |
| 1704 |
algo, salt, hash_string = u.password.split("$") |
| 1705 |
self.assertContains(response, '<div class="readonly">testclient</div>') |
| 1706 |
# ReadOnlyPasswordHashWidget is used to render the field. |
| 1707 |
self.assertContains( |
| 1708 |
response, |
| 1709 |
"<strong>algorithm</strong>: <bdi>%s</bdi>\n\n" |
| 1710 |
"<strong>salt</strong>: <bdi>%s********************</bdi>\n\n" |
| 1711 |
"<strong>hash</strong>: <bdi>%s**************************</bdi>\n\n" |
| 1712 |
% ( |
| 1713 |
algo, |
| 1714 |
salt[:2], |
| 1715 |
hash_string[:6], |
| 1716 |
), |
| 1717 |
html=True, |
| 1718 |
) |
| 1719 |
# Value in POST data is ignored. |
| 1720 |
data = self.get_user_data(u) |
| 1721 |
data["password"] = "shouldnotchange" |
| 1722 |
change_url = reverse("auth_test_admin:auth_user_change", args=(u.pk,)) |
| 1723 |
response = self.client.post(change_url, data) |
| 1724 |
self.assertEqual(response.status_code, 403) |
| 1725 |
u.refresh_from_db() |
| 1726 |
self.assertEqual(u.password, original_password) |
| 1727 |
|
| 1728 |
|
| 1729 |
@override_settings( |
| 1730 |
AUTH_USER_MODEL="auth_tests.UUIDUser", |
| 1731 |
ROOT_URLCONF="auth_tests.urls_custom_user_admin", |
| 1732 |
) |
| 1733 |
class UUIDUserTests(TestCase): |
| 1734 |
def test_admin_password_change(self): |
| 1735 |
u = UUIDUser.objects.create_superuser( |
| 1736 |
username="uuid", email="[email protected]", password="test" |
| 1737 |
) |
| 1738 |
self.assertTrue(self.client.login(username="uuid", password="test")) |
| 1739 |
|
| 1740 |
user_change_url = reverse( |
| 1741 |
"custom_user_admin:auth_tests_uuiduser_change", args=(u.pk,) |
| 1742 |
) |
| 1743 |
response = self.client.get(user_change_url) |
| 1744 |
self.assertEqual(response.status_code, 200) |
| 1745 |
|
| 1746 |
password_change_url = reverse( |
| 1747 |
"custom_user_admin:auth_user_password_change", args=(u.pk,) |
| 1748 |
) |
| 1749 |
response = self.client.get(password_change_url) |
| 1750 |
# The action attribute is omitted. |
| 1751 |
self.assertContains(response, '<form method="post" id="uuiduser_form">') |
| 1752 |
|
| 1753 |
# A LogEntry is created with pk=1 which breaks a FK constraint on MySQL |
| 1754 |
with connection.constraint_checks_disabled(): |
| 1755 |
response = self.client.post( |
| 1756 |
password_change_url, |
| 1757 |
{ |
| 1758 |
"password1": "password1", |
| 1759 |
"password2": "password1", |
| 1760 |
}, |
| 1761 |
) |
| 1762 |
self.assertRedirects(response, user_change_url) |
| 1763 |
row = LogEntry.objects.latest("id") |
| 1764 |
self.assertEqual(row.user_id, 1) # hardcoded in CustomUserAdmin.log_change() |
| 1765 |
self.assertEqual(row.object_id, str(u.pk)) |
| 1766 |
self.assertEqual(row.get_change_message(), "Changed password.") |
| 1767 |
|
| 1768 |
# The LogEntry.user column isn't altered to a UUID type so it's set to |
| 1769 |
# an integer manually in CustomUserAdmin to avoid an error. To avoid a |
| 1770 |
# constraint error, delete the entry before constraints are checked |
| 1771 |
# after the test. |
| 1772 |
row.delete() |