| 1 |
from collections.abc import Iterable |
| 2 |
from inspect import isawaitable |
| 3 |
import sys |
| 4 |
from types import GeneratorType |
| 5 |
from typing import Any |
| 6 |
import warnings |
| 7 |
|
| 8 |
# Import deprecated decorator with fallback for Python < 3.13 |
| 9 |
if sys.version_info >= (3, 13): |
| 10 |
from warnings import deprecated |
| 11 |
else: |
| 12 |
from typing_extensions import deprecated |
| 13 |
|
| 14 |
from asgiref.sync import sync_to_async |
| 15 |
|
| 16 |
try: |
| 17 |
from asgiref.sync import iscoroutinefunction |
| 18 |
except ImportError: |
| 19 |
# asgiref < 3.6, which Django < 4.2 still allows. The asynchronous path is |
| 20 |
# disabled on those versions anyway, so the stricter detector is enough. |
| 21 |
from inspect import iscoroutinefunction |
| 22 |
|
| 23 |
from django import VERSION as DJANGO_VERSION |
| 24 |
from django.conf import settings |
| 25 |
from django.contrib.auth.decorators import REDIRECT_FIELD_NAME, login_required |
| 26 |
from django.core.exceptions import ImproperlyConfigured, PermissionDenied |
| 27 |
from django.db.models import Model, QuerySet |
| 28 |
from django.http import HttpRequest, HttpResponse, HttpResponseForbidden, HttpResponseNotFound, HttpResponseRedirect |
| 29 |
|
| 30 |
from guardian.shortcuts import get_objects_for_user |
| 31 |
from guardian.utils import get_40x_or_None, get_anonymous_user, get_group_obj_perms_model, get_user_obj_perms_model |
| 32 |
|
| 33 |
# Django 4.1.2 made the response for a disallowed HTTP method awaitable, which |
| 34 |
# asynchronous views rely on. 4.1 is end of life, so 4.2 is the floor here. |
| 35 |
# Two components only: comparing django.VERSION with three is deprecated. |
| 36 |
_ASYNC_VIEWS_SUPPORTED = DJANGO_VERSION >= (4, 2) |
| 37 |
|
| 38 |
|
| 39 |
class LoginRequiredMixin: |
| 40 |
"""A login required mixin for use with class-based views. |
| 41 |
|
| 42 |
This Class is a light wrapper around the Django `login_required` decorator, |
| 43 |
function parameters are instead attributes defined on the class. |
| 44 |
|
| 45 |
Due to Python Method Resolution Order (MRO), this mixin must be added as the left |
| 46 |
most mixin of a view. |
| 47 |
|
| 48 |
Attributes: |
| 49 |
redirect_field_name (str): *Default*: `'next'` |
| 50 |
login_url (str): *Default*: `settings.LOGIN_URL` |
| 51 |
|
| 52 |
Example: |
| 53 |
```python |
| 54 |
from guardian.mixins import LoginRequiredMixin |
| 55 |
from django.views.generic import View |
| 56 |
|
| 57 |
class SecretView(LoginRequiredMixin, View): |
| 58 |
redirect_field_name = 'foobar' |
| 59 |
login_url = '/let-me-in/' |
| 60 |
|
| 61 |
def get(self, request): |
| 62 |
return HttpResponse('secret-view') |
| 63 |
``` |
| 64 |
|
| 65 |
Note: |
| 66 |
The mixin has exactly the same flow as `login_required` decorator: |
| 67 |
|
| 68 |
- If the user isn't logged in, redirect to `settings.LOGIN_URL`, passing |
| 69 |
the current absolute path in the query string. |
| 70 |
- Example: `/accounts/login/?next=/polls/3/`. |
| 71 |
|
| 72 |
- If the user is logged in, execute the view normally. |
| 73 |
The view code is free to assume the user is logged in. |
| 74 |
|
| 75 |
|
| 76 |
See Also: |
| 77 |
- [Python MRO historical reference](https://docs.python.org/3/howto/mro.html) |
| 78 |
""" |
| 79 |
|
| 80 |
redirect_field_name = REDIRECT_FIELD_NAME |
| 81 |
login_url = settings.LOGIN_URL |
| 82 |
|
| 83 |
def dispatch(self, request, *args, **kwargs): |
| 84 |
return login_required(redirect_field_name=self.redirect_field_name, login_url=self.login_url)(super().dispatch)( |
| 85 |
request, *args, **kwargs |
| 86 |
) |
| 87 |
|
| 88 |
|
| 89 |
class PermissionRequiredMixin: |
| 90 |
"""A view mixin that verifies if the current logged-in user has the specified permission. |
| 91 |
|
| 92 |
This mixin works by wrapping the `request.user.has_perm(...)` method. |
| 93 |
If a `get_object()` method is defined either manually or by including |
| 94 |
another mixin (e.g., `SingleObjectMixin`) or `self.object` is |
| 95 |
defined, then the permission will be tested against that specific instance. |
| 96 |
Alternatively, you can specify `get_permission_object()` method if `self.object` |
| 97 |
or `get_object()` does not return the object against you want to test permission |
| 98 |
|
| 99 |
The mixin does the following: |
| 100 |
|
| 101 |
- If the user isn't logged in, redirect to settings.LOGIN_URL, passing |
| 102 |
the current absolute path in the query string. |
| 103 |
- Example: /accounts/login/?next=/polls/3/. |
| 104 |
|
| 105 |
- If `raise_exception` is set to `True` a `PermissionDenied` (403) is raised |
| 106 |
instead of redirecting the user to `settings.LOGIN_URL`. |
| 107 |
|
| 108 |
- If the user is logged in, and passes the permission check, the view is executed normally. |
| 109 |
|
| 110 |
Note: |
| 111 |
Testing of a permission against a specific object instance requires an |
| 112 |
authentication backend that supports. |
| 113 |
The `guardian.backends.ObjectPermissionBackend` or a custom implementation |
| 114 |
must be listed under the list of authentication backends in your project. |
| 115 |
|
| 116 |
Attributes: |
| 117 |
permission_required (str | list[str]): permissions to check |
| 118 |
in form `"<app_label>.<permission codename>"`. |
| 119 |
Default is `None`. |
| 120 |
login_url (str): Default: `settings.LOGIN_URL` |
| 121 |
redirect_field_name (str): Default is `'next'` |
| 122 |
return_403 (bool): Returns 403 error page instead of redirecting. |
| 123 |
Default is `False`. |
| 124 |
return_404 (bool): Returns 404 error page instead of redirecting. |
| 125 |
Default is `False`. |
| 126 |
raise_exception (bool): Default is `False` |
| 127 |
permission_denied_message (str): A string to pass to the `PermissionDenied` exception. |
| 128 |
It is available in the 403 template context object as `exception`. |
| 129 |
Default is `''`. |
| 130 |
accept_global_perms (bool): Whether the mixin should first check for global perms. |
| 131 |
If none are found, proceed to check object level permissions. |
| 132 |
Default is `False`. |
| 133 |
permission_object (None | object): Object against which test the permission; |
| 134 |
if not set fallback to `self.get_permission_object()` which return `self.get_object()` |
| 135 |
or `self.object` by default. |
| 136 |
Default is `None`. |
| 137 |
any_perm (bool): Whether any of the permissions in sequence is accepted. |
| 138 |
Default is `False`. |
| 139 |
|
| 140 |
Example: |
| 141 |
```python |
| 142 |
from guardian.mixins import PermissionRequiredMixin |
| 143 |
from django.views.generic import View |
| 144 |
|
| 145 |
class SecureView(PermissionRequiredMixin, View): |
| 146 |
... |
| 147 |
permission_required = 'auth.change_user' |
| 148 |
... |
| 149 |
``` |
| 150 |
""" |
| 151 |
|
| 152 |
# default class view settings |
| 153 |
login_url: str = settings.LOGIN_URL |
| 154 |
permission_required: str | list[str] | None = None |
| 155 |
redirect_field_name: str = REDIRECT_FIELD_NAME |
| 156 |
return_403: bool = False |
| 157 |
return_404: bool = False |
| 158 |
raise_exception: bool = False |
| 159 |
object_permission_denied_message: str = "" |
| 160 |
accept_global_perms: bool = False |
| 161 |
any_perm: bool = False |
| 162 |
|
| 163 |
def get_object_permission_denied_message(self) -> str: |
| 164 |
"""Get the message to pass to the `PermissionDenied` exception. |
| 165 |
|
| 166 |
Override this method to override the object_permission_denied_message attribute. |
| 167 |
""" |
| 168 |
return self.object_permission_denied_message |
| 169 |
|
| 170 |
def get_required_permissions(self, request: HttpRequest | None = None) -> list[str]: |
| 171 |
"""Get the required permissions. |
| 172 |
|
| 173 |
Returns list of permissions in format *<app_label>.<codename>* that |
| 174 |
should be checked against *request.user* and *object*. |
| 175 |
By default, it returns a list from `permission_required` attribute. |
| 176 |
|
| 177 |
Parameters: |
| 178 |
request (HttpRequest): Original request. |
| 179 |
""" |
| 180 |
if isinstance(self.permission_required, str): |
| 181 |
perms = [self.permission_required] |
| 182 |
elif isinstance(self.permission_required, GeneratorType): |
| 183 |
# This feature will be removed in v4. (#666) |
| 184 |
warnings.warn( |
| 185 |
"Using generators for 'permission_required' attribute is deprecated and will be removed in v4. " |
| 186 |
"Use a list or tuple instead as generators can only be consumed once, " |
| 187 |
"potentially leading to security issues.", |
| 188 |
DeprecationWarning, |
| 189 |
stacklevel=2, |
| 190 |
) |
| 191 |
perms = [p for p in self.permission_required] |
| 192 |
elif isinstance(self.permission_required, Iterable): |
| 193 |
perms = [p for p in self.permission_required] |
| 194 |
else: |
| 195 |
raise ImproperlyConfigured( |
| 196 |
"'PermissionRequiredMixin' requires " |
| 197 |
"'permission_required' attribute to be set to " |
| 198 |
"'<app_label>.<permission codename>' but is set to '%s' instead" % self.permission_required |
| 199 |
) |
| 200 |
return perms |
| 201 |
|
| 202 |
def get_permission_object(self): |
| 203 |
if hasattr(self, "permission_object"): |
| 204 |
return self.permission_object |
| 205 |
return hasattr(self, "get_object") and self.get_object() or getattr(self, "object", None) |
| 206 |
|
| 207 |
def check_permissions( |
| 208 |
self, request: HttpRequest |
| 209 |
) -> HttpResponseForbidden | HttpResponseNotFound | HttpResponseRedirect | HttpResponse | None: |
| 210 |
"""Check if the user has the required permissions. |
| 211 |
|
| 212 |
Checks if `request.user` has all permissions returned by the |
| 213 |
`get_required_permissions()` method. |
| 214 |
|
| 215 |
Parameters: |
| 216 |
request (HttpRequest): The original request. |
| 217 |
""" |
| 218 |
return self._check_permissions_for_object(request, self.get_permission_object()) |
| 219 |
|
| 220 |
def _check_permissions_for_object( |
| 221 |
self, request: HttpRequest, obj: Model | Any | None |
| 222 |
) -> HttpResponseForbidden | HttpResponseNotFound | HttpResponseRedirect | HttpResponse | None: |
| 223 |
"""Run the permission check against an already resolved object. |
| 224 |
|
| 225 |
Shared by `check_permissions()` and `acheck_permissions()`. Every |
| 226 |
synchronous hook is called from here, so that the asynchronous version |
| 227 |
only needs a single thread to run all of them. |
| 228 |
""" |
| 229 |
forbidden = get_40x_or_None( |
| 230 |
request, |
| 231 |
perms=self.get_required_permissions(request), |
| 232 |
obj=obj, |
| 233 |
login_url=self.login_url, |
| 234 |
redirect_field_name=self.redirect_field_name, |
| 235 |
return_403=self.return_403, |
| 236 |
return_404=self.return_404, |
| 237 |
permission_denied_message=self.get_object_permission_denied_message(), |
| 238 |
accept_global_perms=self.accept_global_perms, |
| 239 |
any_perm=self.any_perm, |
| 240 |
) |
| 241 |
if forbidden: |
| 242 |
self.on_permission_check_fail(request, forbidden, obj=obj) |
| 243 |
if forbidden and self.raise_exception: |
| 244 |
raise PermissionDenied(self.get_object_permission_denied_message()) |
| 245 |
return forbidden |
| 246 |
|
| 247 |
def on_permission_check_fail( |
| 248 |
self, request: HttpRequest, response: HttpResponse, obj: Model | Any | None = None |
| 249 |
) -> None: |
| 250 |
"""Method called upon permission check fail. |
| 251 |
|
| 252 |
Allow subclasses to hook into the permission check failure process. |
| 253 |
By default, it does nothing and should only be overridden, if needed. |
| 254 |
|
| 255 |
Parameters: |
| 256 |
request (HttpRequest): Original request |
| 257 |
response (HttpResponse): 403 response returned by *check_permissions* method. |
| 258 |
obj (Model | Any): Object that was fetched from the view (using `get_object` |
| 259 |
method or `object` attribute, in that order). |
| 260 |
""" |
| 261 |
|
| 262 |
async def aget_permission_object(self): |
| 263 |
"""Asynchronous version of `get_permission_object()`. |
| 264 |
|
| 265 |
By default it runs the synchronous version in a thread, so existing |
| 266 |
views keep working unchanged. Override it when the object is fetched |
| 267 |
through the asynchronous ORM API: |
| 268 |
|
| 269 |
```python |
| 270 |
async def aget_permission_object(self): |
| 271 |
return await Post.objects.aget(slug=self.kwargs["slug"]) |
| 272 |
``` |
| 273 |
|
| 274 |
An asynchronous `get_permission_object()` or `get_object()` defined on |
| 275 |
the view is awaited as well. |
| 276 |
""" |
| 277 |
if iscoroutinefunction(self.get_permission_object): |
| 278 |
return await self.get_permission_object() |
| 279 |
obj = await sync_to_async(self.get_permission_object)() |
| 280 |
if isawaitable(obj): |
| 281 |
# The view defines an asynchronous `get_object()`, whose coroutine the |
| 282 |
# synchronous `get_permission_object()` returned without awaiting it and |
| 283 |
# without reaching its fallback. Await it and apply that fallback here. |
| 284 |
obj = await obj or getattr(self, "object", None) |
| 285 |
return obj |
| 286 |
|
| 287 |
async def acheck_permissions( |
| 288 |
self, request: HttpRequest |
| 289 |
) -> HttpResponseForbidden | HttpResponseNotFound | HttpResponseRedirect | HttpResponse | None: |
| 290 |
"""Asynchronous version of `check_permissions()`. |
| 291 |
|
| 292 |
Parameters: |
| 293 |
request (HttpRequest): The original request. |
| 294 |
""" |
| 295 |
obj = await self.aget_permission_object() |
| 296 |
return await sync_to_async(self._check_permissions_for_object)(request, obj) |
| 297 |
|
| 298 |
def dispatch(self, request, *args, **kwargs): |
| 299 |
self.request = request |
| 300 |
self.args = args |
| 301 |
self.kwargs = kwargs |
| 302 |
# `view_is_async` is missing when the mixin is used outside Django's `View`. |
| 303 |
if _ASYNC_VIEWS_SUPPORTED and getattr(self, "view_is_async", False): |
| 304 |
# The returned coroutine is awaited by Django's `View.as_view()` wrapper. |
| 305 |
return self.adispatch(request, *args, **kwargs) |
| 306 |
response = self.check_permissions(request) |
| 307 |
if response: |
| 308 |
return response |
| 309 |
return super().dispatch(request, *args, **kwargs) |
| 310 |
|
| 311 |
async def adispatch(self, request, *args, **kwargs): |
| 312 |
"""Asynchronous version of `dispatch()`, used when the view is asynchronous. |
| 313 |
|
| 314 |
Requires Django >= 4.2. |
| 315 |
""" |
| 316 |
response = await self.acheck_permissions(request) |
| 317 |
if response: |
| 318 |
return response |
| 319 |
return await super().dispatch(request, *args, **kwargs) |
| 320 |
|
| 321 |
|
| 322 |
class GuardianUserMixin: |
| 323 |
@staticmethod |
| 324 |
def get_anonymous(): |
| 325 |
return get_anonymous_user() |
| 326 |
|
| 327 |
def add_obj_perm(self, perm: str, obj: Model) -> Any: |
| 328 |
UserObjectPermission = get_user_obj_perms_model() |
| 329 |
return UserObjectPermission.objects.assign_perm(perm, self, obj) |
| 330 |
|
| 331 |
def del_obj_perm(self, perm: str, obj: Model) -> Any: |
| 332 |
UserObjectPermission = get_user_obj_perms_model() |
| 333 |
return UserObjectPermission.objects.remove_perm(perm, self, obj) |
| 334 |
|
| 335 |
|
| 336 |
class GuardianGroupMixin: |
| 337 |
def add_obj_perm(self, perm: str, obj: Model) -> Any: |
| 338 |
GroupObjectPermission = get_group_obj_perms_model() |
| 339 |
return GroupObjectPermission.objects.assign_perm(perm, self, obj) |
| 340 |
|
| 341 |
def del_obj_perm(self, perm: str, obj: Model) -> Any: |
| 342 |
GroupObjectPermission = get_group_obj_perms_model() |
| 343 |
return GroupObjectPermission.objects.remove_perm(perm, self, obj) |
| 344 |
|
| 345 |
|
| 346 |
class PermissionListMixin: |
| 347 |
"""A view mixin that filter a queryset by user and permission. |
| 348 |
|
| 349 |
This mixin filter object retrieved by a queryset that the |
| 350 |
logged-in user has the specified permission for. |
| 351 |
|
| 352 |
Example: |
| 353 |
```python |
| 354 |
from django.views.generic import ListView |
| 355 |
from guardian.mixins import PermissionListMixin |
| 356 |
|
| 357 |
class SecureView(PermissionListMixin, ListView): |
| 358 |
... |
| 359 |
permission_required = 'articles.view_article' |
| 360 |
... |
| 361 |
|
| 362 |
# or |
| 363 |
|
| 364 |
class SecureView(PermissionListMixin, ListView): |
| 365 |
... |
| 366 |
permission_required = 'auth.change_user' |
| 367 |
get_objects_for_user_extra_kwargs = {'use_groups': False} |
| 368 |
... |
| 369 |
``` |
| 370 |
|
| 371 |
Attributes: |
| 372 |
permission_required (str | list[str]): permissions to check |
| 373 |
in format: `"<app_label>.<permission codename>"`. |
| 374 |
Default is `None` |
| 375 |
get_objects_for_user_extra_kwargs (dict): Extra params to pass to `guardian.shortcuts.get_objects_for_user`. |
| 376 |
Default to `{}`, |
| 377 |
""" |
| 378 |
|
| 379 |
permission_required: str | list[str] | None = None |
| 380 |
# rename get_objects_for_user_kwargs to when get_get_objects_for_user_kwargs is removed |
| 381 |
get_objects_for_user_extra_kwargs: dict = {} |
| 382 |
|
| 383 |
def get_required_permissions(self, request: HttpRequest | None = None) -> list[str]: |
| 384 |
"""Get the required permissions. |
| 385 |
|
| 386 |
Returns list of permissions in format *<app_label>.<codename>* that |
| 387 |
should be checked against *request.user* and *object*. |
| 388 |
By default, it returns a list from `permission_required` attribute. |
| 389 |
|
| 390 |
Parameters: |
| 391 |
request (HttpRequest): Original request. |
| 392 |
|
| 393 |
Returns: |
| 394 |
List of the required permissions. |
| 395 |
""" |
| 396 |
if isinstance(self.permission_required, str): |
| 397 |
perms = [self.permission_required] |
| 398 |
elif isinstance(self.permission_required, GeneratorType): |
| 399 |
# This feature will be removed in v4. (#666) |
| 400 |
warnings.warn( |
| 401 |
"Using generators for 'permission_required' attribute is deprecated and will be removed in v4. " |
| 402 |
"Use a list or tuple instead as generators can only be consumed once, " |
| 403 |
"potentially leading to security issues.", |
| 404 |
DeprecationWarning, |
| 405 |
stacklevel=2, |
| 406 |
) |
| 407 |
perms = [p for p in self.permission_required] |
| 408 |
elif isinstance(self.permission_required, Iterable): |
| 409 |
perms = [p for p in self.permission_required] |
| 410 |
else: |
| 411 |
raise ImproperlyConfigured( |
| 412 |
"'PermissionRequiredMixin' requires " |
| 413 |
"'permission_required' attribute to be set to " |
| 414 |
"'<app_label>.<permission codename>' but is set to '%s' instead" % self.permission_required |
| 415 |
) |
| 416 |
return perms |
| 417 |
|
| 418 |
@deprecated( |
| 419 |
"This method is deprecated and will be removed in future versions. Use get_user_object_kwargs instead which has identical behavior." |
| 420 |
) |
| 421 |
def get_get_objects_for_user_kwargs(self, queryset: QuerySet) -> dict: |
| 422 |
"""Get kwargs to pass to `get_objects_for_user`. |
| 423 |
|
| 424 |
Returns: |
| 425 |
dict of kwargs to be passed to `get_objects_for_user`. |
| 426 |
|
| 427 |
Parameters: |
| 428 |
queryset (QuerySet): Queryset to filter. |
| 429 |
|
| 430 |
Warning: Deprecation Warning |
| 431 |
This method is deprecated and will be removed in future versions. |
| 432 |
Use `get_user_object_kwargs` instead which has identical behavior. |
| 433 |
""" |
| 434 |
return self.get_user_object_kwargs(queryset) |
| 435 |
|
| 436 |
def get_user_object_kwargs(self, queryset: QuerySet) -> dict: |
| 437 |
"""Get kwargs to pass to `get_objects_for_user`. |
| 438 |
|
| 439 |
Returns: |
| 440 |
dict of kwargs to be passed to `get_objects_for_user`. |
| 441 |
|
| 442 |
Parameters: |
| 443 |
queryset (QuerySet): Queryset to filter. |
| 444 |
""" |
| 445 |
return dict( |
| 446 |
user=self.request.user, # type: ignore[attr-defined] |
| 447 |
perms=self.get_required_permissions(self.request), # type: ignore[attr-defined] |
| 448 |
klass=queryset, |
| 449 |
**self.get_objects_for_user_extra_kwargs, |
| 450 |
) |
| 451 |
|
| 452 |
def get_queryset(self, *args, **kwargs): |
| 453 |
qs = super().get_queryset(*args, **kwargs) |
| 454 |
return get_objects_for_user(**self.get_user_object_kwargs(qs)) |