diff --git a/account/middleware.py b/account/middleware.py index 245c32a0..3177da92 100644 --- a/account/middleware.py +++ b/account/middleware.py @@ -1,3 +1,4 @@ +from django.conf import settings from django.db import connection from django.utils.timezone import now from django.utils.deprecation import MiddlewareMixin @@ -19,10 +20,11 @@ class APITokenAuthMiddleware(MiddlewareMixin): class SessionRecordMiddleware(MiddlewareMixin): def process_request(self, request): + request.ip = request.META.get(settings.IP_HEADER, request.META.get("REMOTE_ADDR")) if request.user.is_authenticated(): session = request.session session["user_agent"] = request.META.get("HTTP_USER_AGENT", "") - session["ip"] = request.META.get("HTTP_X_REAL_IP", request.META.get("REMOTE_ADDR")) + session["ip"] = request.ip session["last_activity"] = now() user_sessions = request.user.session_keys if session.session_key not in user_sessions: diff --git a/conf/tests.py b/conf/tests.py index c6a49afc..dce80c68 100644 --- a/conf/tests.py +++ b/conf/tests.py @@ -1,6 +1,7 @@ import hashlib from unittest import mock +from django.conf import settings from django.utils import timezone from options.options import SysOptions @@ -87,7 +88,7 @@ class JudgeServerHeartbeatTest(APITestCase): self.token = "test" self.hashed_token = hashlib.sha256(self.token.encode("utf-8")).hexdigest() SysOptions.judge_server_token = self.token - self.headers = {"HTTP_X_JUDGE_SERVER_TOKEN": self.hashed_token, "HTTP_X_REAL_IP": "1.2.3.4"} + self.headers = {"HTTP_X_JUDGE_SERVER_TOKEN": self.hashed_token, settings.IP_HEADER: "1.2.3.4"} def test_new_heartbeat(self): resp = self.client.post(self.url, data=self.data, **self.headers) diff --git a/conf/views.py b/conf/views.py index 62c1d350..a1ddbb19 100644 --- a/conf/views.py +++ b/conf/views.py @@ -136,7 +136,7 @@ class JudgeServerHeartbeatAPI(CSRFExemptAPIView): server.memory_usage = data["memory"] server.cpu_usage = data["cpu"] server.service_url = data["service_url"] - server.ip = request.META["HTTP_X_REAL_IP"] + server.ip = request.ip server.last_heartbeat = timezone.now() server.save() except JudgeServer.DoesNotExist: diff --git a/deploy/nginx/api_proxy.conf b/deploy/nginx/api_proxy.conf index 631103d9..cc508c8e 100644 --- a/deploy/nginx/api_proxy.conf +++ b/deploy/nginx/api_proxy.conf @@ -1,5 +1,6 @@ proxy_pass http://backend; proxy_set_header X-Real-IP __IP_HEADER__; -proxy_set_header Host $http_host;client_max_body_size 200M; +proxy_set_header Host $http_host; +client_max_body_size 200M; proxy_http_version 1.1; proxy_set_header Connection ''; \ No newline at end of file diff --git a/oj/settings.py b/oj/settings.py index 055c0558..7656f536 100644 --- a/oj/settings.py +++ b/oj/settings.py @@ -207,4 +207,6 @@ CELERY_ACCEPT_CONTENT = ["json"] CELERY_TASK_SERIALIZER = "json" RAVEN_CONFIG = { 'dsn': 'https://b200023b8aed4d708fb593c5e0a6ad3d:1fddaba168f84fcf97e0d549faaeaff0@sentry.io/263057' -} \ No newline at end of file +} + +IP_HEADER = "HTTP_X_REAL_IP"