Robert
Robert

Reputation: 545

Django restful API - get user id with token

How to obtain User ID from Django API having authentication token? Basically, I want to send authentication token and get back User id. I have tried this solution: How can I return user ID with token in Django? but it is returning token with provided username and password, which is not what I want.

Upvotes: 3

Views: 4002

Answers (3)

In the perform_create method you can assign the user to your model

class EmailViewSet(viewsets.ModelViewSet):
    authentication_classes = (TokenAuthentication)
    permission_classes = (IsAuthenticated,)
    queryset = Email.objects.all()
    serializer_class = EmailSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

Upvotes: 0

Robert
Robert

Reputation: 545

#myapp/views.py
class UserIdViewSet(viewsets.ModelViewSet):
    serializer_class = UserSerializer

    def get_queryset(self):
        return User.objects.filter(id=self.request.user.id)

#myapp/urls.py
router.register(r'api/user-id', userviews.UserIdViewSet, base_name="UserId")

sort out the problem. Basically created View set and sort this out against current user.

Upvotes: 4

Enthusiast Martin
Enthusiast Martin

Reputation: 3091

What type of authentication you use ?

If for example, you use TokenAuthentication from rest_framework, you can have a look how this class implements request authentication.

You can find there methods authenticate and authenticate_credentials and I believe that there - you will find your answer how to get the user.

Upvotes: 1

Related Questions