Merge branch 'main' into ressources

This commit is contained in:
Danhia 2022-01-23 15:48:57 +01:00
commit 0e41087f6a
13 changed files with 324 additions and 163 deletions

View File

@ -0,0 +1,22 @@
# Generated by Django 3.1.5 on 2022-01-14 23:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0005_auto_20211227_1556'),
]
operations = [
migrations.RemoveField(
model_name='team',
name='size',
),
migrations.AddField(
model_name='team',
name='auto',
field=models.BooleanField(default=False),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.1.5 on 2022-01-16 21:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('events', '0006_auto_20220114_2319'),
]
operations = [
migrations.AddField(
model_name='event',
name='auto_match',
field=models.BooleanField(default=False),
),
]

View File

@ -15,6 +15,7 @@ class Event(models.Model):
password = models.CharField(max_length=200, blank=True)
slug = models.SlugField(max_length=55)
team_size = models.PositiveIntegerField(default=1)
auto_match = models.BooleanField(default=False)
def __str__(self):
return self.name
@ -22,9 +23,9 @@ class Team(models.Model):
name = models.CharField(max_length=200)
password = models.CharField(max_length=200)
event = models.ForeignKey(Event, on_delete=models.CASCADE, null=True)
size = models.PositiveIntegerField(default=1)
score = models.PositiveIntegerField(default=0, db_index=True)
last_submission_date = models.DateTimeField('Last Submission Date', default=timezone.now)
auto = models.BooleanField(default=False)
def __str__(self):
return self.name

View File

@ -10,17 +10,12 @@
</div>
<div class="ctf-footer">
<div class="col-sm-8 col-md-6 mx-auto">
{% if logged == True%}
{% if registered == False %}
<span class="message error-msg">{% trans "You need to be registered to the event." %}</span>
{% else %}
{% if notexist == True %}
<span class="message error-msg">{% trans "Team does not exist." %}</span>
{% elif wrongpwd == True %}
<span class="message error-msg">{% trans "Wrong password submited." %}</span>
{% elif max == True %}
<span class="message error-msg">{% trans "Maximum size reached." %}</span>
{% elif exist == True %}
{% if exist == True %}
<span class="message error-msg">{% trans "Name already taken." %}</span>
{% endif %}
<h2>Create Team</h2>
@ -32,29 +27,35 @@
<input type="submit" name="" class="form-control" value="{% trans "Create Team" %}">
</div>
</form>
<h2>Join Team</h2>
<form method="post" action="{% url 'events:join_team' event_slug=event.slug %}" class="join-team-form">
{% csrf_token %}
<div class="form-group">
<input class="form-control" type="text" name="teamname" placeholder="{% trans "Team name" %} *" maxlength="150" required="" id="id_teamname"></br>
<input class="form-control" type="password" name="password" placeholder="{% trans "Password" %} *" required="" id="id_password"></br>
<input type="submit" name="" class="form-control" value="{% trans "Join Team" %}">
</div>
</form>
{% endif %}
{% else %}
<h4>{% trans "You need to be logged to access this event." %}</h4>
{% endif %}
</div>
</div>
</div>
</div>
<div class="d-none d-md-block col-10 col-md-3 right-sidebar">
<ul class="list-group">
<li class="list-group-item">{{ event.name }}</li>
<li class="list-group-item">{% trans "Start at" %} : {{ event.start_date }}</li>
<li class="list-group-item">{% trans "End at" %} : {{ event.end_date }}</li>
<li class="list-group-item">{% trans "Starts at" %} : {{ event.start_date | date:'H:i d-m-y'}}</li>
<li class="list-group-item">{% trans "Ends at" %} : {{ event.end_date | date:'H:i d-m-y'}}</li>
</ul>
<ul class="list-group">
<a href="{% url 'events:create_team' event_slug=event.slug %}" class="list-group-item">{% trans "Create Team" %}</a>
<a href="{% url 'events:join_team' event_slug=event.slug %}" class="list-group-item">{% trans "Join Team" %}</a>
</ul>
{% if event.auto_match %}
<ul class="list-group">
<form method='GET' action="{% url 'events:find_team' event_slug=event.slug %}">
{%csrf_token%}
<li class="list-group-item">
<input class="form-control" type="submit" value="{% trans "Find me a team !" %}">
</li>
</form>
</ul>
{% endif %}
</div>
</div>
{% endblock %}

View File

@ -108,8 +108,8 @@
<div class="d-none d-md-block col-10 col-md-3 right-sidebar">
<ul class="list-group">
<li class="list-group-item">{{ event.name }}</li>
<li class="list-group-item">{% trans "Starts at" %} : {{ event.start_date }}</li>
<li class="list-group-item">{% trans "Ends at" %} : {{ event.end_date }}</li>
<li class="list-group-item">{% trans "Starts at" %} : {{ event.start_date | date:'H:i d-m-y'}}</li>
<li class="list-group-item">{% trans "Ends at" %} : {{ event.end_date | date:'H:i d-m-y'}}</li>
{% if ended == False and IsRegistered == False %}
<form method='POST' action="{% url 'events:subscribe_event' event_slug=event.slug %}">
{%csrf_token%}

View File

@ -33,8 +33,8 @@
<div class="d-none d-md-block col-10 col-md-3 right-sidebar">
<ul class="list-group">
<li class="list-group-item">{{ event.name }}</li>
<li class="list-group-item">{% trans "Start at" %} : {{ event.start_date }}</li>
<li class="list-group-item">{% trans "End at" %} : {{ event.end_date }}</li>
<li class="list-group-item">{% trans "Starts at" %} : {{ event.start_date | date:'H:i d-m-y'}}</li>
<li class="list-group-item">{% trans "Ends at" %} : {{ event.end_date | date:'H:i d-m-y'}}</li>
</ul>
</div>

View File

@ -0,0 +1,66 @@
{% extends 'base.html' %}
{% block content %}
{% load i18n %}
<div class="row">
<div class="col-sm-12 col-md-9">
<div class="ctf-block">
<div class="ctf-head">
<h3>{{ event.name }}</h3>
<small>{% trans "This event starts at" %} : {{ event.start_date }}</small>
</div>
<div class="ctf-footer">
<div class="col-sm-8 col-md-6 mx-auto">
{% if logged == True%}
{% if registered == False %}
<span class="message error-msg">{% trans "You need to be registered to the event." %}</span>
{% else %}
{% if notexist == True %}
<span class="message error-msg">{% trans "Team does not exist." %}</span>
{% elif wrongpwd == True %}
<span class="message error-msg">{% trans "Wrong password submited." %}</span>
{% elif max == True %}
<span class="message error-msg">{% trans "Maximum size reached." %}</span>
{% elif exist == True %}
{% endif %}
<h2>Join Team</h2>
<form method="post" action="{% url 'events:join_team' event_slug=event.slug %}" class="join-team-form">
{% csrf_token %}
<div class="form-group">
<input class="form-control" type="text" name="teamname" placeholder="{% trans "Team name" %} *" maxlength="150" required="" id="id_teamname"></br>
<input class="form-control" type="password" name="password" placeholder="{% trans "Password" %} *" required="" id="id_password"></br>
<input type="submit" name="" class="form-control" value="{% trans "Join Team" %}">
</div>
</form>
{% endif %}
{% else %}
<h4>{% trans "You need to be logged to access this event." %}</h4>
{% endif %}
</div>
</div>
</div>
</div>
<div class="d-none d-md-block col-10 col-md-3 right-sidebar">
<ul class="list-group">
<li class="list-group-item">{{ event.name }}</li>
<li class="list-group-item">{% trans "Starts at" %} : {{ event.start_date | date:'H:i d-m-y' }}</li>
<li class="list-group-item">{% trans "Ends at" %} : {{ event.end_date | date:'H:i d-m-y' }}</li>
</ul>
<ul class="list-group">
<a href="{% url 'events:join_team' event_slug=event.slug %}" class="list-group-item">{% trans "Join Team" %}</a>
<a href="{% url 'events:create_team' event_slug=event.slug %}" class="list-group-item">{% trans "Create Team" %}</a>
</ul>
{% if event.auto_match %}
<ul class="list-group">
<form method='GET' action="{% url 'events:find_team' event_slug=event.slug %}">
{%csrf_token%}
<li class="list-group-item">
<input class="form-control" type="submit" value="{% trans "Find me a team !" %}">
</li>
</form>
</ul>
{% endif %}
</div>
</div>
{% endblock %}

View File

@ -9,6 +9,8 @@ def isflagged(user, ctf):
flagged = False
event_info = ctf.event
if user.is_authenticated == False:
return ""
if event_info.team_size == 1:
if CTF_flags.objects.filter(user=user, ctf=ctf):
flagged = True

View File

@ -16,4 +16,5 @@ urlpatterns = [
path('<str:event_slug>/team/<str:name>', views.team_info, name='team_info'),
path('<str:event_slug>/manage_team', views.manage_team, name='manage_team'),
path('<str:event_slug>/leave_team', views.leave_team, name='leave_team'),
path('find_team/<str:event_slug>', views.find_team, name='find_team'),
]

10
src/events/utils.py Normal file
View File

@ -0,0 +1,10 @@
from random import choice, randint
colors = ['blue', 'red', 'yellow', 'green', 'black', 'white', 'purple', 'orange', 'brown', 'fuchsia', 'gold', 'pink', 'cyan',
'magenta', 'pearl']
animals = ['tiger', 'bee', 'dog', 'cat', 'otter', 'lizard', 'horse', 'mouse', 'butterfly', 'dolphin', 'elephant', 'falcon', 'goat',
'cow', 'lion', 'ostrich']
def get_random_name():
return choice(colors) + choice(animals) + str(randint(0, 100))

View File

@ -0,0 +1,2 @@
from .events import *
from .teams import *

View File

@ -1,13 +1,11 @@
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import timezone
from .forms import submit_flag, TeamUpdateForm
from .models import Event, EventPlayer, Team
from ..forms import submit_flag
from ..models import Event, EventPlayer, Team
from ctfs.models import CTF, CTF_flags, Category
from django.utils.translation import get_language
from django.contrib.auth.models import User
from accounts.models import UserProfileInfo
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
def get_description_by_lang(ctf):
@ -220,45 +218,6 @@ def subscribe_to_event(request, event_slug):
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})
return redirect('events:event_info', event_slug=event_slug)
@login_required
def create_team(request, event_slug):
response = redirect('events:create_team', event_slug=event_slug)
if request.method == 'POST':
if request.user.is_authenticated:
ev = get_object_or_404(Event, slug=event_slug)
if Team.objects.filter(name=request.POST.get('teamname'), event=ev).exists():
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'exist' : True})
new = Team(name=request.POST.get('teamname'), password=request.POST.get('password'), event=ev)
new.save()
player = EventPlayer.objects.get(user=request.user, event=ev)
player.team = new
player.save()
return redirect('events:event_info', event_slug=event_slug)
@login_required
def join_team(request, event_slug):
response = redirect('events:join_team', event_slug=event_slug)
if request.method == 'POST':
if request.user.is_authenticated:
ev = get_object_or_404(Event, slug=event_slug)
try:
team = Team.objects.get(name=request.POST.get('teamname'), event=ev)
except:
team = None
if team is None:
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': True, 'registered' : True, 'notexist' : True})
else:
members = EventPlayer.objects.filter(team=team)
if request.POST.get('password') != team.password:
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': True, 'registered' : True, 'notexist' : False})
if members.count() >= ev.team_size:
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False, 'max' : True})
else:
player = EventPlayer.objects.get(user=request.user, event=ev)
player.team = team
player.save()
return redirect('events:event_info', event_slug=event_slug)
@login_required
def profile(request, user_name, event_slug):
catsDatas = []
@ -298,101 +257,4 @@ def profile(request, user_name, event_slug):
return render(request,'accounts/profile.html', {'user':user_obj, 'solves':solves,'solved':solved,'catsDatas': catsDatas, 'pointDatas': pointDatas,
'rank': rank, 'score' : somme, 'cats':cats})
@login_required
def team_info(request, name, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
team = Team.objects.get(name=name, event=event_info)
catsDatas = []
players = EventPlayer.objects.filter(team=team, event=event_info)
users = [p.user for p in players]
all_teams = list(Team.objects.filter(event=event_info).order_by('-score', 'last_submission_date', 'name'))
rank = all_teams.index(get_object_or_404(Team, id=team.id, event=event_info)) + 1
all_cats = Category.objects.all()
cats = [cat for cat in all_cats if CTF.objects.filter(category__name=cat.name, event=event_info)]
pointDatas = {}
for cat in cats:
# prepare categories
solved_count = 0
solved = []
max_count = CTF.objects.filter(category__name=cat.name, event=event_info).count()
somme = 0
pointDatas[cat.name] = [[event_info.start_date.timestamp()*1000, 0]]
for user_obj in users:
# get datas
solved_count += CTF_flags.objects.filter(user=user_obj, ctf__event=event_info , ctf__category__name=cat.name).count()
solved += CTF_flags.objects.filter(user=user_obj, ctf__category__name=cat.name, ctf__event=event_info).order_by('flag_date')
percent = (solved_count / max_count) * 100
catsDatas.append([cat.name, solved_count, max_count, '{:.0f}'.format(percent)])
for flag in solved:
somme += flag.ctf.points
pointDatas[cat.name].append([flag.flag_date.timestamp() * 1000, somme])
query = Q()
for user_obj in users:
query |= Q(user=user_obj)
query &= Q(ctf__event=event_info)
solves = CTF_flags.objects.filter(query).order_by('-flag_date')
solved = []
somme = 0
solved.append([event_info.start_date.timestamp() * 1000, 0])
for s in solves.reverse():
somme += s.ctf.points
solved.append([s.flag_date.timestamp() * 1000,somme])
return render(request,'events/team.html', {'users':users, 'solves':solves,'solved':solved,'catsDatas': catsDatas, 'pointDatas': pointDatas,
'rank': rank, 'team':team, 'score':somme, 'event':event_info, 'cats':cats})
@login_required
def manage_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
player = EventPlayer.objects.get(user=request.user, event=event_info)
members = EventPlayer.objects.filter(team=player.team, event=event_info)
if request.method == 'POST':
tname = player.team.name
p_form = TeamUpdateForm(request.POST, instance=player.team)
error = None
success = None
if p_form.is_valid():
pname = p_form.cleaned_data['name']
if pname == tname:
pass
else:
if Team.objects.filter(name=pname, event=event_info).exists():
error = _("Name already taken.")
ppassword = p_form.cleaned_data['password']
if error is None:
p_form.save()
success = _("Updated.")
context={'p_form': p_form, 'error':error, 'success' : success, 'player':player, 'members':members}
return render(request, 'events/manage_team.html', context)
else:
p_form = TeamUpdateForm(instance=player.team)
context={'p_form': p_form, 'player':player, 'members':members}
return render(request, 'events/manage_team.html',context)
@login_required
def leave_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
player = EventPlayer.objects.get(user=request.user, event=event_info)
team = Team.objects.get(event=event_info, name=player.team.name)
team.score -= player.score
team.save()
player.team = None
solved = CTF_flags.objects.filter(user=player.user, ctf__event=event_info)
player.score = 0
solved.delete()
player.save()
members = EventPlayer.objects.filter(team=team, event=event_info)
if members.count() == 0:
team.delete()
return render(request, 'events/create_team.html', {'event' : event_info, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})

176
src/events/views/teams.py Normal file
View File

@ -0,0 +1,176 @@
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from ..forms import TeamUpdateForm
from ..models import Event, EventPlayer, Team
from ctfs.models import CTF, CTF_flags, Category
from django.contrib.auth.models import User
from django.db.models import Q
from django.utils.translation import gettext_lazy as _
from ..utils import get_random_name
from random import randint
@login_required
def create_team(request, event_slug):
response = redirect('events:create_team', event_slug=event_slug)
ev = get_object_or_404(Event, slug=event_slug)
if request.method == 'POST':
if request.user.is_authenticated and ev.team_size > 1:
if Team.objects.filter(name=request.POST.get('teamname'), event=ev).exists():
return render(request, 'events/create_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'exist' : True})
new = Team(name=request.POST.get('teamname'), password=request.POST.get('password'), event=ev)
new.save()
player = EventPlayer.objects.get(user=request.user, event=ev)
player.team = new
player.save()
return redirect('events:event_info', event_slug=event_slug)
@login_required
def join_team(request, event_slug):
response = redirect('events:join_team', event_slug=event_slug)
ev = get_object_or_404(Event, slug=event_slug)
if request.method == 'POST':
if request.user.is_authenticated and ev.team_size > 1:
try:
team = Team.objects.get(name=request.POST.get('teamname'), event=ev)
except:
team = None
if team is None:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': True, 'registered' : True, 'notexist' : True})
else:
members = EventPlayer.objects.filter(team=team)
if request.POST.get('password') != team.password:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': True, 'registered' : True, 'notexist' : False})
if members.count() >= ev.team_size:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False, 'max' : True})
else:
player = EventPlayer.objects.get(user=request.user, event=ev)
player.team = team
player.save()
else:
return render(request, 'events/join_team.html', {'event' : ev, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})
return redirect('events:event_info', event_slug=event_slug)
@login_required
def team_info(request, name, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
team = Team.objects.get(name=name, event=event_info)
catsDatas = []
players = EventPlayer.objects.filter(team=team, event=event_info)
users = [p.user for p in players]
all_teams = list(Team.objects.filter(event=event_info).order_by('-score', 'last_submission_date', 'name'))
rank = all_teams.index(get_object_or_404(Team, id=team.id, event=event_info)) + 1
all_cats = Category.objects.all()
cats = [cat for cat in all_cats if CTF.objects.filter(category__name=cat.name, event=event_info)]
pointDatas = {}
for cat in cats:
# prepare categories
solved_count = 0
solved = []
max_count = CTF.objects.filter(category__name=cat.name, event=event_info).count()
somme = 0
pointDatas[cat.name] = [[event_info.start_date.timestamp()*1000, 0]]
for user_obj in users:
# get datas
solved_count += CTF_flags.objects.filter(user=user_obj, ctf__event=event_info , ctf__category__name=cat.name).count()
solved += CTF_flags.objects.filter(user=user_obj, ctf__category__name=cat.name, ctf__event=event_info).order_by('flag_date')
percent = (solved_count / max_count) * 100
catsDatas.append([cat.name, solved_count, max_count, '{:.0f}'.format(percent)])
for flag in solved:
somme += flag.ctf.points
pointDatas[cat.name].append([flag.flag_date.timestamp() * 1000, somme])
query = Q()
for user_obj in users:
query |= Q(user=user_obj)
query &= Q(ctf__event=event_info)
solves = CTF_flags.objects.filter(query).order_by('-flag_date')
solved = []
somme = 0
solved.append([event_info.start_date.timestamp() * 1000, 0])
for s in solves.reverse():
somme += s.ctf.points
solved.append([s.flag_date.timestamp() * 1000,somme])
return render(request,'events/team.html', {'users':users, 'solves':solves,'solved':solved,'catsDatas': catsDatas, 'pointDatas': pointDatas,
'rank': rank, 'team':team, 'score':somme, 'event':event_info, 'cats':cats})
@login_required
def manage_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
player = EventPlayer.objects.get(user=request.user, event=event_info)
members = EventPlayer.objects.filter(team=player.team, event=event_info)
if request.method == 'POST':
tname = player.team.name
p_form = TeamUpdateForm(request.POST, instance=player.team)
error = None
success = None
if p_form.is_valid():
pname = p_form.cleaned_data['name']
if pname == tname:
pass
else:
if Team.objects.filter(name=pname, event=event_info).exists():
error = _("Name already taken.")
ppassword = p_form.cleaned_data['password']
if error is None:
p_form.save()
success = _("Updated.")
context={'p_form': p_form, 'error':error, 'success' : success, 'player':player, 'members':members}
return render(request, 'events/manage_team.html', context)
else:
p_form = TeamUpdateForm(instance=player.team)
context={'p_form': p_form, 'player':player, 'members':members}
return render(request, 'events/manage_team.html',context)
@login_required
def leave_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
player = EventPlayer.objects.get(user=request.user, event=event_info)
team = Team.objects.get(event=event_info, name=player.team.name)
team.score -= player.score
team.save()
player.team = None
solved = CTF_flags.objects.filter(user=player.user, ctf__event=event_info)
player.score = 0
solved.delete()
player.save()
members = EventPlayer.objects.filter(team=team, event=event_info)
if members.count() == 0:
team.delete()
return render(request, 'events/create_team.html', {'event' : event_info, 'logged': True, 'wrongpwd': False, 'registered' : True, 'notexist' : False})
@login_required
def find_team(request, event_slug):
event_info = get_object_or_404(Event, slug=event_slug)
teams = Team.objects.filter(event=event_info, auto=True)
team = None
player = EventPlayer.objects.get(user=request.user, event=event_info)
if event_info.auto_match == False:
return redirect('events:event_info', event_slug=event_slug)
for t in teams:
if EventPlayer.objects.filter(team=t, event=event_info).count() < event_info.team_size:
team = t
break
if team is None:
teamname = get_random_name()
while Team.objects.filter(name=teamname, event=event_info).exists():
teamname = get_random_name()
team = Team(name=teamname, password="".join([str(randint(0,10)) for _ in range(16)]), event=event_info, auto=True)
team.save()
player.team = team
player.save()
return redirect('events:event_info', event_slug=event_slug)