From f72a93a673fe349bd31a994cfb2ff8f001a4f999 Mon Sep 17 00:00:00 2001 From: imperosol Date: Tue, 20 May 2025 18:16:14 +0200 Subject: [PATCH] Make HasPerm work with ApiKeyAuth --- core/auth/api_permissions.py | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/core/auth/api_permissions.py b/core/auth/api_permissions.py index 6a28f13c..3d18529e 100644 --- a/core/auth/api_permissions.py +++ b/core/auth/api_permissions.py @@ -96,7 +96,16 @@ class HasPerm(BasePermission): self._perms = perms def has_permission(self, request: HttpRequest, controller: ControllerBase) -> bool: - return reduce(self._operator, (request.user.has_perm(p) for p in self._perms)) + # if the request has the `auth` property, + # it means that the user has been explicitly authenticated + # using a django-ninja authentication backend + # (whether it is SessionAuth or ApiKeyAuth). + # If not, this authentication has not been done, but the user may + # still be implicitly authenticated through AuthenticationMiddleware + user = request.auth if hasattr(request, "auth") else request.user + # `user` may either be a `core.User` or an `apikey.ApiClient` ; + # they are not the same model, but they both implement the `has_perm` method + return reduce(self._operator, (user.has_perm(p) for p in self._perms)) class IsRoot(BasePermission):