Source code for nlpmed_portal.management.permissions

# 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 rest_framework.permissions import BasePermission
from rest_framework.request import Request
from rest_framework.views import APIView


[docs] def has_global_permission(user, codename): """ Check if the user has a global permission based on group membership. """ return user.has_perm(codename)
[docs] def impersonate_other_users(*, hijacker, hijacked): if hijacked.pk == hijacker.pk: return False if not hijacked.is_active: return False if hijacked.is_superuser: return False if hijacker.is_superuser: return True return has_global_permission(hijacker, "management.can_impersonate")
[docs] class MethodBasePermission(BasePermission): """Enforce HTTP-method-specific permissions declared by a view. Views using this permission class must define ``required_perms``, mapping HTTP method names to Django permission codenames. """
[docs] def has_permission(self, request: Request, view: APIView) -> bool: required_perms = getattr(view, "required_perms", {}) if not required_perms: return False required_perm = required_perms.get(request.method) if not required_perm: return False return has_global_permission(user=request.user, codename=required_perm)