简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM