Skip to content

Commit

Permalink
style: lint & format
Browse files Browse the repository at this point in the history
  • Loading branch information
mikucat0309 committed Feb 9, 2024
1 parent 12712bf commit 3329c12
Show file tree
Hide file tree
Showing 123 changed files with 3,801 additions and 2,421 deletions.
17 changes: 0 additions & 17 deletions .travis.yml

This file was deleted.

64 changes: 43 additions & 21 deletions account/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,17 @@ def __get__(self, obj, obj_type):
return functools.partial(self.__call__, obj)

def error(self, data):
return JSONResponse.response({"error": "permission-denied", "data": data})
return JSONResponse.response({'error': 'permission-denied', 'data': data})

def __call__(self, *args, **kwargs):
self.request = args[1]

if self.check_permission():
if self.request.user.is_disabled:
return self.error("Your account is disabled")
return self.error('Your account is disabled')
return self.func(*args, **kwargs)
else:
return self.error("Please login first")
return self.error('Please login first')

def check_permission(self):
raise NotImplementedError()
Expand Down Expand Up @@ -67,13 +67,18 @@ def check_contest_password(password, contest_password):
else:
# sig#timestamp 这种形式的密码也可以,但是在界面上没提供支持
# sig = sha256(contest_password + timestamp)[:8]
if "#" in password:
s = password.split("#")
if '#' in password:
s = password.split('#')
if len(s) != 2:
return False
sig, ts = s[0], s[1]

if sig == hashlib.sha256((contest_password + ts).encode("utf-8")).hexdigest()[:8]:
if (
sig
== hashlib.sha256((contest_password + ts).encode('utf-8')).hexdigest()[
:8
]
):
try:
ts = int(ts)
except Exception:
Expand All @@ -85,7 +90,7 @@ def check_contest_password(password, contest_password):
return False


