How to add token in response after registering user - DRF Social OAuth2

577 Views Asked by At

I am using DRF Social OAuth2 for social authentication, it's giving me the token when I log in, but I want to return the token in response when I register a user with an email and password. How can I do that

1

There are 1 best solutions below

0
Sorin Burghiu On

We would need to see your endpoint in order to answer the question better. Here is a suggestion if you are using token auth.

from rest_framework.authtoken.models import Token

def get_token_response(user):
    token, _ = Token.objects.get_or_create(user=user)
    response = {"token": "Token " + str(token)}
    return response

And then your endpoint would look something like this (if you are using a viewset):

class UserViewSet(viewsets.ModelViewSet):

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        user = User.objects.get(id=response.data["id"])
        return Response(get_token_response(user), status=201)

My point is that you need to get the token from the database and adjust your create user endpoint (aka registration) to return it.

Hope this helps.