gpt4 book ai didi

django-rest-framework - 如何解决不起作用的权限类或逻辑

转载 作者:行者123 更新时间:2023-12-04 12:54:55 25 4
gpt4 key购买 nike

我在模型 View 集中有一个 permission_classes 像这样:

class MeetingViewSet(viewsets.ModelViewSet):

queryset = Meeting.objects.all()

serializer_class = MeetingSerializer
permission_classes =[IsOwner|IsCreator|IsInvited]
这是相关的模型:
class Meeting(models.Model):

TIMEZONES = tuple(zip(pytz.all_timezones, pytz.all_timezones))

title = models.CharField(max_length=255)
description = models.TextField()

# Date Time Is in UTC
date_time = models.DateTimeField()
time_zone = models.CharField(max_length=32, choices=TIMEZONES,
default='UTC')

#TODO: Convert to REMOTE_USER, Temperory integer
host = models.ForeignKey(get_user_model(),on_delete=models.CASCADE)

is_private = models.BooleanField(default=True)
is_virtual = models.BooleanField(default=True)

url = models.CharField(blank=True,max_length=100)

deleted = models.BooleanField(default=False)
time_created = models.DateTimeField(auto_now_add=True)

def __str__(self):
return '%s' % (self.title)
# TODO: Return host.username after bringup REMOTE_USER

def is_invited(self, email):
meeting = MeetingMember.objects.filter(meeting=self, email=email)
if meeting.exists():
return True
return False
IsOwner 用于所有者更新/删除/获取/发布, Iscreateor 用于方法 post 创建新对象, IsInvited 用于方法 Get 和邀请用户存在于模型中:
class IsOwner(BasePermission):


def has_object_permission(self, request, view, object):

return request.user.pk == object.host and request.user.is_authenticated

class IsCreator(BasePermission):

def has_permission(self, request ,view):

return request.method == 'POST' and request.user.is_authenticated

class IsInvited(BasePermission):

message = 'you must have been invited to see this meeting'

def has_object_permission(self,request, view,object):

return request.method == 'GET' and object.is_invited(request.user.email) and request.user.is_authenticated
并且用户必须在所有三个类中都经过身份验证,但是当我使用简单的 jwt 并使用不同的用户进行身份验证时,我仍然可以获得另一个用户创建的对象,这应该被禁止 bcs 只有所有者才能访问该对象我缺少什么?

最佳答案

学习后This Turorial ,我意识到我只需要在 has_permission 中检查身份验证,所以我像这样更改了代码并且它可以工作:

class IsOwner(BasePermission):
def has_permission(self, request, view):
if request.user.is_authenticated:
return True
return False

def has_object_permission(self, request, view, object):
if request.user == object.host:
return True
return False


class IsInvited(BasePermission):

def has_permission(self, request, view):
if request.user.is_authenticated:
return True
return False


def has_object_permission(self,request, view,object):
if object.is_invited(request.user.email):
return True
return False

关于django-rest-framework - 如何解决不起作用的权限类或逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68691842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com