2015-03-02 172 views
6

我想在我的Django应用程序中登录用户IP地址,特别是登录,注销和登录失败事件。我使用Django的内置功能如下:Django登录user_login_failed信号的用户IP

from django.contrib.auth.signals import user_logged_in, user_logged_out, user_login_failed 
from ipware.ip import get_ip 
import logging 

logger = logging.getLogger(__name__) 

def log_logged_in(sender, user, request, **kwargs): 
    logger.info("%s User %s successfully logged in" % (get_ip(request), user)) 

def log_logged_out(sender, user, request, **kwargs): 
    logger.info("%s User %s successfully logged out" % (get_ip(request), user)) 

def log_login_failed(sender, credentials, **kwargs): 
    logger.warning("%s Authentication failure for user %s" % ("...IP...", credentials['username'])) 

user_logged_in.connect(log_logged_in) 
user_logged_out.connect(log_logged_out) 
user_login_failed.connect(log_login_failed) 

的问题是,我还没有找到一种方式来获得的IP为user_login_failed信号,因为这个功能没有在参数requesthttps://docs.djangoproject.com/en/1.7/ref/contrib/auth/#module-django.contrib.auth.signals) 。 credentials参数是仅包含usernamepassword字段的字典。

我怎样才能得到这个信号的IP地址?

非常感谢您的帮助。

回答

0

您可以覆盖登录表单,并拦截它。 它在那个阶段有要求。

import logging 
from django.contrib.admin.forms import AdminAuthenticationForm 
from django import forms 

log = logging.getLogger(__name__) 


class AuthenticationForm(AdminAuthenticationForm): 
    def clean(self): 
     # to cover more complex cases: 
     # http://stackoverflow.com/questions/4581789/how-do-i-get-user-ip-address-in-django 
     ip = request.META.get('REMOTE_ADDR') 
     try: 
      data = super(AuthenticationForm, self).clean() 
     except forms.ValidationError: 
      log.info('Login Failed (%s) from (%s)', self.cleaned_data.get('username'), ip) 
      raise 

     if bool(self.user_cache): 
      log.info('Login Success (%s) from (%s)', self.cleaned_data.get('username'), ip) 
     else: 
      log.info('Login Failed (%s) from (%s)', self.cleaned_data.get('username'), ip) 

     return data 

把它安装到你需要连接站点时django.contrib.admin.site.login_form

我建议做它在应用程序的准备()方法,像这样:

from django.contrib.admin import site as admin_site 

class Config(AppConfig): 
    ... 

    def ready(self): 
     # Attach the logging hook to the login form 
     from .forms import AuthenticationForm 
     admin_site.login_form = AuthenticationForm