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

后端 未结 4 683
旧巷少年郎
旧巷少年郎 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 10:51

    You'll need to do this with custom middleware.

    In your middleware process_request() method you will have access to the request object so you can do something like the following:

    session_key = request.session.session_key
    ip_address = request.META.get('REMOTE_ADDR', '')
    

    Now you know the IP address, so check a model you create that (roughly) would look like this:

    class SessionIPS(models.Model):
        session = models.ForeignKey(Session)
        IP = models.CharField(max_length=20)
    

    So when a session is created or deleted you will modifiy your session ip's table accordingly, and when a request comes in make sure the IP address isn't being used for another session. If if is, then return a Http404 (or something like it) from the middleware.

    A pluggable app that can show you a lot more detail (and even includes IP address in its own model) is django-tracking.

提交回复
热议问题