How to handle token in django rest when user close the browser?

Viewed 192

I'm new to the Django rest framework and I'm tyring token auth of Django rest but I have no idea how to handle token when user directly close the browser without logout, In such a case what will be the standard way?

Also, I want to implement if a user is already logged in then redirect to the dashboard how to implement this? My views are as follow.

class LoginTemplateClass(TemplateView):
    template_name = 'index.html' 

class LoginAPI(viewsets.ModelViewSet):
    serializer_class = LoginSerializer

    def post(self,request):
        try:
            serializer = self.serializer_class(data=request.data,context={'request': request})                                           
            if serializer.is_valid():
                user = serializer.validated_data['user']
                token, created = Token.objects.get_or_create(user=user)                        
                return Response(token.key,status = 200)
            return Response(serializer.errors,status = 400)            
        except Exception as e:
            return Response({},status = 500)
1 Answers

How to handle token when user directly close the browser without logout, In such a case what will be the standard way?

Generally, you would like user to be logged in to your website, for some time. Cookies are generally used to save login information, as that will be stored on the client side.

So, how your login flow should look like

see if cookie exists -> yes, then check if token exists in your backend
     |
     -----> no, then create a token and set it on the browser cookie with a reasonable timeout.

Also, I want to implement if a user is already logged in then redirect to the dashboard how to implement this?

There are two ways to do this,

  1. you can render the html file in the return statement instead of sending http response. Use Render() function link to doc
  2. You can redirect the login function to return another view, could be indexView. Use Redirect() function link to doc
Related