2015-11-06 12:53:52 +00:00
|
|
|
import time
|
2017-01-24 05:21:49 +00:00
|
|
|
import pytz
|
2017-08-29 11:26:38 +00:00
|
|
|
|
2016-08-07 14:23:55 +00:00
|
|
|
from django.contrib import auth
|
2017-01-24 05:21:49 +00:00
|
|
|
from django.utils import timezone
|
2017-01-23 08:48:04 +00:00
|
|
|
from django.utils.translation import ugettext as _
|
2017-08-29 11:26:38 +00:00
|
|
|
from django.db import connection
|
|
|
|
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-01-23 08:48:04 +00:00
|
|
|
|
2015-11-06 12:53:52 +00:00
|
|
|
|
2017-08-29 11:26:38 +00:00
|
|
|
class SessionSecurityMiddleware(MiddlewareMixin):
|
2015-11-06 12:53:52 +00:00
|
|
|
def process_request(self, request):
|
2017-02-16 07:03:31 +00:00
|
|
|
if request.user.is_authenticated() and request.user.is_admin_role():
|
2015-11-06 12:53:52 +00:00
|
|
|
if "last_activity" in request.session:
|
2016-07-31 12:26:11 +00:00
|
|
|
# 24 hours passed since last visit
|
2015-11-06 12:53:52 +00:00
|
|
|
if time.time() - request.session["last_activity"] >= 24 * 60 * 60:
|
|
|
|
auth.logout(request)
|
2016-11-19 04:32:23 +00:00
|
|
|
return JSONResponse.response({"error": "login-required", "data": _("Please login in first")})
|
2016-09-25 06:07:45 +00:00
|
|
|
# update last active time
|
2015-11-06 12:53:52 +00:00
|
|
|
request.session["last_activity"] = time.time()
|
2016-09-25 06:07:45 +00:00
|
|
|
|
|
|
|
|
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-01-23 08:25:14 +00:00
|
|
|
return JSONResponse.response({"error": "login-required", "data": _("Please login in first")})
|
2017-01-24 05:21:49 +00:00
|
|
|
|
|
|
|
|
2017-08-29 11:26:38 +00:00
|
|
|
class TimezoneMiddleware(MiddlewareMixin):
|
2017-01-24 05:21:49 +00:00
|
|
|
def process_request(self, request):
|
|
|
|
if request.user.is_authenticated():
|
|
|
|
timezone.activate(pytz.timezone(request.user.userprofile.time_zone))
|
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
|