forked from dbaseqp/Quotient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutes.go
1236 lines (1079 loc) · 33.7 KB
/
routes.go
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
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/BurntSushi/toml"
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
"gorm.io/gorm"
)
var (
// Adjustments to process
manualAdjustments map[uint]int
engineMutex = &sync.Mutex{}
stream = NewSSEServer()
)
func addViewRoutes(router *gin.RouterGroup) {
router.GET("/", viewIndex)
router.GET("/login", viewLogin)
if !eventConf.DisableHeadToHead {
router.GET("/scoreboard", viewScoreboard) // need to implement public headtoheads
}
}
func addViewRoutesTeam(router *gin.RouterGroup) {
router.GET("/announcements", viewAnnouncements)
router.GET("/injects", viewInjects)
router.GET("/injects/:injectid", viewInject)
if eventConf.EasyPCR {
router.GET("/pcrs", viewPCRs)
}
router.GET("/overview", viewOverview)
if !eventConf.DisableHeadToHead {
router.Static("/plots", "./plots")
}
}
func addViewRoutesAdmin(router *gin.RouterGroup) {
router.GET("/engine", viewEngine)
if eventConf.DisableHeadToHead {
router.Static("/plots", "./plots")
}
if !eventConf.EasyPCR {
router.GET("/pcrs", viewPCRs)
}
}
// POST routes have structs defined to specifically handle their received data
// These "form" structs will then be mapped to the internal database struct and used internally
func addPublicRoutes(router *gin.RouterGroup) {
// authentication
router.POST("/login", login)
}
func addAuthRoutes(router *gin.RouterGroup) {
// sse
router.GET("/sse", stream.ServeHTTP(), sse)
// authentication
router.GET("/logout", logout)
// team portal
router.GET("/teams/:teamid/scores/uptime", getTeamUptime)
router.GET("/teams/:teamid/scores/sla", getTeamSLA)
router.GET("/teams/:teamid/scores/rounds/:count", getTeamRounds) // maybe turn this into a get parameter
router.GET("/teams/:teamid/scores/:servicename", getTeamService)
// inject portal
router.GET("/injects", getInjects)
router.GET("/injects/:injectid", getInject)
router.GET("/injects/:injectid/file/:filename", downloadInjectFile)
router.POST("/injects/:injectid/submit", submitInject)
router.GET("/injects/:injectid/:teamid", getTeamInjectSubmissions)
router.GET("/injects/:injectid/:teamid/submissions/:submissionid/:filename", downloadSubmissionFile)
// pcr portal
router.POST("/pcrs/submit", submitPCR)
}
func addAdminRoutes(router *gin.RouterGroup) {
// announcements
router.POST("/announcements/add", addAnnouncement)
router.DELETE("/announcements/:announcementid", deleteAnnouncement)
// team portal
router.POST("/teams/:teamid/edit", updateTeam)
router.DELETE("/teams/:teamid", deleteTeam) // admin
// admin portal
router.GET("/engine/export/scores", exportScores) // admin
router.GET("/engine/export/config", exportConfig) // admin
router.GET("/engine/config", getConfig) // admin
router.PUT("/engine/config", submitConfig) // admin
router.POST("/engine/addteam", addTeam) // admin
router.POST("/engine/adjustment", submitManualAdjustment)
router.POST("/engine/pause", pauseEngine)
router.POST("/engine/resume", resumeEngine)
router.POST("/engine/reset", resetEngine)
router.GET("/engine/services/:servicename", getServiceConfig)
router.POST("/engine/syncldap", syncLdap)
// inject portal
router.POST("/injects/add", addInject) // admin
router.POST("/injects/:injectid/edit", updateInject) // admin
router.DELETE("/injects/:injectid", deleteInject) // admin
router.POST("/injects/:injectid/:teamid/submissions/:submissionid/grade", gradeTeamInjectSubmission) // admin
}
func pauseEngine(c *gin.Context) {
engineMutex.Lock()
if enginePause {
c.JSON(http.StatusBadRequest, gin.H{"error": "Engine already paused"})
engineMutex.Unlock()
return
}
enginePauseWg.Add(1)
enginePause = true
engineMutex.Unlock()
log.Println("[ENGINE] ===== Engine paused")
SendSSE(gin.H{"admin": true, "page": "engine", "engine": false})
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func resumeEngine(c *gin.Context) {
engineMutex.Lock()
if !enginePause {
c.JSON(http.StatusBadRequest, gin.H{"error": "Engine already running"})
engineMutex.Unlock()
return
}
enginePauseWg.Done()
enginePause = false
engineMutex.Unlock()
log.Println("[ENGINE] ===== Engine resumed")
SendSSE(gin.H{"admin": true, "page": "engine", "engine": true})
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func resetEngine(c *gin.Context) {
// reset round number
log.Println("[ENGINE] ===== Event reset issued")
engineMutex.Lock()
initialEnginePause := enginePause // if engine was paused, stay paused
enginePause = true
for _, teamMap := range credentialsMutex {
for _, credlist := range teamMap {
credlist.Lock()
}
}
// delete db data
log.Println("[ENGINE] ===== Deleting database data")
err := dbResetScoring()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// delete inject submissions too?
// reset globals after all db transactions were successful
roundNumber = 0
enginePause = initialEnginePause
log.Println("[ENGINE] ===== Deleting PCRs")
for teamid, teamMap := range credentialsMutex {
for _, credlist := range teamMap {
os.RemoveAll(filepath.Join("submissions/pcrs", fmt.Sprint(teamid)))
credlist.Unlock()
}
}
log.Println("[ENGINE] ===== Deleting graphs")
plotDir, err := os.ReadDir("plots")
if err != nil {
log.Fatalln("Failed to open plots directory:", err)
}
for _, file := range plotDir {
if strings.HasSuffix(file.Name(), ".png") {
os.Remove(filepath.Join("plots", file.Name()))
}
}
log.Println("[ENGINE] ===== Reinitializing engine")
bootstrap()
engineMutex.Unlock()
log.Println("[ENGINE] ===== Event reset successfully")
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func syncLdap(c *gin.Context) {
if eventConf.LdapConnectUrl != "" {
err := dbLoadLdapTeams()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
debugPrint("Synced LDAP teams to DB")
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
}
func getServiceConfig(c *gin.Context) {
servicename := c.Param("servicename")
for _, box := range eventConf.Box {
for _, s := range box.Custom {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Dns {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Ftp {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Imap {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Ldap {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Ping {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Pop3 {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Rdp {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Smb {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Smtp {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Sql {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Ssh {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Tcp {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Vnc {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.Web {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
for _, s := range box.WinRM {
if s.Name == servicename {
c.JSON(http.StatusOK, s)
return
}
}
}
c.JSON(http.StatusBadRequest, gin.H{"error": "Service not found"})
}
// func updateServiceConfig(c *gin.Context) {
// type ServiceForm struct {
// Name string `json:"name"` // Name is the box name plus the service (ex. lunar-dns)
// Display string `json:"display"` // Display is the name of the service (ex. dns)
// FQDN string `json:"fqdn"`
// IP string `json:"ip"`
// CredLists []string `json:"credlists"`
// Port int `json:"port"`
// Anonymous bool `json:"anonymous"`
// Points int `json:"points"`
// SlaPenalty int `json:"slapenalty"`
// SlaThreshold int `json:"slathreshold"`
// LaunchTime time.Time `json:"launchtime"`
// StopTime time.Time `json:"stoptime"`
// Disabled bool `json:"disabled"`
// }
// var serviceForm ServiceForm
// if err := c.ShouldBindJSON(&serviceForm); err != nil {
// c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
// return
// }
// servicename := c.Param("servicename")
// for _, box := range eventConf.Box {
// for _, service := range box.CheckList {
// if service.ServiceName == servicename {
// service.Service = serviceForm.Service
// c.JSON(http.StatusOK, service.Service)
// return
// }
// }
// }
// c.JSON(http.StatusBadGateway, gin.H{"error": "Service not found"})
// }
func getConfig(c *gin.Context) {
c.JSON(http.StatusOK, eventConf)
}
func getTeamScore(c *gin.Context) {
teamid, _ := strconv.Atoi(c.Param("teamid"))
teamScore, err := dbGetTeamScore(teamid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// team based auth
claims, err := contextGetClaims(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !claims.Admin && claims.ID != uint(teamid) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
teamUptime := make(map[string]Uptime)
for _, check := range teamScore.Checks {
teamUptime[check.ServiceName] = uptime[uint(teamid)][check.ServiceName]
}
c.JSON(http.StatusOK, gin.H{"status": "success", "scores": teamScore, "uptime": teamUptime})
}
func exportScores(c *gin.Context) {
teams, err := dbGetTeams()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
type ScoreSummary struct {
ID uint
Name string
ServiceTotal int
AdjustmentTotal int
InjectTotal int
SLATotal int
}
var export []ScoreSummary
for _, team := range teams {
score, err := dbGetTeamScore(int(team.ID))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
var adjustmentTotal int
for _, adjustment := range score.ManualAdjustments {
adjustmentTotal += adjustment.Amount
}
var injectTotal int
for _, submission := range score.SubmissionData {
injectTotal += submission.Score
}
var slaTotal int
for _, sla := range score.SLAs {
slaTotal += sla.Penalty
}
export = append(export, ScoreSummary{ID: team.ID, Name: team.Name, ServiceTotal: score.CumulativeServiceScore, AdjustmentTotal: adjustmentTotal, InjectTotal: injectTotal, SLATotal: slaTotal})
}
jsonData, err := json.MarshalIndent(gin.H{"export": export}, "", " ")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
exportPath := "./temporary/scores.json"
os.WriteFile(exportPath, jsonData, 0644)
c.File(exportPath)
}
func exportConfig(c *gin.Context) {
buf := new(bytes.Buffer)
encoder := toml.NewEncoder(buf)
encoder.Indent = " "
if err := encoder.Encode(eventConf); err != nil {
c.JSON(http.StatusInternalServerError, err.Error())
return
}
exportPath := "./temporary/export.conf"
os.WriteFile(exportPath, buf.Bytes(), 0644)
c.File(exportPath)
}
func submitConfig(c *gin.Context) {
var configForm Config
// Read the JSON data from the request body
if err := c.ShouldBindJSON(&configForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := checkConfig(&configForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": strings.Split(err.Error(), "\n")})
return
}
configForm.Box = eventConf.Box
c.JSON(http.StatusOK, configForm)
}
func submitPCR(c *gin.Context) {
type PCRForm struct {
TeamID int `json:"teamid"`
CredList string `json:"credlist"`
Changes string `json:"changes"`
}
var pcrForm PCRForm
if err := c.ShouldBindJSON(&pcrForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// team based auth
claims, err := contextGetClaims(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if !claims.Admin && !eventConf.EasyPCR {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
var teamid uint
if claims.Admin {
teamid = uint(pcrForm.TeamID)
} else {
teamid = claims.ID
}
scanner := bufio.NewScanner(strings.NewReader(pcrForm.Changes))
for scanner.Scan() {
record := strings.SplitN(scanner.Text(), ",", 2)
// Process each line as needed
if _, ok := credentials[teamid][pcrForm.CredList][record[0]]; ok {
credentials[teamid][pcrForm.CredList][record[0]] = record[1]
}
}
teamSpecificCredlist := filepath.Join("submissions/pcrs", fmt.Sprint(teamid), pcrForm.CredList)
// Write the modified content back to the file
credentialsMutex[teamid][pcrForm.CredList].Lock()
file, err := os.Create(teamSpecificCredlist)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer file.Close()
for username, password := range credentials[teamid][pcrForm.CredList] {
_, err = file.WriteString(fmt.Sprintf("%s,%s\n", username, password))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
}
credentialsMutex[teamid][pcrForm.CredList].Unlock()
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func addAnnouncement(c *gin.Context) {
type AnnouncementForm struct {
Content string `json:"content"`
}
var announcementForm AnnouncementForm
// Read the JSON data from the request body
if err := c.ShouldBindJSON(&announcementForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if announcementForm.Content == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing announcement content"})
return
}
announcement := AnnouncementData{
Content: announcementForm.Content,
}
_, err := dbAddAnnouncement(announcement)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
SendSSE(gin.H{"admin": false, "page": "announcements"})
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func deleteAnnouncement(c *gin.Context) {
announcementid, _ := strconv.Atoi(c.Param("announcementid"))
err := dbDeleteAnnouncement(announcementid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func addTeam(c *gin.Context) {
type TeamForm struct {
Name string `json:"name"`
Pw string `json:"password"`
Identifier string `json:"identifier"`
//Token string `toml:"token,omitempty" json:"token,omitempty"`
}
var teamForm TeamForm
// Read the JSON data from the request body
if err := c.ShouldBindJSON(&teamForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if teamForm.Name == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing team name"})
return
}
if teamForm.Pw == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing team password"})
return
}
if teamForm.Identifier == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing team third octet"})
return
}
identifier, err := strconv.Atoi(teamForm.Identifier)
if identifier < 0 || identifier > 254 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid team third octet"})
return
}
team := TeamData{
Name: teamForm.Name,
Pw: teamForm.Pw,
Identifier: teamForm.Identifier,
}
_, err = dbAddTeam(team)
if err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Team name/IP must be unique"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "team": team})
}
func updateTeam(c *gin.Context) {
// optional fields, only update ones that are not zero-valued
type TeamForm struct {
Name string `form:"name"`
Password string `form:"password"`
Identifier string `form:"identifier"`
}
var teamForm TeamForm
teamid, _ := strconv.Atoi(c.Param("teamid"))
if err := c.ShouldBindJSON(&teamForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
team := TeamData{
ID: uint(teamid),
}
if teamForm.Name != "" {
team.Name = teamForm.Name
}
if teamForm.Password != "" {
team.Pw = teamForm.Password
}
if teamForm.Identifier != "" {
team.Identifier = teamForm.Identifier
}
err := dbUpdateTeam(team)
if err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Team name/IP must be unique"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func deleteTeam(c *gin.Context) {
teamid, _ := strconv.Atoi(c.Param("teamid"))
err := dbDeleteTeam(teamid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func addInject(c *gin.Context) {
type InjectForm struct {
Title string `form:"title" binding:"required"`
Description string `form:"description" binding:"required"`
OpenTime string `form:"opentime" binding:"required"`
DueTime string `form:"duetime" binding:"required"`
CloseTime string `form:"closetime" binding:"required"`
Files []*multipart.FileHeader `form:"files" binding:"required"`
}
var injectForm InjectForm
// Read the form data from the request body
if err := c.ShouldBind(&injectForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// realistically only error should be bad format
ot, err := time.Parse(time.RFC3339, injectForm.OpenTime)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing open time or wrong format"})
return
}
dt, err := time.Parse(time.RFC3339, injectForm.DueTime)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing due time or wrong format"})
return
}
ct, err := time.Parse(time.RFC3339, injectForm.CloseTime)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing close time or wrong format"})
return
}
if ot.After(dt) || dt.After(ct) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Open time must be before due time, and due time must be before close time"})
return
}
var filenames []string
for _, fileHeader := range injectForm.Files {
filenames = append(filenames, filepath.Base(fileHeader.Filename))
dst := filepath.Join("./injects", injectForm.Title, filepath.Base(fileHeader.Filename))
if err := c.SaveUploadedFile(fileHeader, dst); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
return
}
}
inject := InjectData{
Title: injectForm.Title,
Description: injectForm.Description,
OpenTime: ot.Truncate(time.Minute),
DueTime: dt.Truncate(time.Minute),
CloseTime: ct.Truncate(time.Minute),
InjectFileNames: filenames,
}
injectid, err := dbAddInject(inject)
if err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Inject name must be unique"})
return
}
// Delete uploaded files if database function fails
os.RemoveAll(filepath.Join("./injects", injectForm.Title))
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
teams, err := dbGetTeams() // consider creating teams map in memory to avoid database query
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
submissionMutex.Lock()
submissions[int(injectid)] = make(map[int]int)
for _, team := range teams {
submissions[int(injectid)][int(team.ID)] = 0
}
submissionMutex.Unlock()
SendSSE(gin.H{"admin": true, "page": "injects"})
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func getInjects(c *gin.Context) {
injects, err := dbGetInjects()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// TODO: if Admin return, otherwise remove injects not opened yet
c.JSON(http.StatusOK, injects)
}
func getInject(c *gin.Context) {
injectid, _ := strconv.Atoi(c.Param("injectid"))
inject, err := dbGetInject(injectid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// TODO: if Admin return, otherwise remove injects not opened yet
c.JSON(http.StatusOK, inject)
}
// currently does not support updating changing ID
func updateInject(c *gin.Context) {
// optional fields, only update ones that are not zero-valued
type InjectForm struct {
Title string `form:"title"`
Description string `form:"description"`
OpenTime string `form:"opentime"`
DueTime string `form:"duetime"`
CloseTime string `form:"closetime"`
Files []*multipart.FileHeader `form:"files"`
}
var injectForm InjectForm
injectid, _ := strconv.Atoi(c.Param("injectid"))
inject, err := dbGetInject(injectid)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if err := c.ShouldBind(&injectForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if injectForm.Title != "" {
inject.Title = injectForm.Title
}
if injectForm.Description != "" {
inject.Description = injectForm.Description
}
if injectForm.OpenTime != "" {
ot, err := time.Parse(time.RFC3339, injectForm.OpenTime)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Open time wrong format"})
return
}
inject.OpenTime = ot.Truncate(time.Minute)
}
if injectForm.DueTime != "" {
dt, err := time.Parse(time.RFC3339, injectForm.DueTime)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Due time wrong format"})
return
}
inject.DueTime = dt.Truncate(time.Minute)
}
if injectForm.CloseTime != "" {
ct, err := time.Parse(time.RFC3339, injectForm.CloseTime)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Close time wrong format"})
return
}
inject.CloseTime = ct.Truncate(time.Minute)
}
if inject.OpenTime.After(inject.DueTime) || inject.DueTime.After(inject.CloseTime) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Open time must be before due time, and due time must be before close time"})
return
}
if len(injectForm.Files) != 0 {
os.RemoveAll(filepath.Join("./injects", injectForm.Title))
var filenames []string
for _, fileHeader := range injectForm.Files {
filenames = append(filenames, filepath.Base(fileHeader.Filename))
dst := filepath.Join("./injects", injectForm.Title, filepath.Base(fileHeader.Filename))
if err := c.SaveUploadedFile(fileHeader, dst); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
return
}
}
inject.InjectFileNames = filenames
}
err = dbUpdateInject(inject)
if err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Inject name must be unique"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func submitInject(c *gin.Context) {
type InjectSubmissionForm struct {
Files []*multipart.FileHeader `form:"files" binding:"required"`
}
var submissionForm InjectSubmissionForm
submissionTime := time.Now()
injectid, _ := strconv.Atoi(c.Param("injectid"))
inject, err := dbGetInject(injectid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if submissionTime.After(inject.CloseTime) {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Inject '%s' cannot accept submission after its close time", inject.Title)})
return
}
if err := c.ShouldBind(&submissionForm); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// team based auth
claims, err := contextGetClaims(c)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
teamid := int(claims.ID)
submissionid := submissions[injectid][teamid] + 1
var filenames []string
for _, fileHeader := range submissionForm.Files {
filenames = append(filenames, filepath.Base(fileHeader.Filename))
dst := filepath.Join("./submissions", inject.Title, fmt.Sprint(teamid), fmt.Sprint("attempt", fmt.Sprint(submissionid)), filepath.Base(fileHeader.Filename))
if err := c.SaveUploadedFile(fileHeader, dst); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
return
}
}
submission := SubmissionData{
TeamID: uint(teamid),
InjectID: uint(injectid),
SubmissionTime: submissionTime,
SubmissionFileNames: filenames,
AttemptNumber: submissionid,
}
err = dbSubmitInject(submission)
if err != nil {
// Delete uploaded files if database function fails
os.RemoveAll(filepath.Join("./submissions", fmt.Sprint(injectid), fmt.Sprint(teamid), fmt.Sprint("attempt", fmt.Sprint(submissionid))))
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
submissionMutex.Lock()
submissions[injectid][teamid] = submissionid
submissionMutex.Unlock()
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
// consider preventing how inject deletion might work during competition after submissions have been made
func deleteInject(c *gin.Context) {
injectid, _ := strconv.Atoi(c.Param("injectid"))
inject, err := dbGetInject(injectid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
err = dbDeleteInject(injectid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
os.RemoveAll(filepath.Join("./injects", inject.Title))
c.JSON(http.StatusOK, gin.H{"status": "success"})
}
func getTeamInjectSubmissions(c *gin.Context) {
teamid, _ := strconv.Atoi(c.Param("teamid"))
injectid, _ := strconv.Atoi(c.Param("injectid"))
// team based auth
claims, err := contextGetClaims(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !claims.Admin && claims.ID != uint(teamid) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
return
}
teamInjectSubmissions, err := dbGetInjectSubmissions(injectid, teamid)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"status": "success", "submissions": teamInjectSubmissions})
}
// grader
// score
// feedback
func gradeTeamInjectSubmission(c *gin.Context) {
type SubmissionForm struct {
Grader string `json:"grader"` // required will be handled by admin frontend here
Score int `json:"score"` // required will be handled by admin frontend here
Feedback string `json:"feedback"` // required will be handled by admin frontend here
}
var gradedSubmissionForm SubmissionForm
teamid, _ := strconv.Atoi(c.Param("teamid"))
injectid, _ := strconv.Atoi(c.Param("injectid"))
submissionid, _ := strconv.Atoi(c.Param("submissionid"))