如何检测来自不同位置的 Django Web 应用程序的多次登录? [英] How can I detect multiple logins into a Django web application from different locations?

查看:22
本文介绍了如何检测来自不同位置的 Django Web 应用程序的多次登录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的 Django 应用程序中的个人登录,我希望一次只允许一个经过身份验证的会话.因此,如果用户通过给定的 IP 地址登录网页,并且使用相同的用户凭据从不同的 IP 地址登录,我想做一些事情(注销第一个用户或拒绝访问第二个用户.)

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, and those same user credentials are used to login from a different IP address I want to do something (either logout the first user or deny access to the second user.)

推荐答案

不确定是否仍然需要,但我想我会分享我的解决方案:

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

1) 安装 django-tracking(谢谢你的提示,Van Gale Google Maps + GeoIP 很棒!)

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

2) 添加这个中间件:

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) 确保它在 VisitorTrackingMiddleware 之后,您应该会发现当有人新登录时,以前的登录会自动中断 :)

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

这篇关于如何检测来自不同位置的 Django Web 应用程序的多次登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