| 1 |
import sys |
| 2 |
import unittest |
| 3 |
from datetime import date |
| 4 |
from typing import TYPE_CHECKING, TypeAlias |
| 5 |
from unittest import mock |
| 6 |
from unittest.mock import patch |
| 7 |
|
| 8 |
from asgiref.sync import sync_to_async |
| 9 |
|
| 10 |
from django.contrib.auth import ( |
| 11 |
BACKEND_SESSION_KEY, |
| 12 |
SESSION_KEY, |
| 13 |
_clean_credentials, |
| 14 |
aauthenticate, |
| 15 |
authenticate, |
| 16 |
get_user, |
| 17 |
signals, |
| 18 |
) |
| 19 |
from django.contrib.auth.backends import BaseBackend, ModelBackend |
| 20 |
from django.contrib.auth.forms import PasswordChangeForm, SetPasswordForm |
| 21 |
from django.contrib.auth.hashers import MD5PasswordHasher |
| 22 |
from django.contrib.auth.models import AnonymousUser, Group, Permission, User |
| 23 |
from django.contrib.contenttypes.models import ContentType |
| 24 |
from django.core.exceptions import ImproperlyConfigured, PermissionDenied |
| 25 |
from django.http import HttpRequest |
| 26 |
from django.test import ( |
| 27 |
Client, |
| 28 |
RequestFactory, |
| 29 |
SimpleTestCase, |
| 30 |
TestCase, |
| 31 |
modify_settings, |
| 32 |
override_settings, |
| 33 |
) |
| 34 |
from django.urls import reverse |
| 35 |
from django.utils.version import PY314 |
| 36 |
from django.views.debug import ExceptionReporter, technical_500_response |
| 37 |
from django.views.decorators.debug import sensitive_variables |
| 38 |
|
| 39 |
from .models import ( |
| 40 |
CustomPermissionsUser, |
| 41 |
CustomUser, |
| 42 |
CustomUserWithoutIsActiveField, |
| 43 |
ExtensionUser, |
| 44 |
UUIDUser, |
| 45 |
) |
| 46 |
|
| 47 |
if TYPE_CHECKING: |
| 48 |
AnnotatedUsername: TypeAlias = str |
| 49 |
AnnotatedPassword: TypeAlias = str |
| 50 |
|
| 51 |
|
| 52 |
class FilteredExceptionReporter(ExceptionReporter): |
| 53 |
def get_traceback_frames(self): |
| 54 |
frames = super().get_traceback_frames() |
| 55 |
return [ |
| 56 |
frame |
| 57 |
for frame in frames |
| 58 |
if not isinstance(dict(frame["vars"]).get("self"), Client) |
| 59 |
] |
| 60 |
|
| 61 |
|
| 62 |
class SimpleBackend(BaseBackend): |
| 63 |
def get_user_permissions(self, user_obj, obj=None): |
| 64 |
return ["user_perm"] |
| 65 |
|
| 66 |
def get_group_permissions(self, user_obj, obj=None): |
| 67 |
return ["group_perm"] |
| 68 |
|
| 69 |
|
| 70 |
@override_settings( |
| 71 |
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleBackend"] |
| 72 |
) |
| 73 |
class BaseBackendTest(TestCase): |
| 74 |
@classmethod |
| 75 |
def setUpTestData(cls): |
| 76 |
cls.user = User.objects.create_user("test", "[email protected]", "test") |
| 77 |
|
| 78 |
def test_get_user_permissions(self): |
| 79 |
self.assertEqual(self.user.get_user_permissions(), {"user_perm"}) |
| 80 |
|
| 81 |
async def test_aget_user_permissions(self): |
| 82 |
self.assertEqual(await self.user.aget_user_permissions(), {"user_perm"}) |
| 83 |
|
| 84 |
def test_get_group_permissions(self): |
| 85 |
self.assertEqual(self.user.get_group_permissions(), {"group_perm"}) |
| 86 |
|
| 87 |
async def test_aget_group_permissions(self): |
| 88 |
self.assertEqual(await self.user.aget_group_permissions(), {"group_perm"}) |
| 89 |
|
| 90 |
def test_get_all_permissions(self): |
| 91 |
self.assertEqual(self.user.get_all_permissions(), {"user_perm", "group_perm"}) |
| 92 |
|
| 93 |
async def test_aget_all_permissions(self): |
| 94 |
self.assertEqual( |
| 95 |
await self.user.aget_all_permissions(), {"user_perm", "group_perm"} |
| 96 |
) |
| 97 |
|
| 98 |
def test_has_perm(self): |
| 99 |
self.assertIs(self.user.has_perm("user_perm"), True) |
| 100 |
self.assertIs(self.user.has_perm("group_perm"), True) |
| 101 |
self.assertIs(self.user.has_perm("other_perm", TestObj()), False) |
| 102 |
|
| 103 |
async def test_ahas_perm(self): |
| 104 |
self.assertIs(await self.user.ahas_perm("user_perm"), True) |
| 105 |
self.assertIs(await self.user.ahas_perm("group_perm"), True) |
| 106 |
self.assertIs(await self.user.ahas_perm("other_perm", TestObj()), False) |
| 107 |
|
| 108 |
def test_has_perms_perm_list_invalid(self): |
| 109 |
msg = "perm_list must be an iterable of permissions." |
| 110 |
with self.assertRaisesMessage(ValueError, msg): |
| 111 |
self.user.has_perms("user_perm") |
| 112 |
with self.assertRaisesMessage(ValueError, msg): |
| 113 |
self.user.has_perms(object()) |
| 114 |
|
| 115 |
async def test_ahas_perms_perm_list_invalid(self): |
| 116 |
msg = "perm_list must be an iterable of permissions." |
| 117 |
with self.assertRaisesMessage(ValueError, msg): |
| 118 |
await self.user.ahas_perms("user_perm") |
| 119 |
with self.assertRaisesMessage(ValueError, msg): |
| 120 |
await self.user.ahas_perms(object()) |
| 121 |
|
| 122 |
|
| 123 |
class CountingMD5PasswordHasher(MD5PasswordHasher): |
| 124 |
"""Hasher that counts how many times it computes a hash.""" |
| 125 |
|
| 126 |
calls = 0 |
| 127 |
|
| 128 |
def encode(self, *args, **kwargs): |
| 129 |
type(self).calls += 1 |
| 130 |
return super().encode(*args, **kwargs) |
| 131 |
|
| 132 |
|
| 133 |
class BaseModelBackendTest: |
| 134 |
""" |
| 135 |
A base class for tests that need to validate the ModelBackend |
| 136 |
with different User models. Subclasses should define a class |
| 137 |
level UserModel attribute, and a create_users() method to |
| 138 |
construct two users for test purposes. |
| 139 |
""" |
| 140 |
|
| 141 |
backend = "django.contrib.auth.backends.ModelBackend" |
| 142 |
|
| 143 |
@classmethod |
| 144 |
def setUpClass(cls): |
| 145 |
cls.enterClassContext( |
| 146 |
modify_settings(AUTHENTICATION_BACKENDS={"append": cls.backend}) |
| 147 |
) |
| 148 |
super().setUpClass() |
| 149 |
|
| 150 |
def setUp(self): |
| 151 |
# The custom_perms test messes with ContentTypes, which will be cached. |
| 152 |
# Flush the cache to ensure there are no side effects. |
| 153 |
self.addCleanup(ContentType.objects.clear_cache) |
| 154 |
self.create_users() |
| 155 |
|
| 156 |
def test_has_perm(self): |
| 157 |
user = self.UserModel._default_manager.get(pk=self.user.pk) |
| 158 |
self.assertIs(user.has_perm("auth.test"), False) |
| 159 |
|
| 160 |
user.is_staff = True |
| 161 |
user.save() |
| 162 |
self.assertIs(user.has_perm("auth.test"), False) |
| 163 |
|
| 164 |
user.is_superuser = True |
| 165 |
user.save() |
| 166 |
self.assertIs(user.has_perm("auth.test"), True) |
| 167 |
|
| 168 |
user.is_staff = True |
| 169 |
user.is_superuser = True |
| 170 |
user.is_active = False |
| 171 |
user.save() |
| 172 |
self.assertIs(user.has_perm("auth.test"), False) |
| 173 |
|
| 174 |
async def test_ahas_perm(self): |
| 175 |
user = await self.UserModel._default_manager.aget(pk=self.user.pk) |
| 176 |
self.assertIs(await user.ahas_perm("auth.test"), False) |
| 177 |
|
| 178 |
user.is_staff = True |
| 179 |
await user.asave() |
| 180 |
self.assertIs(await user.ahas_perm("auth.test"), False) |
| 181 |
|
| 182 |
user.is_superuser = True |
| 183 |
await user.asave() |
| 184 |
self.assertIs(await user.ahas_perm("auth.test"), True) |
| 185 |
self.assertIs(await user.ahas_module_perms("auth"), True) |
| 186 |
|
| 187 |
user.is_staff = True |
| 188 |
user.is_superuser = True |
| 189 |
user.is_active = False |
| 190 |
await user.asave() |
| 191 |
self.assertIs(await user.ahas_perm("auth.test"), False) |
| 192 |
|
| 193 |
def test_custom_perms(self): |
| 194 |
user = self.UserModel._default_manager.get(pk=self.user.pk) |
| 195 |
content_type = ContentType.objects.get_for_model(Group) |
| 196 |
perm = Permission.objects.create( |
| 197 |
name="test", content_type=content_type, codename="test" |
| 198 |
) |
| 199 |
user.user_permissions.add(perm) |
| 200 |
|
| 201 |
# reloading user to purge the _perm_cache |
| 202 |
user = self.UserModel._default_manager.get(pk=self.user.pk) |
| 203 |
self.assertEqual(user.get_all_permissions(), {"auth.test"}) |
| 204 |
self.assertEqual(user.get_user_permissions(), {"auth.test"}) |
| 205 |
self.assertEqual(user.get_group_permissions(), set()) |
| 206 |
self.assertIs(user.has_module_perms("Group"), False) |
| 207 |
self.assertIs(user.has_module_perms("auth"), True) |
| 208 |
|
| 209 |
perm = Permission.objects.create( |
| 210 |
name="test2", content_type=content_type, codename="test2" |
| 211 |
) |
| 212 |
user.user_permissions.add(perm) |
| 213 |
perm = Permission.objects.create( |
| 214 |
name="test3", content_type=content_type, codename="test3" |
| 215 |
) |
| 216 |
user.user_permissions.add(perm) |
| 217 |
user = self.UserModel._default_manager.get(pk=self.user.pk) |
| 218 |
expected_user_perms = {"auth.test2", "auth.test", "auth.test3"} |
| 219 |
self.assertEqual(user.get_all_permissions(), expected_user_perms) |
| 220 |
self.assertIs(user.has_perm("test"), False) |
| 221 |
self.assertIs(user.has_perm("auth.test"), True) |
| 222 |
self.assertIs(user.has_perms(["auth.test2", "auth.test3"]), True) |
| 223 |
|
| 224 |
perm = Permission.objects.create( |
| 225 |
name="test_group", content_type=content_type, codename="test_group" |
| 226 |
) |
| 227 |
group = Group.objects.create(name="test_group") |
| 228 |
group.permissions.add(perm) |
| 229 |
user.groups.add(group) |
| 230 |
user = self.UserModel._default_manager.get(pk=self.user.pk) |
| 231 |
self.assertEqual( |
| 232 |
user.get_all_permissions(), {*expected_user_perms, "auth.test_group"} |
| 233 |
) |
| 234 |
self.assertEqual(user.get_user_permissions(), expected_user_perms) |
| 235 |
self.assertEqual(user.get_group_permissions(), {"auth.test_group"}) |
| 236 |
self.assertIs(user.has_perms(["auth.test3", "auth.test_group"]), True) |
| 237 |
|
| 238 |
user = AnonymousUser() |
| 239 |
self.assertIs(user.has_perm("test"), False) |
| 240 |
self.assertIs(user.has_perms(["auth.test2", "auth.test3"]), False) |
| 241 |
|
| 242 |
async def test_acustom_perms(self): |
| 243 |
user = await self.UserModel._default_manager.aget(pk=self.user.pk) |
| 244 |
content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) |
| 245 |
perm = await Permission.objects.acreate( |
| 246 |
name="test", content_type=content_type, codename="test" |
| 247 |
) |
| 248 |
await user.user_permissions.aadd(perm) |
| 249 |
|
| 250 |
# Reloading user to purge the _perm_cache. |
| 251 |
user = await self.UserModel._default_manager.aget(pk=self.user.pk) |
| 252 |
self.assertEqual(await user.aget_all_permissions(), {"auth.test"}) |
| 253 |
self.assertEqual(await user.aget_user_permissions(), {"auth.test"}) |
| 254 |
self.assertEqual(await user.aget_group_permissions(), set()) |
| 255 |
self.assertIs(await user.ahas_module_perms("Group"), False) |
| 256 |
self.assertIs(await user.ahas_module_perms("auth"), True) |
| 257 |
|
| 258 |
perm = await Permission.objects.acreate( |
| 259 |
name="test2", content_type=content_type, codename="test2" |
| 260 |
) |
| 261 |
await user.user_permissions.aadd(perm) |
| 262 |
perm = await Permission.objects.acreate( |
| 263 |
name="test3", content_type=content_type, codename="test3" |
| 264 |
) |
| 265 |
await user.user_permissions.aadd(perm) |
| 266 |
user = await self.UserModel._default_manager.aget(pk=self.user.pk) |
| 267 |
expected_user_perms = {"auth.test2", "auth.test", "auth.test3"} |
| 268 |
self.assertEqual(await user.aget_all_permissions(), expected_user_perms) |
| 269 |
self.assertIs(await user.ahas_perm("test"), False) |
| 270 |
self.assertIs(await user.ahas_perm("auth.test"), True) |
| 271 |
self.assertIs(await user.ahas_perms(["auth.test2", "auth.test3"]), True) |
| 272 |
|
| 273 |
perm = await Permission.objects.acreate( |
| 274 |
name="test_group", content_type=content_type, codename="test_group" |
| 275 |
) |
| 276 |
group = await Group.objects.acreate(name="test_group") |
| 277 |
await group.permissions.aadd(perm) |
| 278 |
await user.groups.aadd(group) |
| 279 |
user = await self.UserModel._default_manager.aget(pk=self.user.pk) |
| 280 |
self.assertEqual( |
| 281 |
await user.aget_all_permissions(), {*expected_user_perms, "auth.test_group"} |
| 282 |
) |
| 283 |
self.assertEqual(await user.aget_user_permissions(), expected_user_perms) |
| 284 |
self.assertEqual(await user.aget_group_permissions(), {"auth.test_group"}) |
| 285 |
self.assertIs(await user.ahas_perms(["auth.test3", "auth.test_group"]), True) |
| 286 |
|
| 287 |
user = AnonymousUser() |
| 288 |
self.assertIs(await user.ahas_perm("test"), False) |
| 289 |
self.assertIs(await user.ahas_perms(["auth.test2", "auth.test3"]), False) |
| 290 |
|
| 291 |
def test_has_no_object_perm(self): |
| 292 |
"""Regressiontest for #12462""" |
| 293 |
user = self.UserModel._default_manager.get(pk=self.user.pk) |
| 294 |
content_type = ContentType.objects.get_for_model(Group) |
| 295 |
perm = Permission.objects.create( |
| 296 |
name="test", content_type=content_type, codename="test" |
| 297 |
) |
| 298 |
user.user_permissions.add(perm) |
| 299 |
|
| 300 |
self.assertIs(user.has_perm("auth.test", "object"), False) |
| 301 |
self.assertEqual(user.get_all_permissions("object"), set()) |
| 302 |
self.assertIs(user.has_perm("auth.test"), True) |
| 303 |
self.assertEqual(user.get_all_permissions(), {"auth.test"}) |
| 304 |
|
| 305 |
async def test_ahas_no_object_perm(self): |
| 306 |
"""See test_has_no_object_perm()""" |
| 307 |
user = await self.UserModel._default_manager.aget(pk=self.user.pk) |
| 308 |
content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) |
| 309 |
perm = await Permission.objects.acreate( |
| 310 |
name="test", content_type=content_type, codename="test" |
| 311 |
) |
| 312 |
await user.user_permissions.aadd(perm) |
| 313 |
|
| 314 |
self.assertIs(await user.ahas_perm("auth.test", "object"), False) |
| 315 |
self.assertEqual(await user.aget_all_permissions("object"), set()) |
| 316 |
self.assertIs(await user.ahas_perm("auth.test"), True) |
| 317 |
self.assertEqual(await user.aget_all_permissions(), {"auth.test"}) |
| 318 |
|
| 319 |
def test_anonymous_has_no_permissions(self): |
| 320 |
""" |
| 321 |
#17903 -- Anonymous users shouldn't have permissions in |
| 322 |
ModelBackend.get_(all|user|group)_permissions(). |
| 323 |
""" |
| 324 |
backend = ModelBackend() |
| 325 |
|
| 326 |
user = self.UserModel._default_manager.get(pk=self.user.pk) |
| 327 |
content_type = ContentType.objects.get_for_model(Group) |
| 328 |
user_perm = Permission.objects.create( |
| 329 |
name="test", content_type=content_type, codename="test_user" |
| 330 |
) |
| 331 |
group_perm = Permission.objects.create( |
| 332 |
name="test2", content_type=content_type, codename="test_group" |
| 333 |
) |
| 334 |
user.user_permissions.add(user_perm) |
| 335 |
|
| 336 |
group = Group.objects.create(name="test_group") |
| 337 |
user.groups.add(group) |
| 338 |
group.permissions.add(group_perm) |
| 339 |
|
| 340 |
self.assertEqual( |
| 341 |
backend.get_all_permissions(user), {"auth.test_user", "auth.test_group"} |
| 342 |
) |
| 343 |
self.assertEqual(backend.get_user_permissions(user), {"auth.test_user"}) |
| 344 |
self.assertEqual(backend.get_group_permissions(user), {"auth.test_group"}) |
| 345 |
|
| 346 |
with mock.patch.object(self.UserModel, "is_anonymous", True): |
| 347 |
self.assertEqual(backend.get_all_permissions(user), set()) |
| 348 |
self.assertEqual(backend.get_user_permissions(user), set()) |
| 349 |
self.assertEqual(backend.get_group_permissions(user), set()) |
| 350 |
|
| 351 |
async def test_aanonymous_has_no_permissions(self): |
| 352 |
"""See test_anonymous_has_no_permissions()""" |
| 353 |
backend = ModelBackend() |
| 354 |
|
| 355 |
user = await self.UserModel._default_manager.aget(pk=self.user.pk) |
| 356 |
content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) |
| 357 |
user_perm = await Permission.objects.acreate( |
| 358 |
name="test", content_type=content_type, codename="test_user" |
| 359 |
) |
| 360 |
group_perm = await Permission.objects.acreate( |
| 361 |
name="test2", content_type=content_type, codename="test_group" |
| 362 |
) |
| 363 |
await user.user_permissions.aadd(user_perm) |
| 364 |
|
| 365 |
group = await Group.objects.acreate(name="test_group") |
| 366 |
await user.groups.aadd(group) |
| 367 |
await group.permissions.aadd(group_perm) |
| 368 |
|
| 369 |
self.assertEqual( |
| 370 |
await backend.aget_all_permissions(user), |
| 371 |
{"auth.test_user", "auth.test_group"}, |
| 372 |
) |
| 373 |
self.assertEqual(await backend.aget_user_permissions(user), {"auth.test_user"}) |
| 374 |
self.assertEqual( |
| 375 |
await backend.aget_group_permissions(user), {"auth.test_group"} |
| 376 |
) |
| 377 |
|
| 378 |
with mock.patch.object(self.UserModel, "is_anonymous", True): |
| 379 |
self.assertEqual(await backend.aget_all_permissions(user), set()) |
| 380 |
self.assertEqual(await backend.aget_user_permissions(user), set()) |
| 381 |
self.assertEqual(await backend.aget_group_permissions(user), set()) |
| 382 |
|
| 383 |
def test_inactive_has_no_permissions(self): |
| 384 |
""" |
| 385 |
#17903 -- Inactive users shouldn't have permissions in |
| 386 |
ModelBackend.get_(all|user|group)_permissions(). |
| 387 |
""" |
| 388 |
backend = ModelBackend() |
| 389 |
|
| 390 |
user = self.UserModel._default_manager.get(pk=self.user.pk) |
| 391 |
content_type = ContentType.objects.get_for_model(Group) |
| 392 |
user_perm = Permission.objects.create( |
| 393 |
name="test", content_type=content_type, codename="test_user" |
| 394 |
) |
| 395 |
group_perm = Permission.objects.create( |
| 396 |
name="test2", content_type=content_type, codename="test_group" |
| 397 |
) |
| 398 |
user.user_permissions.add(user_perm) |
| 399 |
|
| 400 |
group = Group.objects.create(name="test_group") |
| 401 |
user.groups.add(group) |
| 402 |
group.permissions.add(group_perm) |
| 403 |
|
| 404 |
self.assertEqual( |
| 405 |
backend.get_all_permissions(user), {"auth.test_user", "auth.test_group"} |
| 406 |
) |
| 407 |
self.assertEqual(backend.get_user_permissions(user), {"auth.test_user"}) |
| 408 |
self.assertEqual(backend.get_group_permissions(user), {"auth.test_group"}) |
| 409 |
|
| 410 |
user.is_active = False |
| 411 |
user.save() |
| 412 |
|
| 413 |
self.assertEqual(backend.get_all_permissions(user), set()) |
| 414 |
self.assertEqual(backend.get_user_permissions(user), set()) |
| 415 |
self.assertEqual(backend.get_group_permissions(user), set()) |
| 416 |
|
| 417 |
async def test_ainactive_has_no_permissions(self): |
| 418 |
"""See test_inactive_has_no_permissions()""" |
| 419 |
backend = ModelBackend() |
| 420 |
|
| 421 |
user = await self.UserModel._default_manager.aget(pk=self.user.pk) |
| 422 |
content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) |
| 423 |
user_perm = await Permission.objects.acreate( |
| 424 |
name="test", content_type=content_type, codename="test_user" |
| 425 |
) |
| 426 |
group_perm = await Permission.objects.acreate( |
| 427 |
name="test2", content_type=content_type, codename="test_group" |
| 428 |
) |
| 429 |
await user.user_permissions.aadd(user_perm) |
| 430 |
|
| 431 |
group = await Group.objects.acreate(name="test_group") |
| 432 |
await user.groups.aadd(group) |
| 433 |
await group.permissions.aadd(group_perm) |
| 434 |
|
| 435 |
self.assertEqual( |
| 436 |
await backend.aget_all_permissions(user), |
| 437 |
{"auth.test_user", "auth.test_group"}, |
| 438 |
) |
| 439 |
self.assertEqual(await backend.aget_user_permissions(user), {"auth.test_user"}) |
| 440 |
self.assertEqual( |
| 441 |
await backend.aget_group_permissions(user), {"auth.test_group"} |
| 442 |
) |
| 443 |
|
| 444 |
user.is_active = False |
| 445 |
await user.asave() |
| 446 |
|
| 447 |
self.assertEqual(await backend.aget_all_permissions(user), set()) |
| 448 |
self.assertEqual(await backend.aget_user_permissions(user), set()) |
| 449 |
self.assertEqual(await backend.aget_group_permissions(user), set()) |
| 450 |
|
| 451 |
def test_get_all_superuser_permissions(self): |
| 452 |
"""A superuser has all permissions. Refs #14795.""" |
| 453 |
user = self.UserModel._default_manager.get(pk=self.superuser.pk) |
| 454 |
self.assertEqual(len(user.get_all_permissions()), len(Permission.objects.all())) |
| 455 |
|
| 456 |
async def test_aget_all_superuser_permissions(self): |
| 457 |
"""See test_get_all_superuser_permissions()""" |
| 458 |
user = await self.UserModel._default_manager.aget(pk=self.superuser.pk) |
| 459 |
self.assertEqual( |
| 460 |
len(await user.aget_all_permissions()), await Permission.objects.acount() |
| 461 |
) |
| 462 |
|
| 463 |
@override_settings( |
| 464 |
PASSWORD_HASHERS=["auth_tests.test_auth_backends.CountingMD5PasswordHasher"] |
| 465 |
) |
| 466 |
def test_authentication_timing(self): |
| 467 |
"""Hasher is run once regardless of whether the user exists. Refs #20760.""" |
| 468 |
# Re-set the password, because this tests overrides PASSWORD_HASHERS |
| 469 |
self.user.set_password("test") |
| 470 |
self.user.save() |
| 471 |
|
| 472 |
CountingMD5PasswordHasher.calls = 0 |
| 473 |
username = getattr(self.user, self.UserModel.USERNAME_FIELD) |
| 474 |
authenticate(username=username, password="test") |
| 475 |
self.assertEqual(CountingMD5PasswordHasher.calls, 1) |
| 476 |
|
| 477 |
CountingMD5PasswordHasher.calls = 0 |
| 478 |
authenticate(username="no_such_user", password="test") |
| 479 |
self.assertEqual(CountingMD5PasswordHasher.calls, 1) |
| 480 |
|
| 481 |
@override_settings( |
| 482 |
PASSWORD_HASHERS=["auth_tests.test_auth_backends.CountingMD5PasswordHasher"] |
| 483 |
) |
| 484 |
async def test_aauthentication_timing(self): |
| 485 |
"""See test_authentication_timing()""" |
| 486 |
# Re-set the password, because this tests overrides PASSWORD_HASHERS. |
| 487 |
self.user.set_password("test") |
| 488 |
await self.user.asave() |
| 489 |
|
| 490 |
CountingMD5PasswordHasher.calls = 0 |
| 491 |
username = getattr(self.user, self.UserModel.USERNAME_FIELD) |
| 492 |
await aauthenticate(username=username, password="test") |
| 493 |
self.assertEqual(CountingMD5PasswordHasher.calls, 1) |
| 494 |
|
| 495 |
CountingMD5PasswordHasher.calls = 0 |
| 496 |
await aauthenticate(username="no_such_user", password="test") |
| 497 |
self.assertEqual(CountingMD5PasswordHasher.calls, 1) |
| 498 |
|
| 499 |
@override_settings( |
| 500 |
PASSWORD_HASHERS=["auth_tests.test_auth_backends.CountingMD5PasswordHasher"] |
| 501 |
) |
| 502 |
def test_authentication_without_credentials(self): |
| 503 |
CountingMD5PasswordHasher.calls = 0 |
| 504 |
for credentials in ( |
| 505 |
{}, |
| 506 |
{"username": getattr(self.user, self.UserModel.USERNAME_FIELD)}, |
| 507 |
{"password": "test"}, |
| 508 |
): |
| 509 |
with self.subTest(credentials=credentials): |
| 510 |
with self.assertNumQueries(0): |
| 511 |
authenticate(**credentials) |
| 512 |
self.assertEqual(CountingMD5PasswordHasher.calls, 0) |
| 513 |
|
| 514 |
|
| 515 |
class ModelBackendTest(BaseModelBackendTest, TestCase): |
| 516 |
""" |
| 517 |
Tests for the ModelBackend using the default User model. |
| 518 |
""" |
| 519 |
|
| 520 |
UserModel = User |
| 521 |
user_credentials = {"username": "test", "password": "test"} |
| 522 |
|
| 523 |
def create_users(self): |
| 524 |
self.user = User.objects.create_user( |
| 525 |
email="[email protected]", **self.user_credentials |
| 526 |
) |
| 527 |
self.superuser = User.objects.create_superuser( |
| 528 |
username="test2", |
| 529 |
email="[email protected]", |
| 530 |
password="test", |
| 531 |
) |
| 532 |
|
| 533 |
def test_authenticate_inactive(self): |
| 534 |
""" |
| 535 |
An inactive user can't authenticate. |
| 536 |
""" |
| 537 |
self.assertEqual(authenticate(**self.user_credentials), self.user) |
| 538 |
self.user.is_active = False |
| 539 |
self.user.save() |
| 540 |
self.assertIsNone(authenticate(**self.user_credentials)) |
| 541 |
|
| 542 |
async def test_aauthenticate_inactive(self): |
| 543 |
""" |
| 544 |
An inactive user can't authenticate. |
| 545 |
""" |
| 546 |
self.assertEqual(await aauthenticate(**self.user_credentials), self.user) |
| 547 |
self.user.is_active = False |
| 548 |
await self.user.asave() |
| 549 |
self.assertIsNone(await aauthenticate(**self.user_credentials)) |
| 550 |
|
| 551 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithoutIsActiveField") |
| 552 |
def test_authenticate_user_without_is_active_field(self): |
| 553 |
""" |
| 554 |
A custom user without an `is_active` field is allowed to authenticate. |
| 555 |
""" |
| 556 |
user = CustomUserWithoutIsActiveField.objects._create_user( |
| 557 |
username="test", |
| 558 |
email="[email protected]", |
| 559 |
password="test", |
| 560 |
) |
| 561 |
self.assertEqual(authenticate(username="test", password="test"), user) |
| 562 |
|
| 563 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUserWithoutIsActiveField") |
| 564 |
async def test_aauthenticate_user_without_is_active_field(self): |
| 565 |
""" |
| 566 |
A custom user without an `is_active` field is allowed to authenticate. |
| 567 |
""" |
| 568 |
user = await CustomUserWithoutIsActiveField.objects._acreate_user( |
| 569 |
username="test", |
| 570 |
email="[email protected]", |
| 571 |
password="test", |
| 572 |
) |
| 573 |
self.assertEqual(await aauthenticate(username="test", password="test"), user) |
| 574 |
|
| 575 |
|
| 576 |
@override_settings(AUTH_USER_MODEL="auth_tests.ExtensionUser") |
| 577 |
class ExtensionUserModelBackendTest(BaseModelBackendTest, TestCase): |
| 578 |
""" |
| 579 |
Tests for the ModelBackend using the custom ExtensionUser model. |
| 580 |
|
| 581 |
This isn't a perfect test, because both the User and ExtensionUser are |
| 582 |
synchronized to the database, which wouldn't ordinary happen in |
| 583 |
production. As a result, it doesn't catch errors caused by the non- |
| 584 |
existence of the User table. |
| 585 |
|
| 586 |
The specific problem is queries on .filter(groups__user) et al, which |
| 587 |
makes an implicit assumption that the user model is called 'User'. In |
| 588 |
production, the auth.User table won't exist, so the requested join |
| 589 |
won't exist either; in testing, the auth.User *does* exist, and |
| 590 |
so does the join. However, the join table won't contain any useful |
| 591 |
data; for testing, we check that the data we expect actually does exist. |
| 592 |
""" |
| 593 |
|
| 594 |
UserModel = ExtensionUser |
| 595 |
|
| 596 |
def create_users(self): |
| 597 |
self.user = ExtensionUser._default_manager.create_user( |
| 598 |
username="test", |
| 599 |
email="[email protected]", |
| 600 |
password="test", |
| 601 |
date_of_birth=date(2006, 4, 25), |
| 602 |
) |
| 603 |
self.superuser = ExtensionUser._default_manager.create_superuser( |
| 604 |
username="test2", |
| 605 |
email="[email protected]", |
| 606 |
password="test", |
| 607 |
date_of_birth=date(1976, 11, 8), |
| 608 |
) |
| 609 |
|
| 610 |
|
| 611 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomPermissionsUser") |
| 612 |
class CustomPermissionsUserModelBackendTest(BaseModelBackendTest, TestCase): |
| 613 |
""" |
| 614 |
Tests for the ModelBackend using the CustomPermissionsUser model. |
| 615 |
|
| 616 |
As with the ExtensionUser test, this isn't a perfect test, because both |
| 617 |
the User and CustomPermissionsUser are synchronized to the database, |
| 618 |
which wouldn't ordinary happen in production. |
| 619 |
""" |
| 620 |
|
| 621 |
UserModel = CustomPermissionsUser |
| 622 |
|
| 623 |
def create_users(self): |
| 624 |
self.user = CustomPermissionsUser._default_manager.create_user( |
| 625 |
email="[email protected]", password="test", date_of_birth=date(2006, 4, 25) |
| 626 |
) |
| 627 |
self.superuser = CustomPermissionsUser._default_manager.create_superuser( |
| 628 |
email="[email protected]", password="test", date_of_birth=date(1976, 11, 8) |
| 629 |
) |
| 630 |
|
| 631 |
|
| 632 |
@override_settings(AUTH_USER_MODEL="auth_tests.CustomUser") |
| 633 |
class CustomUserModelBackendAuthenticateTest(TestCase): |
| 634 |
""" |
| 635 |
The model backend can accept a credentials kwarg labeled with |
| 636 |
custom user model's USERNAME_FIELD. |
| 637 |
""" |
| 638 |
|
| 639 |
def test_authenticate(self): |
| 640 |
test_user = CustomUser._default_manager.create_user( |
| 641 |
email="[email protected]", password="test", date_of_birth=date(2006, 4, 25) |
| 642 |
) |
| 643 |
authenticated_user = authenticate(email="[email protected]", password="test") |
| 644 |
self.assertEqual(test_user, authenticated_user) |
| 645 |
|
| 646 |
async def test_aauthenticate(self): |
| 647 |
test_user = await CustomUser._default_manager.acreate_user( |
| 648 |
email="[email protected]", password="test", date_of_birth=date(2006, 4, 25) |
| 649 |
) |
| 650 |
authenticated_user = await aauthenticate( |
| 651 |
email="[email protected]", password="test" |
| 652 |
) |
| 653 |
self.assertEqual(test_user, authenticated_user) |
| 654 |
|
| 655 |
|
| 656 |
@override_settings(AUTH_USER_MODEL="auth_tests.UUIDUser") |
| 657 |
class UUIDUserTests(TestCase): |
| 658 |
def test_login(self): |
| 659 |
""" |
| 660 |
A custom user with a UUID primary key should be able to login. |
| 661 |
""" |
| 662 |
user = UUIDUser.objects.create_user(username="uuid", password="test") |
| 663 |
self.assertTrue(self.client.login(username="uuid", password="test")) |
| 664 |
self.assertEqual( |
| 665 |
UUIDUser.objects.get(pk=self.client.session[SESSION_KEY]), user |
| 666 |
) |
| 667 |
|
| 668 |
async def test_alogin(self): |
| 669 |
"""See test_login()""" |
| 670 |
user = await UUIDUser.objects.acreate_user(username="uuid", password="test") |
| 671 |
self.assertTrue(await self.client.alogin(username="uuid", password="test")) |
| 672 |
session_key = await self.client.session.aget(SESSION_KEY) |
| 673 |
self.assertEqual(await UUIDUser.objects.aget(pk=session_key), user) |
| 674 |
|
| 675 |
|
| 676 |
class TestObj: |
| 677 |
pass |
| 678 |
|
| 679 |
|
| 680 |
class SimpleRowlevelBackend: |
| 681 |
def has_perm(self, user, perm, obj=None): |
| 682 |
if not obj: |
| 683 |
return # We only support row level perms |
| 684 |
|
| 685 |
if isinstance(obj, TestObj): |
| 686 |
if user.username == "test2": |
| 687 |
return True |
| 688 |
elif user.is_anonymous and perm == "anon": |
| 689 |
return True |
| 690 |
elif not user.is_active and perm == "inactive": |
| 691 |
return True |
| 692 |
return False |
| 693 |
|
| 694 |
async def ahas_perm(self, user, perm, obj=None): |
| 695 |
return self.has_perm(user, perm, obj) |
| 696 |
|
| 697 |
def has_module_perms(self, user, app_label): |
| 698 |
return (user.is_anonymous or user.is_active) and app_label == "app1" |
| 699 |
|
| 700 |
async def ahas_module_perms(self, user, app_label): |
| 701 |
return self.has_module_perms(user, app_label) |
| 702 |
|
| 703 |
def get_all_permissions(self, user, obj=None): |
| 704 |
if not obj: |
| 705 |
return [] # We only support row level perms |
| 706 |
|
| 707 |
if not isinstance(obj, TestObj): |
| 708 |
return ["none"] |
| 709 |
|
| 710 |
if user.is_anonymous: |
| 711 |
return ["anon"] |
| 712 |
if user.username == "test2": |
| 713 |
return ["simple", "advanced"] |
| 714 |
else: |
| 715 |
return ["simple"] |
| 716 |
|
| 717 |
async def aget_all_permissions(self, user, obj=None): |
| 718 |
return self.get_all_permissions(user, obj) |
| 719 |
|
| 720 |
def get_group_permissions(self, user, obj=None): |
| 721 |
if not obj: |
| 722 |
return # We only support row level perms |
| 723 |
|
| 724 |
if not isinstance(obj, TestObj): |
| 725 |
return ["none"] |
| 726 |
|
| 727 |
if "test_group" in [group.name for group in user.groups.all()]: |
| 728 |
return ["group_perm"] |
| 729 |
else: |
| 730 |
return ["none"] |
| 731 |
|
| 732 |
|
| 733 |
@modify_settings( |
| 734 |
AUTHENTICATION_BACKENDS={ |
| 735 |
"append": "auth_tests.test_auth_backends.SimpleRowlevelBackend", |
| 736 |
} |
| 737 |
) |
| 738 |
class RowlevelBackendTest(TestCase): |
| 739 |
""" |
| 740 |
Tests for auth backend that supports object level permissions |
| 741 |
""" |
| 742 |
|
| 743 |
@classmethod |
| 744 |
def setUpTestData(cls): |
| 745 |
cls.user1 = User.objects.create_user("test", "[email protected]", "test") |
| 746 |
cls.user2 = User.objects.create_user("test2", "[email protected]", "test") |
| 747 |
cls.user3 = User.objects.create_user("test3", "[email protected]", "test") |
| 748 |
|
| 749 |
def tearDown(self): |
| 750 |
# The get_group_permissions test messes with ContentTypes, which will |
| 751 |
# be cached; flush the cache to ensure there are no side effects |
| 752 |
# Refs #14975, #14925 |
| 753 |
ContentType.objects.clear_cache() |
| 754 |
|
| 755 |
def test_has_perm(self): |
| 756 |
self.assertIs(self.user1.has_perm("perm", TestObj()), False) |
| 757 |
self.assertIs(self.user2.has_perm("perm", TestObj()), True) |
| 758 |
self.assertIs(self.user2.has_perm("perm"), False) |
| 759 |
self.assertIs(self.user2.has_perms(["simple", "advanced"], TestObj()), True) |
| 760 |
self.assertIs(self.user3.has_perm("perm", TestObj()), False) |
| 761 |
self.assertIs(self.user3.has_perm("anon", TestObj()), False) |
| 762 |
self.assertIs(self.user3.has_perms(["simple", "advanced"], TestObj()), False) |
| 763 |
|
| 764 |
def test_get_all_permissions(self): |
| 765 |
self.assertEqual(self.user1.get_all_permissions(TestObj()), {"simple"}) |
| 766 |
self.assertEqual( |
| 767 |
self.user2.get_all_permissions(TestObj()), {"simple", "advanced"} |
| 768 |
) |
| 769 |
self.assertEqual(self.user2.get_all_permissions(), set()) |
| 770 |
|
| 771 |
def test_get_group_permissions(self): |
| 772 |
group = Group.objects.create(name="test_group") |
| 773 |
self.user3.groups.add(group) |
| 774 |
self.assertEqual(self.user3.get_group_permissions(TestObj()), {"group_perm"}) |
| 775 |
|
| 776 |
|
| 777 |
@override_settings( |
| 778 |
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleRowlevelBackend"], |
| 779 |
) |
| 780 |
class AnonymousUserBackendTest(SimpleTestCase): |
| 781 |
""" |
| 782 |
Tests for AnonymousUser delegating to backend. |
| 783 |
""" |
| 784 |
|
| 785 |
def setUp(self): |
| 786 |
self.user1 = AnonymousUser() |
| 787 |
|
| 788 |
def test_has_perm(self): |
| 789 |
self.assertIs(self.user1.has_perm("perm", TestObj()), False) |
| 790 |
self.assertIs(self.user1.has_perm("anon", TestObj()), True) |
| 791 |
|
| 792 |
async def test_ahas_perm(self): |
| 793 |
self.assertIs(await self.user1.ahas_perm("perm", TestObj()), False) |
| 794 |
self.assertIs(await self.user1.ahas_perm("anon", TestObj()), True) |
| 795 |
|
| 796 |
def test_has_perms(self): |
| 797 |
self.assertIs(self.user1.has_perms(["anon"], TestObj()), True) |
| 798 |
self.assertIs(self.user1.has_perms(["anon", "perm"], TestObj()), False) |
| 799 |
|
| 800 |
async def test_ahas_perms(self): |
| 801 |
self.assertIs(await self.user1.ahas_perms(["anon"], TestObj()), True) |
| 802 |
self.assertIs(await self.user1.ahas_perms(["anon", "perm"], TestObj()), False) |
| 803 |
|
| 804 |
def test_has_perms_perm_list_invalid(self): |
| 805 |
msg = "perm_list must be an iterable of permissions." |
| 806 |
with self.assertRaisesMessage(ValueError, msg): |
| 807 |
self.user1.has_perms("perm") |
| 808 |
with self.assertRaisesMessage(ValueError, msg): |
| 809 |
self.user1.has_perms(object()) |
| 810 |
|
| 811 |
async def test_ahas_perms_perm_list_invalid(self): |
| 812 |
msg = "perm_list must be an iterable of permissions." |
| 813 |
with self.assertRaisesMessage(ValueError, msg): |
| 814 |
await self.user1.ahas_perms("perm") |
| 815 |
with self.assertRaisesMessage(ValueError, msg): |
| 816 |
await self.user1.ahas_perms(object()) |
| 817 |
|
| 818 |
def test_has_module_perms(self): |
| 819 |
self.assertIs(self.user1.has_module_perms("app1"), True) |
| 820 |
self.assertIs(self.user1.has_module_perms("app2"), False) |
| 821 |
|
| 822 |
async def test_ahas_module_perms(self): |
| 823 |
self.assertIs(await self.user1.ahas_module_perms("app1"), True) |
| 824 |
self.assertIs(await self.user1.ahas_module_perms("app2"), False) |
| 825 |
|
| 826 |
def test_get_all_permissions(self): |
| 827 |
self.assertEqual(self.user1.get_all_permissions(TestObj()), {"anon"}) |
| 828 |
|
| 829 |
async def test_aget_all_permissions(self): |
| 830 |
self.assertEqual(await self.user1.aget_all_permissions(TestObj()), {"anon"}) |
| 831 |
|
| 832 |
|
| 833 |
@override_settings(AUTHENTICATION_BACKENDS=[]) |
| 834 |
class NoBackendsTest(TestCase): |
| 835 |
""" |
| 836 |
An appropriate error is raised if no auth backends are provided. |
| 837 |
""" |
| 838 |
|
| 839 |
@classmethod |
| 840 |
def setUpTestData(cls): |
| 841 |
cls.user = User.objects.create_user("test", "[email protected]", "test") |
| 842 |
|
| 843 |
def test_raises_exception(self): |
| 844 |
msg = ( |
| 845 |
"No authentication backends have been defined. " |
| 846 |
"Does AUTHENTICATION_BACKENDS contain anything?" |
| 847 |
) |
| 848 |
with self.assertRaisesMessage(ImproperlyConfigured, msg): |
| 849 |
self.user.has_perm(("perm", TestObj())) |
| 850 |
|
| 851 |
async def test_araises_exception(self): |
| 852 |
msg = ( |
| 853 |
"No authentication backends have been defined. " |
| 854 |
"Does AUTHENTICATION_BACKENDS contain anything?" |
| 855 |
) |
| 856 |
with self.assertRaisesMessage(ImproperlyConfigured, msg): |
| 857 |
await self.user.ahas_perm(("perm", TestObj())) |
| 858 |
|
| 859 |
|
| 860 |
@override_settings( |
| 861 |
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.SimpleRowlevelBackend"] |
| 862 |
) |
| 863 |
class InActiveUserBackendTest(TestCase): |
| 864 |
""" |
| 865 |
Tests for an inactive user |
| 866 |
""" |
| 867 |
|
| 868 |
@classmethod |
| 869 |
def setUpTestData(cls): |
| 870 |
cls.user1 = User.objects.create_user("test", "[email protected]", "test") |
| 871 |
cls.user1.is_active = False |
| 872 |
cls.user1.save() |
| 873 |
|
| 874 |
def test_has_perm(self): |
| 875 |
self.assertIs(self.user1.has_perm("perm", TestObj()), False) |
| 876 |
self.assertIs(self.user1.has_perm("inactive", TestObj()), True) |
| 877 |
|
| 878 |
def test_has_module_perms(self): |
| 879 |
self.assertIs(self.user1.has_module_perms("app1"), False) |
| 880 |
self.assertIs(self.user1.has_module_perms("app2"), False) |
| 881 |
|
| 882 |
|
| 883 |
class PermissionDeniedBackend: |
| 884 |
""" |
| 885 |
Always raises PermissionDenied in `authenticate`, `has_perm` and `has_module_perms`. |
| 886 |
""" |
| 887 |
|
| 888 |
def authenticate(self, request, username=None, password=None): |
| 889 |
raise PermissionDenied |
| 890 |
|
| 891 |
async def aauthenticate(self, request, username=None, password=None): |
| 892 |
raise PermissionDenied |
| 893 |
|
| 894 |
def has_perm(self, user_obj, perm, obj=None): |
| 895 |
raise PermissionDenied |
| 896 |
|
| 897 |
async def ahas_perm(self, user_obj, perm, obj=None): |
| 898 |
raise PermissionDenied |
| 899 |
|
| 900 |
def has_module_perms(self, user_obj, app_label): |
| 901 |
raise PermissionDenied |
| 902 |
|
| 903 |
async def ahas_module_perms(self, user_obj, app_label): |
| 904 |
raise PermissionDenied |
| 905 |
|
| 906 |
|
| 907 |
class PermissionDeniedBackendTest(TestCase): |
| 908 |
""" |
| 909 |
Other backends are not checked once a backend raises PermissionDenied |
| 910 |
""" |
| 911 |
|
| 912 |
backend = "auth_tests.test_auth_backends.PermissionDeniedBackend" |
| 913 |
|
| 914 |
@classmethod |
| 915 |
def setUpTestData(cls): |
| 916 |
cls.user1 = User.objects.create_user("test", "[email protected]", "test") |
| 917 |
|
| 918 |
def setUp(self): |
| 919 |
self.user_login_failed = [] |
| 920 |
signals.user_login_failed.connect(self.user_login_failed_listener) |
| 921 |
self.addCleanup( |
| 922 |
signals.user_login_failed.disconnect, self.user_login_failed_listener |
| 923 |
) |
| 924 |
|
| 925 |
def user_login_failed_listener(self, sender, credentials, **kwargs): |
| 926 |
self.user_login_failed.append(credentials) |
| 927 |
|
| 928 |
@modify_settings(AUTHENTICATION_BACKENDS={"prepend": backend}) |
| 929 |
def test_permission_denied(self): |
| 930 |
"user is not authenticated after a backend raises permission denied #2550" |
| 931 |
self.assertIsNone(authenticate(username="test", password="test")) |
| 932 |
# user_login_failed signal is sent. |
| 933 |
self.assertEqual( |
| 934 |
self.user_login_failed, |
| 935 |
[{"password": "********************", "username": "test"}], |
| 936 |
) |
| 937 |
|
| 938 |
@modify_settings(AUTHENTICATION_BACKENDS={"prepend": backend}) |
| 939 |
async def test_aauthenticate_permission_denied(self): |
| 940 |
self.assertIsNone(await aauthenticate(username="test", password="test")) |
| 941 |
# user_login_failed signal is sent. |
| 942 |
self.assertEqual( |
| 943 |
self.user_login_failed, |
| 944 |
[{"password": "********************", "username": "test"}], |
| 945 |
) |
| 946 |
|
| 947 |
@modify_settings(AUTHENTICATION_BACKENDS={"append": backend}) |
| 948 |
def test_authenticates(self): |
| 949 |
self.assertEqual(authenticate(username="test", password="test"), self.user1) |
| 950 |
|
| 951 |
@modify_settings(AUTHENTICATION_BACKENDS={"append": backend}) |
| 952 |
async def test_aauthenticate(self): |
| 953 |
self.assertEqual( |
| 954 |
await aauthenticate(username="test", password="test"), self.user1 |
| 955 |
) |
| 956 |
|
| 957 |
@modify_settings(AUTHENTICATION_BACKENDS={"prepend": backend}) |
| 958 |
def test_has_perm_denied(self): |
| 959 |
content_type = ContentType.objects.get_for_model(Group) |
| 960 |
perm = Permission.objects.create( |
| 961 |
name="test", content_type=content_type, codename="test" |
| 962 |
) |
| 963 |
self.user1.user_permissions.add(perm) |
| 964 |
|
| 965 |
self.assertIs(self.user1.has_perm("auth.test"), False) |
| 966 |
self.assertIs(self.user1.has_module_perms("auth"), False) |
| 967 |
|
| 968 |
@modify_settings(AUTHENTICATION_BACKENDS={"prepend": backend}) |
| 969 |
async def test_ahas_perm_denied(self): |
| 970 |
content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) |
| 971 |
perm = await Permission.objects.acreate( |
| 972 |
name="test", content_type=content_type, codename="test" |
| 973 |
) |
| 974 |
await self.user1.user_permissions.aadd(perm) |
| 975 |
|
| 976 |
self.assertIs(await self.user1.ahas_perm("auth.test"), False) |
| 977 |
self.assertIs(await self.user1.ahas_module_perms("auth"), False) |
| 978 |
|
| 979 |
@modify_settings(AUTHENTICATION_BACKENDS={"append": backend}) |
| 980 |
def test_has_perm(self): |
| 981 |
content_type = ContentType.objects.get_for_model(Group) |
| 982 |
perm = Permission.objects.create( |
| 983 |
name="test", content_type=content_type, codename="test" |
| 984 |
) |
| 985 |
self.user1.user_permissions.add(perm) |
| 986 |
|
| 987 |
self.assertIs(self.user1.has_perm("auth.test"), True) |
| 988 |
self.assertIs(self.user1.has_module_perms("auth"), True) |
| 989 |
|
| 990 |
@modify_settings(AUTHENTICATION_BACKENDS={"append": backend}) |
| 991 |
async def test_ahas_perm(self): |
| 992 |
content_type = await sync_to_async(ContentType.objects.get_for_model)(Group) |
| 993 |
perm = await Permission.objects.acreate( |
| 994 |
name="test", content_type=content_type, codename="test" |
| 995 |
) |
| 996 |
await self.user1.user_permissions.aadd(perm) |
| 997 |
|
| 998 |
self.assertIs(await self.user1.ahas_perm("auth.test"), True) |
| 999 |
self.assertIs(await self.user1.ahas_module_perms("auth"), True) |
| 1000 |
|
| 1001 |
|
| 1002 |
class NewModelBackend(ModelBackend): |
| 1003 |
pass |
| 1004 |
|
| 1005 |
|
| 1006 |
class ChangedBackendSettingsTest(TestCase): |
| 1007 |
""" |
| 1008 |
Tests for changes in the settings.AUTHENTICATION_BACKENDS |
| 1009 |
""" |
| 1010 |
|
| 1011 |
backend = "auth_tests.test_auth_backends.NewModelBackend" |
| 1012 |
|
| 1013 |
TEST_USERNAME = "test_user" |
| 1014 |
TEST_PASSWORD = "test_password" |
| 1015 |
TEST_EMAIL = "[email protected]" |
| 1016 |
|
| 1017 |
@classmethod |
| 1018 |
def setUpTestData(cls): |
| 1019 |
User.objects.create_user(cls.TEST_USERNAME, cls.TEST_EMAIL, cls.TEST_PASSWORD) |
| 1020 |
|
| 1021 |
@override_settings(AUTHENTICATION_BACKENDS=[backend]) |
| 1022 |
def test_changed_backend_settings(self): |
| 1023 |
""" |
| 1024 |
Removing a backend configured in AUTHENTICATION_BACKENDS makes already |
| 1025 |
logged-in users disconnect. |
| 1026 |
""" |
| 1027 |
# Get a session for the test user |
| 1028 |
self.assertTrue( |
| 1029 |
self.client.login( |
| 1030 |
username=self.TEST_USERNAME, |
| 1031 |
password=self.TEST_PASSWORD, |
| 1032 |
) |
| 1033 |
) |
| 1034 |
# Prepare a request object |
| 1035 |
request = HttpRequest() |
| 1036 |
request.session = self.client.session |
| 1037 |
# Remove NewModelBackend |
| 1038 |
with self.settings( |
| 1039 |
AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.ModelBackend"] |
| 1040 |
): |
| 1041 |
# Get the user from the request |
| 1042 |
user = get_user(request) |
| 1043 |
|
| 1044 |
# Assert that the user retrieval is successful and the user is |
| 1045 |
# anonymous as the backend is not longer available. |
| 1046 |
self.assertIsNotNone(user) |
| 1047 |
self.assertTrue(user.is_anonymous) |
| 1048 |
|
| 1049 |
|
| 1050 |
class TypeErrorBackend: |
| 1051 |
""" |
| 1052 |
Always raises TypeError. |
| 1053 |
""" |
| 1054 |
|
| 1055 |
@sensitive_variables("password") |
| 1056 |
def authenticate(self, request, username=None, password=None): |
| 1057 |
raise TypeError |
| 1058 |
|
| 1059 |
@sensitive_variables("password") |
| 1060 |
async def aauthenticate(self, request, username=None, password=None): |
| 1061 |
raise TypeError |
| 1062 |
|
| 1063 |
|
| 1064 |
class TypeErrorValidator: |
| 1065 |
""" |
| 1066 |
Always raises a TypeError. |
| 1067 |
""" |
| 1068 |
|
| 1069 |
def validate(self, password=None, user=None): |
| 1070 |
raise TypeError |
| 1071 |
|
| 1072 |
|
| 1073 |
class SkippedBackend: |
| 1074 |
def authenticate(self): |
| 1075 |
# Doesn't accept any credentials so is skipped by authenticate(). |
| 1076 |
pass |
| 1077 |
|
| 1078 |
|
| 1079 |
class SkippedBackendWithDecoratedMethod: |
| 1080 |
@sensitive_variables() |
| 1081 |
def authenticate(self): |
| 1082 |
pass |
| 1083 |
|
| 1084 |
|
| 1085 |
class AuthenticateTests(TestCase): |
| 1086 |
@classmethod |
| 1087 |
def setUpTestData(cls): |
| 1088 |
cls.user1 = User.objects.create_user("test", "[email protected]", "test") |
| 1089 |
|
| 1090 |
def setUp(self): |
| 1091 |
self.sensitive_password = "mypassword" |
| 1092 |
|
| 1093 |
@override_settings( |
| 1094 |
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.TypeErrorBackend"] |
| 1095 |
) |
| 1096 |
def test_type_error_raised(self): |
| 1097 |
"""A TypeError within a backend is propagated properly (#18171).""" |
| 1098 |
with self.assertRaises(TypeError): |
| 1099 |
authenticate(username="test", password="test") |
| 1100 |
|
| 1101 |
@override_settings( |
| 1102 |
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.TypeErrorBackend"] |
| 1103 |
) |
| 1104 |
def test_authenticate_sensitive_variables(self): |
| 1105 |
try: |
| 1106 |
authenticate(username="testusername", password=self.sensitive_password) |
| 1107 |
except TypeError: |
| 1108 |
exc_info = sys.exc_info() |
| 1109 |
rf = RequestFactory() |
| 1110 |
response = technical_500_response(rf.get("/"), *exc_info) |
| 1111 |
self.assertNotContains(response, self.sensitive_password, status_code=500) |
| 1112 |
self.assertContains(response, "TypeErrorBackend", status_code=500) |
| 1113 |
self.assertContains( |
| 1114 |
response, |
| 1115 |
'<tr><td>credentials</td><td class="code">' |
| 1116 |
"<pre>'********************'</pre></td></tr>", |
| 1117 |
html=True, |
| 1118 |
status_code=500, |
| 1119 |
) |
| 1120 |
|
| 1121 |
@override_settings( |
| 1122 |
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.TypeErrorBackend"] |
| 1123 |
) |
| 1124 |
async def test_aauthenticate_sensitive_variables(self): |
| 1125 |
try: |
| 1126 |
await aauthenticate( |
| 1127 |
username="testusername", password=self.sensitive_password |
| 1128 |
) |
| 1129 |
except TypeError: |
| 1130 |
exc_info = sys.exc_info() |
| 1131 |
rf = RequestFactory() |
| 1132 |
response = technical_500_response(rf.get("/"), *exc_info) |
| 1133 |
self.assertNotContains(response, self.sensitive_password, status_code=500) |
| 1134 |
self.assertContains(response, "TypeErrorBackend", status_code=500) |
| 1135 |
self.assertContains( |
| 1136 |
response, |
| 1137 |
'<tr><td>credentials</td><td class="code">' |
| 1138 |
"<pre>'********************'</pre></td></tr>", |
| 1139 |
html=True, |
| 1140 |
status_code=500, |
| 1141 |
) |
| 1142 |
|
| 1143 |
def test_clean_credentials_sensitive_variables(self): |
| 1144 |
try: |
| 1145 |
# Passing in a list to cause an exception |
| 1146 |
_clean_credentials([1, self.sensitive_password]) |
| 1147 |
except TypeError: |
| 1148 |
exc_info = sys.exc_info() |
| 1149 |
rf = RequestFactory() |
| 1150 |
response = technical_500_response(rf.get("/"), *exc_info) |
| 1151 |
self.assertNotContains(response, self.sensitive_password, status_code=500) |
| 1152 |
self.assertContains( |
| 1153 |
response, |
| 1154 |
'<tr><td>credentials</td><td class="code">' |
| 1155 |
"<pre>'********************'</pre></td></tr>", |
| 1156 |
html=True, |
| 1157 |
status_code=500, |
| 1158 |
) |
| 1159 |
|
| 1160 |
@override_settings( |
| 1161 |
ROOT_URLCONF="django.contrib.auth.urls", |
| 1162 |
AUTHENTICATION_BACKENDS=["auth_tests.test_auth_backends.TypeErrorBackend"], |
| 1163 |
) |
| 1164 |
def test_login_process_sensitive_variables(self): |
| 1165 |
try: |
| 1166 |
self.client.post( |
| 1167 |
reverse("login"), |
| 1168 |
dict(username="testusername", password=self.sensitive_password), |
| 1169 |
) |
| 1170 |
except TypeError: |
| 1171 |
exc_info = sys.exc_info() |
| 1172 |
|
| 1173 |
rf = RequestFactory() |
| 1174 |
with patch("django.views.debug.ExceptionReporter", FilteredExceptionReporter): |
| 1175 |
response = technical_500_response(rf.get("/"), *exc_info) |
| 1176 |
|
| 1177 |
self.assertNotContains(response, self.sensitive_password, status_code=500) |
| 1178 |
self.assertContains(response, "TypeErrorBackend", status_code=500) |
| 1179 |
|
| 1180 |
# AuthenticationForm.clean(). |
| 1181 |
self.assertContains( |
| 1182 |
response, |
| 1183 |
'<tr><td>password</td><td class="code">' |
| 1184 |
"<pre>'********************'</pre></td></tr>", |
| 1185 |
html=True, |
| 1186 |
status_code=500, |
| 1187 |
) |
| 1188 |
|
| 1189 |
def test_setpasswordform_validate_passwords_sensitive_variables(self): |
| 1190 |
password_form = SetPasswordForm(AnonymousUser()) |
| 1191 |
password_form.cleaned_data = { |
| 1192 |
"password1": self.sensitive_password, |
| 1193 |
"password2": self.sensitive_password + "2", |
| 1194 |
} |
| 1195 |
try: |
| 1196 |
password_form.validate_passwords() |
| 1197 |
except ValueError: |
| 1198 |
exc_info = sys.exc_info() |
| 1199 |
|
| 1200 |
rf = RequestFactory() |
| 1201 |
response = technical_500_response(rf.get("/"), *exc_info) |
| 1202 |
self.assertNotContains(response, self.sensitive_password, status_code=500) |
| 1203 |
self.assertNotContains(response, self.sensitive_password + "2", status_code=500) |
| 1204 |
|
| 1205 |
self.assertContains( |
| 1206 |
response, |
| 1207 |
'<tr><td>password1</td><td class="code">' |
| 1208 |
"<pre>'********************'</pre></td></tr>", |
| 1209 |
html=True, |
| 1210 |
status_code=500, |
| 1211 |
) |
| 1212 |
|
| 1213 |
self.assertContains( |
| 1214 |
response, |
| 1215 |
'<tr><td>password2</td><td class="code">' |
| 1216 |
"<pre>'********************'</pre></td></tr>", |
| 1217 |
html=True, |
| 1218 |
status_code=500, |
| 1219 |
) |
| 1220 |
|
| 1221 |
@override_settings( |
| 1222 |
AUTH_PASSWORD_VALIDATORS=[ |
| 1223 |
{"NAME": __name__ + ".TypeErrorValidator"}, |
| 1224 |
] |
| 1225 |
) |
| 1226 |
def test_setpasswordform_validate_password_for_user_sensitive_variables(self): |
| 1227 |
password_form = SetPasswordForm(AnonymousUser()) |
| 1228 |
password_form.cleaned_data = {"password2": self.sensitive_password} |
| 1229 |
try: |
| 1230 |
password_form.validate_password_for_user(AnonymousUser()) |
| 1231 |
except TypeError: |
| 1232 |
exc_info = sys.exc_info() |
| 1233 |
|
| 1234 |
rf = RequestFactory() |
| 1235 |
response = technical_500_response(rf.get("/"), *exc_info) |
| 1236 |
self.assertNotContains(response, self.sensitive_password, status_code=500) |
| 1237 |
|
| 1238 |
self.assertContains( |
| 1239 |
response, |
| 1240 |
'<tr><td>password</td><td class="code">' |
| 1241 |
"<pre>'********************'</pre></td></tr>", |
| 1242 |
html=True, |
| 1243 |
status_code=500, |
| 1244 |
) |
| 1245 |
|
| 1246 |
def test_passwordchangeform_clean_old_password_sensitive_variables(self): |
| 1247 |
password_form = PasswordChangeForm(User()) |
| 1248 |
password_form.cleaned_data = {"old_password": self.sensitive_password} |
| 1249 |
password_form.error_messages = None |
| 1250 |
try: |
| 1251 |
password_form.clean_old_password() |
| 1252 |
except TypeError: |
| 1253 |
exc_info = sys.exc_info() |
| 1254 |
|
| 1255 |
rf = RequestFactory() |
| 1256 |
response = technical_500_response(rf.get("/"), *exc_info) |
| 1257 |
self.assertNotContains(response, self.sensitive_password, status_code=500) |
| 1258 |
|
| 1259 |
self.assertContains( |
| 1260 |
response, |
| 1261 |
'<tr><td>old_password</td><td class="code">' |
| 1262 |
"<pre>'********************'</pre></td></tr>", |
| 1263 |
html=True, |
| 1264 |
status_code=500, |
| 1265 |
) |
| 1266 |
|
| 1267 |
@override_settings( |
| 1268 |
AUTHENTICATION_BACKENDS=( |
| 1269 |
"auth_tests.test_auth_backends.SkippedBackend", |
| 1270 |
"django.contrib.auth.backends.ModelBackend", |
| 1271 |
) |
| 1272 |
) |
| 1273 |
def test_skips_backends_without_arguments(self): |
| 1274 |
""" |
| 1275 |
A backend (SkippedBackend) is ignored if it doesn't accept the |
| 1276 |
credentials as arguments. |
| 1277 |
""" |
| 1278 |
self.assertEqual(authenticate(username="test", password="test"), self.user1) |
| 1279 |
|
| 1280 |
@override_settings( |
| 1281 |
AUTHENTICATION_BACKENDS=( |
| 1282 |
"auth_tests.test_auth_backends.SkippedBackendWithDecoratedMethod", |
| 1283 |
"django.contrib.auth.backends.ModelBackend", |
| 1284 |
) |
| 1285 |
) |
| 1286 |
def test_skips_backends_with_decorated_method(self): |
| 1287 |
self.assertEqual(authenticate(username="test", password="test"), self.user1) |
| 1288 |
|
| 1289 |
@unittest.skipUnless(PY314, "Deferred annotations are Python 3.14+ only") |
| 1290 |
@override_settings( |
| 1291 |
AUTHENTICATION_BACKENDS=[ |
| 1292 |
"auth_tests.test_auth_backends.AnnotatedBackend", |
| 1293 |
], |
| 1294 |
) |
| 1295 |
def test_backend_uses_deferred_annotations(self): |
| 1296 |
class AnnotatedBackend: |
| 1297 |
invariant_user = self.user1 |
| 1298 |
|
| 1299 |
def authenticate( |
| 1300 |
self, |
| 1301 |
request: HttpRequest, |
| 1302 |
username: AnnotatedUsername, |
| 1303 |
password: AnnotatedPassword, |
| 1304 |
) -> User | None: |
| 1305 |
return self.invariant_user |
| 1306 |
|
| 1307 |
with unittest.mock.patch( |
| 1308 |
"django.contrib.auth.import_string", return_value=AnnotatedBackend |
| 1309 |
): |
| 1310 |
self.assertEqual(authenticate(username="test", password="test"), self.user1) |
| 1311 |
|
| 1312 |
|
| 1313 |
class ImproperlyConfiguredUserModelTest(TestCase): |
| 1314 |
""" |
| 1315 |
An exception from within get_user_model() is propagated and doesn't |
| 1316 |
raise an UnboundLocalError (#21439). |
| 1317 |
""" |
| 1318 |
|
| 1319 |
@classmethod |
| 1320 |
def setUpTestData(cls): |
| 1321 |
cls.user1 = User.objects.create_user("test", "[email protected]", "test") |
| 1322 |
|
| 1323 |
def setUp(self): |
| 1324 |
self.client.login(username="test", password="test") |
| 1325 |
|
| 1326 |
@override_settings(AUTH_USER_MODEL="thismodel.doesntexist") |
| 1327 |
def test_does_not_shadow_exception(self): |
| 1328 |
# Prepare a request object |
| 1329 |
request = HttpRequest() |
| 1330 |
request.session = self.client.session |
| 1331 |
|
| 1332 |
msg = ( |
| 1333 |
"AUTH_USER_MODEL refers to model 'thismodel.doesntexist' " |
| 1334 |
"that has not been installed" |
| 1335 |
) |
| 1336 |
with self.assertRaisesMessage(ImproperlyConfigured, msg): |
| 1337 |
get_user(request) |
| 1338 |
|
| 1339 |
|
| 1340 |
class ImportedModelBackend(ModelBackend): |
| 1341 |
pass |
| 1342 |
|
| 1343 |
|
| 1344 |
class CustomModelBackend(ModelBackend): |
| 1345 |
pass |
| 1346 |
|
| 1347 |
|
| 1348 |
class OtherModelBackend(ModelBackend): |
| 1349 |
pass |
| 1350 |
|
| 1351 |
|
| 1352 |
class ImportedBackendTests(TestCase): |
| 1353 |
""" |
| 1354 |
#23925 - The backend path added to the session should be the same |
| 1355 |
as the one defined in AUTHENTICATION_BACKENDS setting. |
| 1356 |
""" |
| 1357 |
|
| 1358 |
backend = "auth_tests.backend_alias.ImportedModelBackend" |
| 1359 |
|
| 1360 |
@override_settings(AUTHENTICATION_BACKENDS=[backend]) |
| 1361 |
def test_backend_path(self): |
| 1362 |
username = "username" |
| 1363 |
password = "password" |
| 1364 |
User.objects.create_user(username, "email", password) |
| 1365 |
self.assertTrue(self.client.login(username=username, password=password)) |
| 1366 |
request = HttpRequest() |
| 1367 |
request.session = self.client.session |
| 1368 |
self.assertEqual(request.session[BACKEND_SESSION_KEY], self.backend) |
| 1369 |
|
| 1370 |
|
| 1371 |
class SelectingBackendTests(TestCase): |
| 1372 |
backend = "auth_tests.test_auth_backends.CustomModelBackend" |
| 1373 |
other_backend = "auth_tests.test_auth_backends.OtherModelBackend" |
| 1374 |
username = "username" |
| 1375 |
password = "password" |
| 1376 |
|
| 1377 |
def assertBackendInSession(self, backend): |
| 1378 |
request = HttpRequest() |
| 1379 |
request.session = self.client.session |
| 1380 |
self.assertEqual(request.session[BACKEND_SESSION_KEY], backend) |
| 1381 |
|
| 1382 |
@override_settings(AUTHENTICATION_BACKENDS=[backend]) |
| 1383 |
def test_backend_path_login_without_authenticate_single_backend(self): |
| 1384 |
user = User.objects.create_user(self.username, "email", self.password) |
| 1385 |
self.client._login(user) |
| 1386 |
self.assertBackendInSession(self.backend) |
| 1387 |
|
| 1388 |
@override_settings(AUTHENTICATION_BACKENDS=[backend, other_backend]) |
| 1389 |
def test_backend_path_login_without_authenticate_multiple_backends(self): |
| 1390 |
user = User.objects.create_user(self.username, "email", self.password) |
| 1391 |
expected_message = ( |
| 1392 |
"You have multiple authentication backends configured and " |
| 1393 |
"therefore must provide the `backend` argument or set the " |
| 1394 |
"`backend` attribute on the user." |
| 1395 |
) |
| 1396 |
with self.assertRaisesMessage(ValueError, expected_message): |
| 1397 |
self.client._login(user) |
| 1398 |
|
| 1399 |
def test_non_string_backend(self): |
| 1400 |
user = User.objects.create_user(self.username, "email", self.password) |
| 1401 |
expected_message = ( |
| 1402 |
"backend must be a dotted import path string (got " |
| 1403 |
"<class 'django.contrib.auth.backends.ModelBackend'>)." |
| 1404 |
) |
| 1405 |
with self.assertRaisesMessage(TypeError, expected_message): |
| 1406 |
self.client._login(user, backend=ModelBackend) |
| 1407 |
|
| 1408 |
@override_settings(AUTHENTICATION_BACKENDS=[backend, other_backend]) |
| 1409 |
def test_backend_path_login_with_explicit_backends(self): |
| 1410 |
user = User.objects.create_user(self.username, "email", self.password) |
| 1411 |
self.client._login(user, self.other_backend) |
| 1412 |
self.assertBackendInSession(self.other_backend) |
| 1413 |
|
| 1414 |
|
| 1415 |
@override_settings( |
| 1416 |
AUTHENTICATION_BACKENDS=["django.contrib.auth.backends.AllowAllUsersModelBackend"] |
| 1417 |
) |
| 1418 |
class AllowAllUsersModelBackendTest(TestCase): |
| 1419 |
""" |
| 1420 |
Inactive users may authenticate with the AllowAllUsersModelBackend. |
| 1421 |
""" |
| 1422 |
|
| 1423 |
user_credentials = {"username": "test", "password": "test"} |
| 1424 |
|
| 1425 |
@classmethod |
| 1426 |
def setUpTestData(cls): |
| 1427 |
cls.user = User.objects.create_user( |
| 1428 |
email="[email protected]", is_active=False, **cls.user_credentials |
| 1429 |
) |
| 1430 |
|
| 1431 |
def test_authenticate(self): |
| 1432 |
self.assertFalse(self.user.is_active) |
| 1433 |
self.assertEqual(authenticate(**self.user_credentials), self.user) |
| 1434 |
|
| 1435 |
def test_get_user(self): |
| 1436 |
self.client.force_login(self.user) |
| 1437 |
request = HttpRequest() |
| 1438 |
request.session = self.client.session |
| 1439 |
user = get_user(request) |
| 1440 |
self.assertEqual(user, self.user) |