Home > Enterprise >  Making use of the token generated upon log in
Making use of the token generated upon log in

Time:10-28

I have coded the API to work with my web and also generate token upon login/register from the Postman request by using knox for the token. Now I want to make use of this token that is linked to the account that is logged in to get the username so I can know which account who make the request. But I am not sure on how to use this token. Can anyone provide me with some advise on how to do this as I am quite new on this. Thanks !

views.py

@api_view(['POST'])
@authentication_classes([TokenAuthentication])
@permission_classes([IsAuthenticated])
def create_job(request):
    job = Job()
    jobserializer = JobSerializers(job, data = request.data)
    if jobserializer.is_valid():
        operation = jobserializer.save()
        data = {}
        if operation:
            data["Success"] = "Successfully created"
        return Response(data)
    return Response(jobserializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

class JobSerializers(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = ['combinedparameters', 'servicedate']

models.py

class Job(models.Model):
    owner = models.CharField(max_length = 150)    
    datetime = models.DateTimeField(default=timezone.now)
    combinedparameters = models.CharField(max_length = 1000)
    servicedate = models.CharField(max_length=10)
    def __str__(self):
            return self.servicedate

In the web browser, I get the user by request.user but I am not sure on how to make use of this token to get the user in API.

CodePudding user response:

If the user is authenticated, you can find the logged in user who is using that token, tokens are usually passed with the header with each request.

You can use a serializer for user details:

@api_view(['GET'])
def current_user(request):
    serializer = UserSerializer(request.user)
    return Response(serializer.data)

or without serializer:

@api_view(['GET'])
def current_user(request):
    user = request.user
    return Response({
        'username': user.username,
        'email': user.email
    })
  • Related