jazzband / django-rest-knox

Authentication Module for django rest auth
MIT License
1.17k stars 213 forks source link

Logout other devices while logging in on a new device #279

Open SyedAhkam opened 2 years ago

SyedAhkam commented 2 years ago

I have a question to ask. I cannot figure out how to force previously logged in sessions to logout while attempting to login on a new device for which a session does not exist.

This is specifically helpful when paired with TOKEN_LIMIT_PER_USER=1, Without implementing this behaviour, a user would be forced to login on their previously logged in device before logging into a new one (matters are worse when its about a mobile app)

How can I achieve this behavior? Is anything wrong with that idea?

SyedAhkam commented 2 years ago

I got it to work. Requires overriding the post method of KnoxLoginView.

class LoginView(KnoxLoginView):
    authentication_classes = (BasicAuthentication,)

    def post(self, request, format=None):
        if request.user.is_authenticated:
            print(f"User already authenticated but a new token was requested: {request.user.id}")

            # Delete all existing tokens for that user
            request.user.auth_token_set.all().delete()

        return super().post(request, format=format)

Perhaps exposing a pre_login signal could be a better solution?

SyedAhkam commented 2 years ago

Keeping it open for others to share ideas.

mathbouq commented 11 months ago

Where should this code be implemented? I inserted it in users/views.py, but it is never called.