2015-03-02 169 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