Django Rest Framework验证类覆盖请求.user

1qczuiv0  于 2023-03-09  发布在  Go
关注(0)|答案(1)|浏览(147)

在我的django应用中,我使用rest_framework创建了一个自定义的认证类:

from business.models import BusinessToken
from rest_framework.authtoken.models import Token
from rest_framework import authentication, exceptions

class AuthenticationMixin(authentication.BaseAuthentication):
    def authenticate(self, request):
        raw_token = request.META.get('HTTP_AUTHORIZATION')

        if not raw_token:
            return None

        token_key = raw_token.replace("Token ", "")

        user_token = Token.objects.filter(key=token_key).first()

        if user_token is not None:
            user = user_token.user
            request.user = user

            return user, None

        business_token = BusinessToken.objects.filter(key=token_key).first()

        if business_token is not None:
            business = business_token.business

            request.business = business

            user = business.owner

            request.user = user

            return business, None
        raise exceptions.AuthenticationFailed('No such user or business')

如您所见,类必须基于来自HTTP请求的令牌传递来验证用户或业务。
如果用户通过API视图中的business令牌进行身份验证,我必须以business.owner的身份访问request.user,request.business以business的身份访问www.example.com,但request.user设置为business,它在某处被覆盖。

5kgi1eie

5kgi1eie1#

二元组的第一项是用户,Django将使用它来设置用户,通过返回business,你将把它设置为request.user,因此你应该返回企业所有者,并设置(仅)request.business

class AuthenticationMixin(authentication.BaseAuthentication):
    def authenticate(self, request):
        raw_token = request.META.get('HTTP_AUTHORIZATION')

        if not raw_token:
            return None, None

        token_key = raw_token.replace('Token ', '')

        try:
            user_token = Token.objects.select_related('user').get(key=token_key)
            user = user_token.user
            return user, None
        except Token.DoesNotExist:
            pass
        try:
            business_token = BusinessToken.objects.select_related(
                'business__owner'
            ).get(key=token_key)
            business = business_token.business
            request.business = business
            return business.owner, None
        except BusinessToken.DoesNotExist:
            raise exceptions.AuthenticationFailed('No such user or business')

相关问题