Skip to content

Commit

Permalink
fixes for user role change and Api key permission (#779)
Browse files Browse the repository at this point in the history
Co-authored-by: vishnuszipstack <[email protected]>
  • Loading branch information
muhammad-ali-e and vishnuszipstack authored Oct 8, 2024
1 parent 59945e6 commit e445963
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
2 changes: 1 addition & 1 deletion backend/account_v2/authentication_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,7 +408,7 @@ def add_user_role(
)
if current_roles:
self.save_organization_user_role(
user_uid=user.user.user.id, role=current_roles[0]
user_uid=user.user.id, role=current_roles[0]
)
return current_roles[0]
else:
Expand Down
4 changes: 2 additions & 2 deletions backend/api_v2/api_key_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
from api_v2.exceptions import APINotFound, PathVariablesNotFound
from api_v2.key_helper import KeyHelper
from api_v2.models import APIKey
from api_v2.permission import IsOwnerOrOrganizationMember
from api_v2.serializers import APIKeyListSerializer, APIKeySerializer
from permissions.permission import IsOwner
from pipeline_v2.exceptions import PipelineNotFound
from pipeline_v2.pipeline_processor import PipelineProcessor
from rest_framework import serializers, viewsets
Expand All @@ -16,7 +16,7 @@

class APIKeyViewSet(viewsets.ModelViewSet):
queryset = APIKey.objects.all()
permission_classes = [IsOwner]
permission_classes = [IsOwnerOrOrganizationMember]

def get_serializer_class(self) -> serializers.Serializer:
if self.action in ["api_keys"]:
Expand Down
28 changes: 28 additions & 0 deletions backend/api_v2/permission.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
from permissions.permission import IsOwner
from utils.user_context import UserContext


class IsOwnerOrOrganizationMember(IsOwner):
"""Permission that grants access if the user is the owner or belongs to the
same organization."""

def has_object_permission(self, request, view, obj):
# Check if the user is the owner via base class logic
if super().has_object_permission(request, view, obj):
return True

# If the object has a 'created_by' field, but the user isn't the owner,
# deny access
if obj.created_by:
return False

# Support legacy API keys where 'created_by' is None by matching the
# organization ID. This allows organization members to access API keys as per
# the existing behavior.
user_organization = UserContext.get_organization()
# Check organization ID for associated `api` or `pipeline`
related_obj = getattr(obj, "api", None) or getattr(obj, "pipeline", None)
if related_obj and related_obj.organization_id == user_organization.id:
return True

return False

0 comments on commit e445963

Please sign in to comment.