tiny work

This commit is contained in:
virusdefender 2017-10-02 04:33:43 +08:00
parent 9990cf647a
commit edb32eaf7b
6 changed files with 21 additions and 50 deletions

View File

@ -10,22 +10,11 @@ from django.utils.deprecation import MiddlewareMixin
from utils.api import JSONResponse
class SessionSecurityMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.user.is_authenticated():
if "last_activity" in request.session and request.user.is_admin_role():
# 24 hours passed since last visit, 86400 = 24 * 60 * 60
if time.time() - request.session["last_activity"] >= 86400:
auth.logout(request)
return JSONResponse.response({"error": "login-required", "data": _("Please login in first")})
request.session["last_activity"] = time.time()
class SessionRecordMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.user.is_authenticated():
session = request.session
ip = request.META.get("REMOTE_ADDR", "")
ip = request.META.get("HTTP_X_REAL_IP", "UNKNOWN IP")
user_agent = request.META.get("HTTP_USER_AGENT", "")
_ip = session.setdefault("ip", ip)
_user_agent = session.setdefault("user_agent", user_agent)
@ -42,13 +31,7 @@ class AdminRoleRequiredMiddleware(MiddlewareMixin):
path = request.path_info
if path.startswith("/admin/") or path.startswith("/api/admin/"):
if not (request.user.is_authenticated() and request.user.is_admin_role()):
return JSONResponse.response({"error": "login-required", "data": _("Please login in first")})
class TimezoneMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.user.is_authenticated():
timezone.activate(pytz.timezone(request.user.userprofile.time_zone))
return JSONResponse.response({"error": "login-required", "data": "Please login in first"})
class LogSqlMiddleware(MiddlewareMixin):

View File

@ -357,7 +357,6 @@ class SessionManagementAPI(APIView):
def get(self, request):
engine = import_module(settings.SESSION_ENGINE)
SessionStore = engine.SessionStore
current_session = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
current_session = request.session.session_key
session_keys = request.user.session_keys
result = []

View File

@ -64,7 +64,7 @@ class Contest(models.Model):
ordering = ("-create_time",)
class ContestRank(models.Model):
class AbstractContestRank(models.Model):
user = models.ForeignKey(User)
contest = models.ForeignKey(Contest)
submission_number = models.IntegerField(default=0)
@ -73,7 +73,7 @@ class ContestRank(models.Model):
abstract = True
class ACMContestRank(ContestRank):
class ACMContestRank(AbstractContestRank):
accepted_number = models.IntegerField(default=0)
# total_time is only for ACM contest total_time = ac time + none-ac times * 20 * 60
total_time = models.IntegerField(default=0)
@ -85,7 +85,7 @@ class ACMContestRank(ContestRank):
db_table = "acm_contest_rank"
class OIContestRank(ContestRank):
class OIContestRank(AbstractContestRank):
total_score = models.IntegerField(default=0)
# {23: 333}}
# key is problem id, value is current score
@ -94,9 +94,6 @@ class OIContestRank(ContestRank):
class Meta:
db_table = "oi_contest_rank"
def update_rank(self, submission):
self.submission_number += 1
class ContestAnnouncement(models.Model):
contest = models.ForeignKey(Contest)

View File

@ -1,6 +1,6 @@
import pickle
from django.utils.timezone import now
from django.db.models import Q
from django.core.cache import cache
from utils.api import APIView, validate_serializer
from utils.cache import default_cache
from utils.constants import CacheKey
@ -32,7 +32,7 @@ class ContestAPI(APIView):
try:
contest = Contest.objects.select_related("created_by").get(id=contest_id, visible=True)
except Contest.DoesNotExist:
return self.error("Contest doesn't exist.")
return self.error("Contest does not exist")
return self.success(ContestSerializer(contest).data)
contests = Contest.objects.select_related("created_by").filter(visible=True)
@ -50,7 +50,7 @@ class ContestAPI(APIView):
elif status == ContestStatus.CONTEST_ENDED:
contests = contests.filter(end_time__lt=cur)
else:
contests = contests.filter(Q(start_time__lte=cur) & Q(end_time__gte=cur))
contests = contests.filter(start_time__lte=cur, end_time__gte=cur)
return self.success(self.paginate_data(request, contests, ContestSerializer))
@ -62,14 +62,14 @@ class ContestPasswordVerifyAPI(APIView):
try:
contest = Contest.objects.get(id=data["contest_id"], visible=True, password__isnull=False)
except Contest.DoesNotExist:
return self.error("Contest %s doesn't exist." % data["contest_id"])
return self.error("Contest does not exist")
if contest.password != data["password"]:
return self.error("Password doesn't match.")
return self.error("Wrong password")
# password verify OK.
if "contests" not in request.session:
request.session["contests"] = []
request.session["contests"].append(int(data["contest_id"]))
if "accessible_contests" not in request.session:
request.session["accessible_contests"] = []
request.session["contests"].append(contest.id)
# https://docs.djangoproject.com/en/dev/topics/http/sessions/#when-sessions-are-saved
request.session.modified = True
return self.success(True)
@ -80,13 +80,8 @@ class ContestAccessAPI(APIView):
def get(self, request):
contest_id = request.GET.get("contest_id")
if not contest_id:
return self.error("Parameter contest_id not exist.")
if "contests" not in request.session:
request.session["contests"] = []
if int(contest_id) in request.session["contests"]:
return self.success({"Access": True})
else:
return self.success({"Access": False})
return self.error()
return self.success({"access": int(contest_id) in request.session.get("accessible_contests", [])})
class ContestRankAPI(APIView):
@ -105,12 +100,10 @@ class ContestRankAPI(APIView):
else:
serializer = OIContestRankSerializer
cache_key = CacheKey.contest_rank_cache + str(self.contest.id)
qs = default_cache.get(cache_key)
cache_key = f"{CacheKey.contest_rank_cache}:{self.contest.id}"
qs = cache.get(cache_key)
if not qs:
ranks = self.get_rank()
default_cache.set(cache_key, pickle.dumps(ranks))
else:
ranks = pickle.loads(qs)
qs = self.get_rank()
cache.set(cache_key, qs)
return self.success(self.paginate_data(request, ranks, serializer))
return self.success(self.paginate_data(request, qs, serializer))

View File

@ -58,7 +58,6 @@ MIDDLEWARE_CLASSES = (
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'account.middleware.AdminRoleRequiredMiddleware',
'account.middleware.SessionSecurityMiddleware',
'account.middleware.SessionRecordMiddleware',
# 'account.middleware.LogSqlMiddleware',
)

View File

@ -79,7 +79,7 @@ class APIView(View):
def success(self, data=None):
return self.response({"error": None, "data": data})
def error(self, msg, err="error"):
def error(self, msg="error", err="error"):
return self.response({"error": err, "data": msg})
def _serializer_error_to_str(self, errors):