perf: 修改获取 ip

pull/11812/head
ibuler 2023-10-12 14:45:45 +08:00
parent 614e019f14
commit 8b3fd2c117
2 changed files with 19 additions and 11 deletions

View File

@ -19,7 +19,7 @@ from django.utils.translation import gettext as _
from rest_framework.request import Request
from acls.models import LoginACL
from common.utils import get_request_ip, get_logger, bulk_get, FlashMessageUtil
from common.utils import get_request_ip_or_data, get_logger, bulk_get, FlashMessageUtil
from users.models import User
from users.utils import LoginBlockUtil, MFABlockUtils, LoginIpBlockUtil
from . import errors
@ -107,13 +107,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)
return self._ip
def raise_credential_error(self, error):
raise self.partial_credential_error(error=error)

View File

@ -17,6 +17,8 @@ import psutil
from django.conf import settings
from django.templatetags.static import static
from common.permissions import ServiceAccountSignaturePermission
UUID_PATTERN = re.compile(r'\w{8}(-\w{4}){3}-\w{12}')
ipip_db = None
@ -153,19 +155,26 @@ 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:
login_ip = request.META.get('REMOTE_ADDR', '')
return login_ip
login_ip = request.META.get('REMOTE_ADDR', '')
return login_ip
def get_request_ip_or_data(request):
ip = ''
if hasattr(request, 'data'):
ip = request.data.get('remote_addr', '')
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