简体   繁体   English

如何检查用户是否使用Django中间件从美国境外登录

[英]how to check if a user has logged in from outside the US using Django middleware

I am pretty new to Django and wanted to know how I could check if a user logging to a django powered website is from outside the US? 我是Django的新手,想知道如何检查登录django的网站的用户是否来自美国以外的地方?

How would I write a class in Middleware to check the same? 我如何在Middleware中编写一个类来检查它? I want to hide particular sections of the website from users logging out of the US. 我希望隐藏用户退出美国的特定网站部分。

I know I am not providing any details and the question might seem vague... but I needed a general idea to get started. 我知道我没有提供任何细节,这个问题可能看起来很模糊......但我需要一个大致的想法才能开始。 I have not started working on the website yet. 我还没有开始在网站上工作。

I went through the Django Middleware documentation but still did not understand how to do so. 我浏览了Django Middleware文档,但仍然不明白该怎么做。 Does the user authentication https://docs.djangoproject.com/en/1.4/topics/auth/#limiting-access-to-logged-in-users provide any such functionality? 用户身份验证https://docs.djangoproject.com/en/1.4/topics/auth/#limiting-access-to-logged-in-users是否提供任何此类功能?

You could use the GeoIP module included with django . 您可以使用django附带GeoIP模块

A simple middleware could look something like this: 一个简单的中间件看起来像这样:

class GeoLocationMiddleware:
    def process_request(self, request):
        if 'geoip_check' not in request.session:
            g = GeoIP()
            country = g.country(request.META.get('REMOTE_ADDR'))
            do_something(country) #Do something with country result.
            request.session['geoip_check'] = True #Could store country result

        return None

You'll notice I add a flag to the session. 你会注意到我在会话中添加了一个标志。 Checking the GeoIP on every request is unnecessary and bad for performance, so we only check it once per session. 在每个请求上检查GeoIP是不必要的,对性能有害,所以我们每次会话只检查一次。 Hope this is what you were looking for. 希望这是你想要的。

Edit: If you only want to do this for logged in users, throw this in there: 编辑:如果您只想为登录用户执行此操作,请将其放入:

if request.user.is_authenticated():

at the beginning. 在开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM