简体   繁体   中英

django - preventing from two clients to login as the same user

I have a login/logout module in my django app (using DRF).

it works in token authentication - when user logs in he passes a username and a password and gets a token, that can be used forever.

(I save the token in my client app). when he logs out - I delete the token from the client app.

The problem I noticed is that when one client (android app) in logged in with user1 for example (currently has the token that was achieved from the server), other clients can login as the same user (provide same username and password and get the token) - and now I have both clients logged in as user1 .

Here is the django code for getting the token:

class ObtainAuthTokenAndUser(APIView):
    throttle_classes = ()
    permission_classes = ()
    parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
    renderer_classes = (renderers.JSONRenderer,)
    serializer_class = AuthTokenSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        user_serializer = UserSerializer(user)
        return Response({'token': token.key, 'user': user_serializer.data})

obtain_auth_token_and_user = ObtainAuthTokenAndUser.as_view()

What can I do in order to prevent this situation??

In the case of another client tries to log in with a already logged in user - I want to send a "already logged in from another device" message and a 401 HTTP.

Any ideas about how to approach this?

You can simply check if any valid token is already present in the database for the same user.

token, created = Token.objects.get_or_create(user=user)

instead of above method you should use

try:
    token = Token.objects.get(user=user) // Chcck if token is present
except Token.DoesNotExist:
    token = Token.objects.create(user=user) // Create new token, no token for this user
else:
    return Response({'error': 'Already logged in', status=400})

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