Source code for nlpmed_portal.annotations.api.viewsets.base

# SPDX-FileCopyrightText: Copyright (C) 2026 Omid Jafari <omidjafari.com>
# SPDX-License-Identifier: AGPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from typing import TYPE_CHECKING
from typing import cast

from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from nlpmed_portal.annotations.models import Project
from nlpmed_portal.annotations.permissions import has_global_permission

if TYPE_CHECKING:
    from nlpmed_portal.users.models import User


[docs] class BaseViewSet(ModelViewSet):
[docs] def filter_queryset_by_scope( self, queryset, required_perm, project_field=None, ): user = cast("User", self.request.user) if has_global_permission( user=user, codename=required_perm, ): return queryset accessible_projects = Project.objects.filter( project_memberships_project__assignee=user, project_memberships_project__group__permissions__codename=required_perm, ) if project_field: return queryset.filter( **{ f"{project_field}__in": accessible_projects, }, ) return accessible_projects
[docs] def destroy(self, request, *args, **kwargs): serializer = self.get_serializer( self.get_object(), ) response_data = serializer.data super().destroy( request, *args, **kwargs, ) return Response( response_data, status=status.HTTP_200_OK, )