mirror of
https://gitlab.crans.org/bde/nk20
synced 2024-12-23 16:02:25 +00:00
38 lines
1.4 KiB
Python
38 lines
1.4 KiB
Python
# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
from django.contrib.contenttypes.models import ContentType
|
|
from permission.backends import PermissionBackend
|
|
from rest_framework import viewsets
|
|
from note_kfet.middlewares import get_current_session
|
|
|
|
|
|
class ReadProtectedModelViewSet(viewsets.ModelViewSet):
|
|
"""
|
|
Protect a ModelViewSet by filtering the objects that the user cannot see.
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.model = ContentType.objects.get_for_model(self.serializer_class.Meta.model).model_class()
|
|
|
|
def get_queryset(self):
|
|
user = self.request.user
|
|
get_current_session().setdefault("permission_mask", 42)
|
|
return self.model.objects.filter(PermissionBackend.filter_queryset(user, self.model, "view")).distinct()
|
|
|
|
|
|
class ReadOnlyProtectedModelViewSet(viewsets.ReadOnlyModelViewSet):
|
|
"""
|
|
Protect a ReadOnlyModelViewSet by filtering the objects that the user cannot see.
|
|
"""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
super().__init__(*args, **kwargs)
|
|
self.model = ContentType.objects.get_for_model(self.serializer_class.Meta.model).model_class()
|
|
|
|
def get_queryset(self):
|
|
user = self.request.user
|
|
get_current_session().setdefault("permission_mask", 42)
|
|
return self.model.objects.filter(PermissionBackend.filter_queryset(user, self.model, "view")).distinct()
|