1
votes

I'm currently using Django Rest Framework JWT for authentication on a project. I have already implemented BasicAuthentication, SessionAuthentication and JSONWebTokenAuthentication where users can request a token by using the POST method for every new session. However, I would like the token to be created (and possibly viewable in the admin section) immediately after each user is created.

I took a look at the Django Rest Framework JWT documentation where it states that tokens can be manually created using:

from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)

I tried putting this code snippet in views.py, models.py and serializers.py but I keep getting a reference error on the "user".

Any help on how to correctly implement this code snippet or an alternative method will be greatly appreciated. Thanks

1

1 Answers

0
votes

I did not follow the example on the official docs. Because I got the error with 2nd and 3rd line. My configuration raises an exception on my settings path.

I call the function directly from the library itself.

from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler

Suppose my function take 1 dictionary as an input and return the token

from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler

def create_token(platform_data: typing.Dict):
    """
    System will search from userprofile model
    Then create user instance
    :param platform_data:
    :return:
    """
    # If found `userprofile `in the system use the existing
    # If not create new `user` and `userprofile`

    platform_id = platform_data.get('id')  # Can trust this because it is primary key
    email = platform_data.get('email')  # This is user input should not trust

    userprofile_qs = UserProfile.objects.filter(platform_id=platform_id)
    if userprofile_qs.exists():
        # user exists in the system
        # return Response token
        userprofile = userprofile_qs.first()
        user = userprofile.user
    else:
        # Create user and then bind it with userprofile
        user = User.objects.create(
            username=f'poink{platform_id}',
        )
    user.email = email  # Get latest email
    user.save()
    UserProfile.objects.create(
        platform_id=platform_id,
        user=user,
    )

    payload = jwt_payload_handler(user)
    token = jwt_encode_handler(payload)
    return token

Hope get the idea from this