Django如何防止多个用户登录使用相同的凭据

Django如何防止多个用户登录使用相同的凭据

问题描述:

我正在使用django身份验证模块开发一个Django应用程序,并希望使用相同的用户名和密码阻止多次登录。

I am developing an Django application using django auth module and would like to prevent multiple login using the same user name and password.

它应该防止多个登录不同机器使用相同的用户名和密码。在Django中如何实现?

It should prevent multiple logins on different machines using the same user name and password. How do I achieve this in Django?

我们必须牢记以下几点:

We have to keep following things in mind:


  1. 如果用户关闭浏览器而不注销

  2. 如果会话超时


您可以尝试这样做,它会注销第一个用户并登录第二个用户。在您的应用程序目录中添加middleware.py(与模型,视图等级相同)并添加此代码。当同一个人使用多个设备时很有用。确保将其添加到您的中间件类:'myapp.middleware.UserRestrict',

You may try this, it logs out the first user and logs in the second. Add middleware.py in your app directory (same level as models, views etc) and add this code. Useful when the same person is using more than one device. Make sure you add this to your middleware classes: 'myapp.middleware.UserRestrict',

class UserRestrict(object):
    def process_request(self, request):
        """
        Checks if different session exists for user and deletes it.
        """
        if request.user.is_authenticated():
            cache = get_cache('default')
            cache_timeout = 86400
            cache_key = "user_pk_%s_restrict" % request.user.pk
            cache_value = cache.get(cache_key)

            if cache_value is not None:
                if request.session.session_key != cache_value:
                    engine = import_module(settings.SESSION_ENGINE)
                    session = engine.SessionStore(session_key=cache_value)
                    session.delete()
                    cache.set(cache_key, request.session.session_key, 
                              cache_timeout)
            else:
                cache.set(cache_key, request.session.session_key, cache_timeout)