简体   繁体   中英

Django : TokenAuthentication, setting permissions on endpoints

I am using Django Rest Framework to build my API and I am quite new to it.

I set up a TokenAuthentication method, and I am now trying to filter the result of my queryset depending on this token.

Basically, I have a GET endpoint (let's say "/wallet"), and I want the /wallet endpoint to give the wallet of the specific user sending the query.

My approach was to redefine the get_queryset method in my ViewSet but I can't figure out how to get the token, and how to filter the results.

Also, anynomous users shouldn't be allowed to access that endpoint.

Here is my ViewSet, I think I need some customisation here :

class WalletViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows wallets to be viewed or edited.
    """
    queryset = Wallet.objects.filter()
    serializer_class = WalletSerializer

My approach was to redefine the get_queryset method in my ViewSet but I can't figure out how to get the token, and how to filter the results.

Django REST framework TokenAuthentication is linked to the user. Therefore I would advice that you filter against the user which should be available in the view through self.request.user

Also, anynomous users shouldn't be allowed to access that endpoint.

Check the permission section of the documentation for that.

To allow only authenticated users to access your viewset just do

class WalletViewSet(viewsets.ModelViewSet):
    queryset = Wallet.objects.filter()
    serializer_class = WalletSerializer
    permission_classes = (IsAuthenticated,)

To get the specific user wallet you could get the user from request and than get it's wallet with a simple model query. The end result beig:

class WalletViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows wallets to be viewed or edited.
    """
    queryset = Wallet.objects.filter()
    serializer_class = WalletSerializer
    permission_classes = (IsAuthenticated,)

    def retrieve(self, request, pk, format=None):
        wallet = Wallet.objects.get(user=request.user)
        Response(WalletSerializer(wallet))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM