Django How to prevent multiple users login using the same credentials

后端 未结 3 2213
南旧
南旧 2020-12-16 04:54

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

It should prevent mult

3条回答
  •  别那么骄傲
    2020-12-16 05:17

    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)
    

提交回复
热议问题