2018-01-06 15:53:41 +00:00
|
|
|
from django.conf import settings
|
2017-08-29 11:26:38 +00:00
|
|
|
from django.db import connection
|
2017-10-06 09:46:14 +00:00
|
|
|
from django.utils.timezone import now
|
2017-08-29 11:26:38 +00:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2016-06-23 04:19:16 +00:00
|
|
|
|
2016-11-19 04:32:23 +00:00
|
|
|
from utils.api import JSONResponse
|
2017-11-25 13:47:51 +00:00
|
|
|
from account.models import User
|
|
|
|
|
|
|
|
|
|
|
|
class APITokenAuthMiddleware(MiddlewareMixin):
|
|
|
|
def process_request(self, request):
|
|
|
|
appkey = request.META.get("HTTP_APPKEY")
|
|
|
|
if appkey:
|
|
|
|
try:
|
|
|
|
request.user = User.objects.get(open_api_appkey=appkey, open_api=True, is_disabled=False)
|
|
|
|
request.csrf_processing_done = True
|
2018-12-16 02:30:19 +00:00
|
|
|
request.auth_method = "api_key"
|
2017-11-25 13:47:51 +00:00
|
|
|
except User.DoesNotExist:
|
|
|
|
pass
|
2017-01-23 08:48:04 +00:00
|
|
|
|
2015-11-06 12:53:52 +00:00
|
|
|
|
2017-09-19 11:10:50 +00:00
|
|
|
class SessionRecordMiddleware(MiddlewareMixin):
|
|
|
|
def process_request(self, request):
|
2018-01-06 15:53:41 +00:00
|
|
|
request.ip = request.META.get(settings.IP_HEADER, request.META.get("REMOTE_ADDR"))
|
2017-09-19 11:10:50 +00:00
|
|
|
if request.user.is_authenticated():
|
|
|
|
session = request.session
|
2017-10-06 09:46:14 +00:00
|
|
|
session["user_agent"] = request.META.get("HTTP_USER_AGENT", "")
|
2018-01-06 15:53:41 +00:00
|
|
|
session["ip"] = request.ip
|
2017-10-06 09:46:14 +00:00
|
|
|
session["last_activity"] = now()
|
2017-09-19 11:10:50 +00:00
|
|
|
user_sessions = request.user.session_keys
|
2017-10-06 09:46:14 +00:00
|
|
|
if session.session_key not in user_sessions:
|
2017-09-19 11:10:50 +00:00
|
|
|
user_sessions.append(session.session_key)
|
|
|
|
request.user.save()
|
|
|
|
|
|
|
|
|
2017-08-29 11:26:38 +00:00
|
|
|
class AdminRoleRequiredMiddleware(MiddlewareMixin):
|
2016-09-25 06:07:45 +00:00
|
|
|
def process_request(self, request):
|
|
|
|
path = request.path_info
|
|
|
|
if path.startswith("/admin/") or path.startswith("/api/admin/"):
|
2017-08-29 11:26:38 +00:00
|
|
|
if not (request.user.is_authenticated() and request.user.is_admin_role()):
|
2017-10-01 20:33:43 +00:00
|
|
|
return JSONResponse.response({"error": "login-required", "data": "Please login in first"})
|
2017-08-29 11:26:38 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LogSqlMiddleware(MiddlewareMixin):
|
|
|
|
def process_response(self, request, response):
|
|
|
|
print("\033[94m", "#" * 30, "\033[0m")
|
|
|
|
time_threshold = 0.03
|
|
|
|
for query in connection.queries:
|
|
|
|
if float(query["time"]) > time_threshold:
|
|
|
|
print("\033[93m", query, "\n", "-" * 30, "\033[0m")
|
|
|
|
else:
|
|
|
|
print(query, "\n", "-" * 30)
|
|
|
|
return response
|