-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
695 lines (620 loc) · 22.2 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
#coding=utf-8
from flask import render_template, request, redirect, jsonify, url_for, session, Blueprint, abort
from CTFd.models import db, Challenges, Files, Solves, WrongKeys, Keys, Tags, Teams, Awards, Hints, Unlocks
from CTFd.utils import admins_only, is_admin
from werkzeug.utils import secure_filename
from sqlalchemy.sql.expression import union_all
from CTFd import utils
#from CTFd.scoreboard import get_standings
from CTFd.plugins import register_plugin_assets_directory
from CTFd.plugins.challenges import get_chal_class
import datetime
import os
competitions = Blueprint('competitions', __name__,
static_folder='assets', template_folder='templates')
#竞赛模型
class Competitions(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(46))
description = db.Column(db.Text)
startTime = db.Column(db.DateTime, default=datetime.datetime.utcnow)
endTime = db.Column(db.DateTime, default=datetime.datetime.utcnow)
profile = db.Column(db.String(50), default='default.jpg')
chals = db.relationship('Chalcomp', backref='competition')
def __init__(self, title, description):
self.title = title
self.description = description
# 存放题目与竞赛的对应关系
class Chalcomp(db.Model):
id = db.Column(db.Integer, primary_key=True)
chalid = db.Column(db.Integer, db.ForeignKey('challenges.id'))
compid = db.Column(db.Integer, db.ForeignKey('competitions.id'))
chal=db.relationship('Challenges',backref=db.backref('chalcomp'))
def get_range(comp, admin=False, count=None, teamid=None):
Comp = Competitions.query.filter(Competitions.id == comp).first()
if not Comp:
return []
scores = db.session.query(
Solves.teamid.label('teamid'),
db.func.sum(Challenges.value).label('score'),
db.func.max(Solves.id).label('id'),
db.func.max(Solves.date).label('date')
).join(Challenges).join(Chalcomp).group_by(Solves.teamid)
awards = db.session.query(
Awards.teamid.label('teamid'),
db.func.sum(Awards.value).label('score'),
db.func.max(Awards.id).label('id'),
db.func.max(Awards.date).label('date')
).group_by(Awards.teamid)
"""
Filter out solves and awards that are before a specific time point.
"""
freeze = utils.get_config('freeze')
chals = [x.chalid for x in Comp.chals]
awardTitles=[u"Hint for {}".format(x.chal.name) for x in Comp.chals]
print awardTitles
if not admin and freeze:
scores = scores.filter(Solves.date < utils.unix_time_to_utc(freeze))
awards = awards.filter(Awards.date < utils.unix_time_to_utc(freeze))
"""
Combine awards and solves with a union. They should have the same amount of columns
"""
scores = scores.filter(Chalcomp.compid == Comp.id)
scores = scores.filter(Solves.date < Comp.endTime)
scores = scores.filter(Solves.date > Comp.startTime)
awards = awards.filter(Awards.date < Comp.endTime)
awards = awards.filter(Awards.date > Comp.startTime)
awards = awards.filter(Awards.name.in_(awardTitles))
#awards=scores.filter(Solves.chalid in chals)
results = union_all(scores, awards).alias('results')
if(teamid is not None):
scores = scores.filter(Solves.teamid == teamid)
awards = awards.filter(Solves.teamid == teamid)
"""
Sum each of the results by the team id to get their score.
"""
sumscores = db.session.query(
results.columns.teamid,
db.func.sum(results.columns.score).label('score'),
db.func.max(results.columns.id).label('id'),
db.func.max(results.columns.date).label('date')
).group_by(results.columns.teamid).subquery()
"""
Admins can see scores for all users but the public cannot see banned users.
Filters out banned users.
Properly resolves value ties by ID.
Different databases treat time precision differently so resolve by the row ID instead.
"""
if admin:
standings_query = db.session.query(
Teams.id.label('teamid'),
Teams.name.label('name'),
Teams.banned, sumscores.columns.score
)\
.join(sumscores, Teams.id == sumscores.columns.teamid) \
.order_by(sumscores.columns.score.desc(), sumscores.columns.id)
else:
standings_query = db.session.query(
Teams.id.label('teamid'),
Teams.name.label('name'),
sumscores.columns.score
)\
.join(sumscores, Teams.id == sumscores.columns.teamid) \
.filter(Teams.banned == False) \
.order_by(sumscores.columns.score.desc(), sumscores.columns.id)
#print standings_query
"""
Only select a certain amount of users if asked.
"""
if count is None:
standings = standings_query.all()
else:
standings = standings_query.limit(count).all()
db.session.close()
return standings
@competitions.route('/competitions', defaults={'compid':None})
@competitions.route('/competitions/<int:compid>')
def comps(compid):
if not utils.is_admin():
if not utils.ctftime():
if utils.view_after_ctf():
pass
else:
abort(403)
if compid is None:
comp=Competitions.query.all()
return render_template('competitions.html',comp=comp)
else:
comp=Competitions.query.filter(Competitions.id==compid).one()
if comp:
return render_template('comp.html',comp=comp)
else:
abort(403)
@competitions.route('/comps',defaults={'compid':None})
@competitions.route('/comps/<int:compid>')
def competitions_json(compid):
if not utils.is_admin():
if not utils.ctftime():
if utils.view_after_ctf():
pass
else:
abort(403)
if compid is None:
comps= Competitions.query.all()
json={'competitions':[]}
for x in comps:
json['competitions'].append({
'id': x.id,
'title': x.title,
'description': x.description,
'startTime': x.startTime,
'endTime': x.endTime,
'profile': x.profile
})
json['competitions'] = sorted(json['competitions'], key=lambda k: k['startTime'])
json['competitions'].reverse()
db.session.close()
return jsonify(json)
else:
x=Competitions.query.filter(Competitions.id==compid).first()
db.session.close()
if x is None:
abort(403)
return jsonify({
'id': x.id,
'title': x.title,
'description': x.description,
'startTime': x.startTime,
'endTime': x.endTime,
'profile': x.profile
})
@competitions.route('/admin/competitions', methods=['GET'])
@admins_only
def admin_competitions():
comp=Competitions.query.all()
return render_template('admin_competitions.html',comp=comp)
@competitions.route('/competitions/<int:compid>/challenges', methods=['GET'])
def challenges_view(compid):
infos = []
errors = []
start = utils.get_config('start') or 0
end = utils.get_config('end') or 0
comp=Competitions.query.filter(Competitions.id==compid).first()
if utils.ctf_paused():
infos.append('{} is paused'.format(utils.ctf_name()))
if not utils.is_admin(): # User is not an admin
if not utils.ctftime():
# It is not CTF time
if utils.view_after_ctf(): # But we are allowed to view after the CTF ends
pass
else: # We are NOT allowed to view after the CTF ends
if utils.get_config('start') and not utils.ctf_started():
errors.append('{} has not started yet'.format(utils.ctf_name()))
if (utils.get_config('end') and utils.ctf_ended()) and not utils.view_after_ctf():
errors.append('{} has ended'.format(utils.ctf_name()))
if comp is None:
errors.append('no such competition')
start=False
if comp.startTime>datetime.datetime.utcnow():
errors=append('{} 尚未开始,敬请期待'.format(comp.title))
start=False
return render_template('comp_challenges.html', infos=infos, errors=errors, start=int(start), end=int(end),comp=comp)
if utils.get_config('verify_emails'):
if utils.authed():
if utils.is_admin() is False and utils.is_verified() is False: # User is not confirmed
return redirect(url_for('auth.confirm_user'))
if utils.user_can_view_challenges(): # Do we allow unauthenticated users?
if utils.get_config('start') and not utils.ctf_started():
errors.append('{} has not started yet'.format(utils.ctf_name()))
if (utils.get_config('end') and utils.ctf_ended()) and not utils.view_after_ctf():
errors.append('{} has ended'.format(utils.ctf_name()))
if comp is None:
errors.append('no such competition')
start=False
if comp.startTime>datetime.datetime.utcnow():
errors.append('{} 尚未开始,敬请期待'.format(comp.title))
start=False
return render_template('comp_challenges.html', infos=infos, errors=errors, start=int(start), end=int(end),comp=comp)
else:
return redirect(url_for('auth.login', next=request.path))
@competitions.route('/competitions/<int:compid>/chals', methods=['GET'])
def comp_challenges(compid):
if not utils.is_admin():
if not utils.ctftime():
if utils.view_after_ctf():
pass
else:
abort(403)
if utils.get_config('verify_emails'):
if utils.authed():
if utils.is_admin() is False and utils.is_verified() is False: # User is not confirmed
abort(403)
if utils.user_can_view_challenges() and (utils.ctf_started() or utils.is_admin()):
teamid = session.get('id')
comp = Competitions.query.filter(Competitions.id == compid).first()
if comp is None:
abort(403)
if comp.startTime>datetime.datetime.utcnow():
abort(403)
#chals=comp.chals
json = {
'competition': {
'id': comp.id,
'title': comp.title,
'description': comp.description,
'startTime': comp.startTime,
'endTime': comp.endTime
},
'game': []
}
for x in comp.chals:
chal = Challenges.query.filter(Challenges.id == x.chalid).first()
if chal is None:
abort(502)
tags = [tag.tag for tag in Tags.query.add_columns('tag').filter(Tags.chal == chal.id).all()]
files = [str(f.location) for f in Files.query.filter(Files.chal == chal.id).all()]
unlocked_hints = set([u.itemid for u in Unlocks.query.filter(Unlocks.model == 'hints', Unlocks.teamid == teamid)])
hints = []
for hint in Hints.query.filter(Hints.chal == chal.id).all():
if hint.id in unlocked_hints or utils.ctf_ended():
hints.append({'id': hint.id, 'cost': hint.cost, 'hint': hint.hint})
else:
hints.append({'id': hint.id, 'cost': hint.cost})
chal_type = get_chal_class(chal.type)
json['game'].append({
'id': chal.id,
'type': chal_type.name,
'name': chal.name,
'value': chal.value,
'description': chal.description,
'category': chal.category,
'files': files,
'tags': tags,
'hints': hints,
'template': chal_type.templates['modal'],
'script': chal_type.scripts['modal'],
})
db.session.close()
return jsonify(json)
else:
db.session.close()
abort(403)
@competitions.route('/admin/competitions/add', methods=['GET','POST'])
@admins_only
def addComp():
if request.method == 'GET':
return render_template('add_comp.html')
elif request.method == 'POST':
title = request.form.get('title')
description = request.form.get('description')
startTime = request.form.get('startTime')
endTime = request.form.get('endTime')
pic=request.files['profile']
picdir=os.path.dirname(__file__)+"/assets/pics/"+secure_filename(pic.filename)
pic.save(picdir)
profile=secure_filename(pic.filename)
print picdir
print picdir
comp = Competitions(title, description)
comp.startTime = datetime.datetime.strptime(startTime, '%Y-%m-%d %H:%M:%S')
comp.endTime = datetime.datetime.strptime(endTime, '%Y-%m-%d %H:%M:%S')
comp.profile = profile
db.session.add(comp)
db.session.flush()
db.session.commit()
return redirect('/admin/competitions')
@competitions.route('/test')
def test1():
return os.path.dirname(__file__)
@competitions.route('/admin/competitions/<int:compid>/del',methods=['DELETE'])
@admins_only
def del_comp(compid):
try:
comp=Competitions.query.filter(Competitions.id==compid).first()
db.session.delete(comp)
chalcomps=Chalcomp.query.filter(Chalcomp.compid==compid).all()
for x in chalcomps:
x.compid=1
db.session.commit()
return jsonify({'res':'success'})
except Exception,e:
return jsonify({'res':'fail'})
@competitions.route('/admin/competitions/<int:compid>/edit',methods=['GET','POST'])
@admins_only
def editcomp(compid):
comp=Competitions.query.filter(Competitions.id==compid).first()
if comp is None:
abort(403)
if(request.method=='GET'):
return render_template('/add_comp.html',comp=comp)
else:
title = request.form.get('title')
description = request.form.get('description')
startTime = request.form.get('startTime')
endTime = request.form.get('endTime')
pic=request.files['profile']
picdir=os.path.dirname(__file__)+"/assets/pics/"+secure_filename(pic.filename)
pic.save(picdir)
profile=secure_filename(pic.filename)
print picdir
print picdir
comp.title = title
comp.description = description
comp.startTime = datetime.datetime.strptime(startTime, '%Y-%m-%d %H:%M:%S')
comp.endTime = datetime.datetime.strptime(endTime, '%Y-%m-%d %H:%M:%S')
comp.profile = profile
db.session.commit()
return redirect('/admin/competitions')
@competitions.route('/competitions/<int:compid>/scores')
def scores(compid):
json = {'standings': []}
if utils.get_config('view_scoreboard_if_authed') and not utils.authed():
return redirect(url_for('auth.login', next=request.path))
if utils.hide_scores():
return jsonify(json)
standings = get_range(comp=compid)
for i, x in enumerate(standings):
json['standings'].append(
{'pos': i + 1, 'id': x.teamid, 'team': x.name, 'score': int(x.score)})
return jsonify(json)
@competitions.route('/competitions/<int:compid>/top/<int:count>')
def topteams(compid, count):
json = {'places': {}}
if utils.get_config('view_scoreboard_if_authed') and not utils.authed():
return redirect(url_for('auth.login', next=request.path))
if utils.hide_scores():
return jsonify(json)
if count > 20 or count < 0:
count = 10
standings = get_range(comp=compid, count=count)
team_ids = [team.teamid for team in standings]
chalids = [chal.chalid for chal in Chalcomp.query.filter(
Chalcomp.compid == compid)]
solves = Solves.query.filter(Solves.teamid.in_(team_ids))
solves = Solves.query.filter(Solves.chalid.in_(chalids))
awards = Awards.query.filter(Awards.teamid.in_(team_ids))
freeze = utils.get_config('freeze')
if freeze:
solves = solves.filter(Solves.date < utils.unix_time_to_utc(freeze))
awards = awards.filter(Awards.date < utils.unix_time_to_utc(freeze))
solves = solves.all()
awards = awards.all()
for i, team in enumerate(team_ids):
json['places'][i + 1] = {
'id': standings[i].teamid,
'name': standings[i].name,
'solves': []
}
for solve in solves:
if solve.teamid == team:
json['places'][i + 1]['solves'].append({
'chal': solve.chalid,
'team': solve.teamid,
'value': solve.chal.value,
'time': utils.unix_time(solve.date)
})
for award in awards:
if award.teamid == team:
json['places'][i + 1]['solves'].append({
'chal': None,
'team': award.teamid,
'value': award.value,
'time': utils.unix_time(award.date)
})
json['places'][i +1]['solves'] = sorted(json['places'][i + 1]['solves'], key=lambda k: k['time'])
return jsonify(json)
@competitions.route('/competitions/<int:compid>/scoreboard')
def comp_scoreboard(compid):
if utils.get_config('view_scoreboard_if_authed') and not utils.authed():
return redirect(url_for('auth.login', next=request.path))
if utils.hide_scores():
print 'error!'
return render_template('compet_scoreboard.html', errors=['Scores are currently hidden'])
comp=Competitions.query.filter(Competitions.id==compid).first()
if comp is None:
abort(404)
standings = get_range(comp=compid)
return render_template('compet_scoreboard.html', teams=standings, score_frozen=utils.is_scoreboard_frozen(),comp=comp)
@competitions.route('/admin/competitions/<int:compid>/chal/delete',methods=['POST'])
@admins_only
def remove_chal(compid):
chal=Chalcomp().query.filter(Chalcomp.compid==compid).filter(Chalcomp.chalid==request.form['id']).one()
print "queried"
if not chal:
abort(403)
else:
db.session.delete(chal)
db.session.commit()
db.session.close()
return '1'
@competitions.route('/competitions/<int:compid>/chalboard/solves/<int:teamid>')
def team_solves(compid, teamid):
json = {'solves': []}
if utils.get_config('view_scoreboard_if_authed') and not utils.authed():
return redirect(url_for('auth.login', next=request.path))
if utils.hide_scores():
return jsonify(json)
chalids = [chal.chalid for chal in Chalcomp.query.filter(
Chalcomp.compid == compid)]
solves = Solves.query.filter(Solves.teamid == teamid)
awards = Awards.query.filter(Awards.teamid == teamid)
solves = solves.filter(Solves.chalid.in_(chalids))
freeze = utils.get_config('freeze')
if freeze:
solves = solves.filter(Solves.date < utils.unix_time_to_utc(freeze))
awards = awards.filter(Awards.date < utils.unix_time_to_utc(freeze))
solves = solves.all()
awards = awards.all()
for solve in solves:
json['solves'].append({
'chal': solve.chalid,
'team': solve.teamid,
'value': solve.chal.value,
'time': utils.unix_time(solve.date)
})
for award in awards:
json['solves'].append({
'chal': None,
'team': award.teamid,
'value': award.value,
'time': utils.unix_time(award.date)
})
json['solves'] = sorted(json['solves'], key=lambda k: k['time'])
return jsonify(json)
@competitions.route('/competitions/<int:compid>/solves')
@competitions.route('/competitions/<int:compid>/solves/<int:teamid>')
def solves(compid,teamid=None):
solves = None
awards = None
comp=Competitions.query.filter(Competitions.id==compid).first()
if comp is None:
abort(403)
if teamid is None:
if utils.is_admin():
solves = Solves.query.filter_by(teamid=session['id']).all()
elif utils.user_can_view_challenges():
if utils.authed():
chalids = [chal.chalid for chal in Chalcomp.query.filter(
Chalcomp.compid == compid)]
solves = Solves.query.join(Teams, Solves.teamid == Teams.id).filter(Solves.teamid == session['id'], Teams.banned == False,Solves.chalid.in_(chalids)).all()
else:
return jsonify({'solves': []})
else:
return redirect(url_for('auth.login', next=request.path))
else:
if utils.authed() and session['id'] == teamid:
solves = Solves.query.filter_by(teamid=teamid)
awards = Awards.query.filter_by(teamid=teamid)
freeze = utils.get_config('freeze')
if freeze:
freeze = utils.unix_time_to_utc(freeze)
if teamid != session.get('id'):
solves = solves.filter(Solves.date < freeze)
awards = awards.filter(Awards.date < freeze)
chalids = [chal.chalid for chal in Chalcomp.query.filter(
Chalcomp.compid == compid)]
print chalids
solves=solves.filter(Solves.chalid.in_(chalids))
solves = solves.all()
awards = awards.all()
elif utils.hide_scores():
# Use empty values to hide scores
solves = []
awards = []
else:
solves = Solves.query.filter_by(teamid=teamid)
awards = Awards.query.filter_by(teamid=teamid)
freeze = utils.get_config('freeze')
if freeze:
freeze = utils.unix_time_to_utc(freeze)
if teamid != session.get('id'):
solves = solves.filter(Solves.date < freeze)
awards = awards.filter(Awards.date < freeze)
chalids = [chal.chalid for chal in Chalcomp.query.filter(
Chalcomp.compid == compid)]
print chalids
solves=solves.filter(Solves.chalid.in_(chalids))
solves = solves.all()
awards = awards.all()
db.session.close()
json = {'solves': []}
for solve in solves:
json['solves'].append({
'chal': solve.chal.name,
'chalid': solve.chalid,
'team': solve.teamid,
'value': solve.chal.value,
'category': solve.chal.category,
'time': utils.unix_time(solve.date)
})
if awards:
for award in awards:
json['solves'].append({
'chal': award.name,
'chalid': None,
'team': award.teamid,
'value': award.value,
'category': award.category or "Award",
'time': utils.unix_time(award.date)
})
json['solves'].sort(key=lambda k: k['time'])
return jsonify(json)
@competitions.route('/admin/competitions/<int:compid>/chals', methods=['POST', 'GET'])
@admins_only
def admin_chals(compid):
comp=Competitions.query.filter(Competitions.id==compid).first()
if not comp:
abort(403)
if request.method == 'POST':
chalids=[x.chalid for x in Chalcomp.query.filter(Chalcomp.compid==compid).all()]
chals = Challenges.query.filter(Challenges.id.in_(chalids)).order_by(Challenges.value).all()
json_data = {'game': []}
for chal in chals:
tags = [tag.tag for tag in Tags.query.add_columns('tag').filter_by(chal=chal.id).all()]
files = [str(f.location) for f in Files.query.filter_by(chal=chal.id).all()]
hints = []
for hint in Hints.query.filter_by(chal=chal.id).all():
hints.append({'id': hint.id, 'cost': hint.cost, 'hint': hint.hint})
type_class = CHALLENGE_CLASSES.get(chal.type)
type_name = type_class.name if type_class else None
json_data['game'].append({
'id': chal.id,
'name': chal.name,
'value': chal.value,
'description': chal.description,
'category': chal.category,
'files': files,
'tags': tags,
'hints': hints,
'hidden': chal.hidden,
'max_attempts': chal.max_attempts,
'type': chal.type,
'type_name': type_name,
'type_data': {
'id': type_class.id,
'name': type_class.name,
'templates': type_class.templates,
'scripts': type_class.scripts,
}
})
db.session.close()
return jsonify(json_data)
else:
chalids=[x.chalid for x in Chalcomp.query.filter(Chalcomp.compid==compid).all()]
challenges = Challenges.query.filter(Challenges.id.in_(chalids)).all()
return render_template('admin_chals.html', challenges=challenges,comp=comp)
@competitions.route('/admin/competitions/<int:compid>/chal/new', methods=['GET', 'POST'])
@admins_only
def admin_create_chal(compid):
comp=Competitions.query.filter(Competitions.id==compid).first()
if not comp:
abort(403)
if request.method == 'POST':
for x in request.values.getlist('chals'):
chalcomp=Chalcomp()
chalcomp.chalid=x
chalcomp.compid=compid
db.session.add(chalcomp)
db.session.commit()
db.session.flush()
#chal_type = request.form['chaltype']
#chal_class = get_chal_class(chal_type)
#chal_class.create(request)
#chalid=db.session.query(db.func.max(Challenges.id)).one()[0]
#chalcomp=Chalcomp()
#chalcomp.chalid=chalid
#chalcomp.compid=compid
#db.session.add(chalcomp)
#db.session.commit()
#db.session.flush()
return redirect('/admin/competitions/'+str(compid)+'/chals')
else:
chalcomps=Chalcomp.query.all()
oldlist=[x.chalid for x in chalcomps]
newchals=Challenges.query.filter(~Challenges.id.in_(oldlist)).all()
return render_template('add_chals.html',comp=comp,chals=newchals)
def load(app):
register_plugin_assets_directory(
app, base_path='/plugins/competitions/assets/')
app.register_blueprint(competitions)
app.db.create_all()