perf: 修改获取 ip

pull/11976/head
wangruidong 2023-10-26 15:09:36 +08:00 committed by 老广
parent 29ab6bbee7
commit cc656a8a97
2 changed files with 30 additions and 19 deletions

View File

@ -18,7 +18,7 @@ from django.contrib.auth import (
from django.core.exceptions import ImproperlyConfigured
from django.shortcuts import reverse, redirect, get_object_or_404
from common.utils import get_request_ip, get_logger, bulk_get, FlashMessageUtil
from common.utils import get_request_ip_or_data, get_request_ip, get_logger, bulk_get, FlashMessageUtil
from acls.models import LoginACL
from users.models import User
from users.utils import LoginBlockUtil, MFABlockUtils, LoginIpBlockUtil
@ -92,13 +92,12 @@ auth.authenticate = authenticate
class CommonMixin:
request: Request
_ip = ''
def get_request_ip(self):
ip = ''
if hasattr(self.request, 'data'):
ip = self.request.data.get('remote_addr', '')
ip = ip or get_request_ip(self.request)
return ip
if not self._ip:
self._ip = get_request_ip_or_data(self.request)
def raise_credential_error(self, error):
raise self.partial_credential_error(error=error)

View File

@ -76,6 +76,7 @@ def setattr_bulk(seq, key, value):
def set_attr(obj):
setattr(obj, key, value)
return obj
return map(set_attr, seq)
@ -152,18 +153,27 @@ def is_uuid(seq):
def get_request_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')
x_real_ip = request.META.get('HTTP_X_REAL_IP', '')
if x_real_ip:
return x_real_ip
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '').split(',')
if x_forwarded_for and x_forwarded_for[0]:
login_ip = x_forwarded_for[0]
else:
return login_ip
login_ip = request.META.get('REMOTE_ADDR', '')
return login_ip
def get_request_ip_or_data(request):
from common.permissions import ServiceAccountSignaturePermission
ip = ''
if hasattr(request, 'data'):
if hasattr(request, 'data') and request.data.get('remote_addr', ''):
permission = ServiceAccountSignaturePermission()
if permission.has_permission(request, None):
ip = request.data.get('remote_addr', '')
ip = ip or get_request_ip(request)
return ip
@ -195,6 +205,7 @@ def with_cache(func):
res = func(*args, **kwargs)
cache[key] = res
return res
return wrapper
@ -216,6 +227,7 @@ def timeit(func):
msg = "End call {}, using: {:.1f}ms".format(name, using)
logger.debug(msg)
return result
return wrapper