def check_contest_permission(check_type="details"):
def check_contest_permission(check_type='details'):
"""
只供Class based view 使用,检查用户是否有权进入该contest, check_type 可选 details, problems, ranks, submissions
若通过验证,在view中可通过self.contest获得该contest
Expand All @@ -96,48 +101,65 @@ def _check_permission(*args, **kwargs):
self = args[0]
request = args[1]
user = request.user
if request.data.get("contest_id"):
contest_id = request.data["contest_id"]
if request.data.get('contest_id'):
contest_id = request.data['contest_id']
else:
contest_id = request.GET.get("contest_id")
contest_id = request.GET.get('contest_id')
if not contest_id:
return self.error("Parameter error, contest_id is required")
return self.error('Parameter error, contest_id is required')

try:
# use self.contest to avoid query contest again in view.
self.contest = Contest.objects.select_related("created_by").get(id=contest_id, visible=True)
self.contest = Contest.objects.select_related('created_by').get(
id=contest_id, visible=True
)
except Contest.DoesNotExist:
return self.error("Contest %s doesn't exist" % contest_id)

# Anonymous
if not user.is_authenticated:
return self.error("Please login first.")
return self.error('Please login first.')

# creator or owner
if user.is_contest_admin(self.contest):
return func(*args, **kwargs)

if self.contest.contest_type == ContestType.PASSWORD_PROTECTED_CONTEST:
# password error
if not check_contest_password(request.session.get(CONTEST_PASSWORD_SESSION_KEY, {}).get(self.contest.id), self.contest.password):
return self.error("Wrong password or password expired")
if not check_contest_password(
request.session.get(CONTEST_PASSWORD_SESSION_KEY, {}).get(
self.contest.id
),
self.contest.password,
):
return self.error('Wrong password or password expired')

# regular user get contest problems, ranks etc. before contest started
if self.contest.status == ContestStatus.CONTEST_NOT_START and check_type != "details":
return self.error("Contest has not started yet.")
if (
self.contest.status == ContestStatus.CONTEST_NOT_START
and check_type != 'details'
):
return self.error('Contest has not started yet.')

# check does user have permission to get ranks, submissions in OI Contest
if self.contest.status == ContestStatus.CONTEST_UNDERWAY and self.contest.rule_type == ContestRuleType.OI:
if not self.contest.real_time_rank and (check_type == "ranks" or check_type == "submissions"):
return self.error(f"No permission to get {check_type}")
if (
self.contest.status == ContestStatus.CONTEST_UNDERWAY
and self.contest.rule_type == ContestRuleType.OI
):
if not self.contest.real_time_rank and (
check_type == 'ranks' or check_type == 'submissions'
):
return self.error(f'No permission to get {check_type}')

return func(*args, **kwargs)

return _check_permission

return decorator


def ensure_created_by(obj, user):
e = APIError(msg=f"{obj.__class__.__name__} does not exist")
e = APIError(msg=f'{obj.__class__.__name__} does not exist')
if not user.is_admin_role():
raise e
if user.is_super_admin():
Expand Down
31 changes: 17 additions & 14 deletions account/middleware.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
from django.conf import settings
from django.db import connection
from django.utils.timezone import now
from django.utils.deprecation import MiddlewareMixin
Expand All @@ -9,12 +8,14 @@

class APITokenAuthMiddleware(MiddlewareMixin):
def process_request(self, request):
appkey = request.META.get("HTTP_APPKEY")
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.user = User.objects.get(
open_api_appkey=appkey, open_api=True, is_disabled=False
)
request.csrf_processing_done = True
request.auth_method = "api_key"
request.auth_method = 'api_key'
except User.DoesNotExist:
pass

Expand All @@ -25,12 +26,12 @@ def process_request(self, request):
if forwarded:
request.ip = forwarded.split(',')[0].strip()
else:
request.ip = request.META["REMOTE_ADDR"]
request.ip = request.META['REMOTE_ADDR']
if request.user.is_authenticated:
session = request.session
session["user_agent"] = request.META.get("HTTP_USER_AGENT", "")
session["ip"] = request.ip
session["last_activity"] = now()
session['user_agent'] = request.META.get('HTTP_USER_AGENT', '')
session['ip'] = request.ip
session['last_activity'] = now()
user_sessions = request.user.session_keys
if session.session_key not in user_sessions:
user_sessions.append(session.session_key)
Expand All @@ -40,18 +41,20 @@ def process_request(self, request):
class AdminRoleRequiredMiddleware(MiddlewareMixin):
def process_request(self, request):
path = request.path_info
if path.startswith("/admin/") or path.startswith("/api/admin/"):
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"})
return JSONResponse.response(
{'error': 'login-required', 'data': 'Please login in first'}
)


class LogSqlMiddleware(MiddlewareMixin):
def process_response(self, request, response):
print("\033[94m", "#" * 30, "\033[0m")
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")
if float(query['time']) > time_threshold:
print('\033[93m', query, '\n', '-' * 30, '\033[0m')
else:
print(query, "\n", "-" * 30)
print(query, '\n', '-' * 30)
return response
46 changes: 37 additions & 9 deletions account/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,30 @@


class Migration(migrations.Migration):

initial = True

dependencies = [
]
dependencies = []

operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID',
),
),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
(
'last_login',
models.DateTimeField(
blank=True, null=True, verbose_name='last login'
),
),
('username', models.CharField(max_length=30, unique=True)),
('real_name', models.CharField(max_length=30, null=True)),
('email', models.EmailField(max_length=254, null=True)),
Expand All @@ -48,20 +59,37 @@ class Migration(migrations.Migration):
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
(
'id',
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name='ID',
),
),
('problems_status', jsonfield.fields.JSONField(default={})),
('avatar', models.CharField(default="default.png", max_length=50)),
('avatar', models.CharField(default='default.png', max_length=50)),
('blog', models.URLField(blank=True, null=True)),
('mood', models.CharField(blank=True, max_length=200, null=True)),
('accepted_problem_number', models.IntegerField(default=0)),
('submission_number', models.IntegerField(default=0)),
('phone_number', models.CharField(blank=True, max_length=15, null=True)),
(
'phone_number',
models.CharField(blank=True, max_length=15, null=True),
),
('school', models.CharField(blank=True, max_length=200, null=True)),
('major', models.CharField(blank=True, max_length=200, null=True)),
('student_id', models.CharField(blank=True, max_length=15, null=True)),
('time_zone', models.CharField(blank=True, max_length=32, null=True)),
('language', models.CharField(blank=True, max_length=32, null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
(
'user',
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL,
),
),
],
options={
'db_table': 'user_profile',
Expand Down
1 change: 0 additions & 1 deletion account/migrations/0002_auto_20170209_1028.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0001_initial'),
]
Expand Down
3 changes: 1 addition & 2 deletions account/migrations/0003_userprofile_total_score.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0002_auto_20170209_1028'),
]
Expand All @@ -25,5 +24,5 @@ class Migration(migrations.Migration):
migrations.RemoveField(
model_name='userprofile',
name='time_zone',
)
),
]
1 change: 0 additions & 1 deletion account/migrations/0005_auto_20170830_1154.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0003_userprofile_total_score'),
]
Expand Down
1 change: 0 additions & 1 deletion account/migrations/0006_user_session_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0005_auto_20170830_1154'),
]
Expand Down
5 changes: 3 additions & 2 deletions account/migrations/0008_auto_20171011_1214.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0006_user_session_keys'),
]
Expand Down Expand Up @@ -70,7 +69,9 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='userprofile',
name='avatar',
field=models.CharField(default='/static/avatar/default.png', max_length=256),
field=models.CharField(
default='/static/avatar/default.png', max_length=256
),
),
migrations.AlterField(
model_name='userprofile',
Expand Down
5 changes: 3 additions & 2 deletions account/migrations/0009_auto_20171125_1514.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0008_auto_20171011_1214'),
]
Expand All @@ -15,6 +14,8 @@ class Migration(migrations.Migration):
migrations.AlterField(
model_name='userprofile',
name='avatar',
field=models.CharField(default='/public/avatar/default.png', max_length=256),
field=models.CharField(
default='/public/avatar/default.png', max_length=256
),
),
]
1 change: 0 additions & 1 deletion account/migrations/0010_auto_20180501_0436.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0009_auto_20171125_1514'),
]
Expand Down
1 change: 0 additions & 1 deletion account/migrations/0011_auto_20180501_0456.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0010_auto_20180501_0436'),
]
Expand Down
1 change: 0 additions & 1 deletion account/migrations/0012_userprofile_language.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@


class Migration(migrations.Migration):

dependencies = [
('account', '0011_auto_20180501_0456'),
]
Expand Down
Loading

0 comments on commit 3329c12

Please sign in to comment.