Search code examples
djangodjango-rest-frameworkdjango-rest-auth

How to check if a user is logged in, in django token authentication?


Hi there I am currently starting a new rest api project with django. Normally when I start a new project I do a lot of planning and get a idea of how I want to build my app. For this app I want to use token authentication but can't find enough resources for this topic. Can anyone tell me these two things, how to check if a user is logged in/authenticated and how to check which user is logged in(of course with token authentication in django). Thank you in advance.

Extra info(you don't need to read this):

The reason I want to use this kind of authentication is because I don't want to use the built in django models for my user model because my User model has to have some specific fields for this web app, obviously I can work my way around this but its not very efficient so I figured I'd use token authentication.


Solution

  • If you will use rest_framework.authtoken https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication you can set in each view to check whether the user is authenticated for admission or not. For example:

    class UserList(generics.ListAPIView):
        """List all users"""
        permission_classes = [IsAuthenticated] # allowed only by authenticated
        serializer_class = UserCreateSerializer
        queryset = CustomUser.objects.all()
    

    To check which user is logged in, rest_framework.authtoken creates a table in the database that contains the token, the user and the time the token was created