2020-03-18 13:42:35 +00:00
|
|
|
# Copyright (C) 2018-2020 by BDE ENS Paris-Saclay
|
|
|
|
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
|
|
|
|
from django.contrib.contenttypes.models import ContentType
|
2020-03-20 13:43:35 +00:00
|
|
|
from permission.backends import PermissionBackend
|
2020-03-18 13:42:35 +00:00
|
|
|
from rest_framework import viewsets
|
2020-03-20 00:46:59 +00:00
|
|
|
from note_kfet.middlewares import get_current_authenticated_user
|
|
|
|
|
2020-03-18 13:42:35 +00:00
|
|
|
|
|
|
|
class ReadProtectedModelViewSet(viewsets.ModelViewSet):
|
|
|
|
"""
|
|
|
|
Protect a ModelViewSet by filtering the objects that the user cannot see.
|
|
|
|
"""
|
|
|
|
|
2020-03-20 00:46:59 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
2020-07-30 13:07:30 +00:00
|
|
|
self.model = ContentType.objects.get_for_model(self.serializer_class.Meta.model).model_class()
|
|
|
|
|
|
|
|
def get_queryset(self):
|
2020-03-20 00:46:59 +00:00
|
|
|
user = get_current_authenticated_user()
|
2020-07-30 13:07:30 +00:00
|
|
|
return self.model.objects.filter(PermissionBackend.filter_queryset(user, self.model, "view"))
|
2020-03-18 13:42:35 +00:00
|
|
|
|
|
|
|
|
|
|
|
class ReadOnlyProtectedModelViewSet(viewsets.ReadOnlyModelViewSet):
|
|
|
|
"""
|
|
|
|
Protect a ReadOnlyModelViewSet by filtering the objects that the user cannot see.
|
|
|
|
"""
|
|
|
|
|
2020-03-20 00:46:59 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
2020-07-30 13:07:30 +00:00
|
|
|
self.model = ContentType.objects.get_for_model(self.serializer_class.Meta.model).model_class()
|
|
|
|
|
|
|
|
def get_queryset(self):
|
2020-03-20 00:46:59 +00:00
|
|
|
user = get_current_authenticated_user()
|
2020-07-30 13:07:30 +00:00
|
|
|
return self.model.objects.filter(PermissionBackend.filter_queryset(user, self.model, "view"))
|