How can I detect multiple logins into a Django web application from different locations?

后端 未结 4 682
旧巷少年郎
旧巷少年郎 2020-11-27 10:37

I want to only allow one authenticated session at a time for an individual login in my Django application. So if a user is logged into the webpage on a given IP address, an

4条回答
  •  醉梦人生
    2020-11-27 11:02

    Not sure if this is still needed but thought I would share my solution:

    1) Install django-tracking (thankyou for that tip Van Gale Google Maps + GeoIP is amazing!)

    2) Add this middleware:

    from django.contrib.sessions.models import Session
    from tracking.models import Visitor
    from datetime import datetime
    
    class UserRestrictMiddleware(object):
        """
        Prevents more than one user logging in at once from two different IPs
        """
        def process_request(self, request):
            ip_address = request.META.get('REMOTE_ADDR','')
            try:
                last_login = request.user.last_login
            except:
                last_login = 0
            if unicode(last_login)==unicode(datetime.now())[:19]:
                previous_visitors = Visitor.objects.filter(user=request.user).exclude(ip_address=ip_address)
                for visitor in previous_visitors:
                    Session.objects.filter(session_key=visitor.session_key).delete()
                    visitor.user = None
                    visitor.save()
    

    3) Make sure it goes after the VisitorTrackingMiddleware and you should find previous logins are automatically bumped when someone new logs in :)

提交回复
热议问题