Skip to content

Commit 8705fe9

Browse files
authored
Merge pull request #95 from Luminic/fix-empty-vote
added check to make sure that votes are not empty
2 parents 7931034 + abc69fe commit 8705fe9

1 file changed

Lines changed: 14 additions & 12 deletions

File tree

‎main.go‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,7 @@ func main() {
346346
UserId: claims.UserInfo.Username,
347347
}
348348

349+
// Populate vote
349350
for _, option := range poll.Options {
350351
optionRankStr := c.PostForm(option)
351352
optionRank, err := strconv.Atoi(optionRankStr)
@@ -360,7 +361,6 @@ func main() {
360361

361362
vote.Options[option] = optionRank
362363
}
363-
364364
// process write-in
365365
if c.PostForm("writeinOption") != "" && c.PostForm("writein") != "" {
366366
for candidate := range vote.Options {
@@ -380,30 +380,32 @@ func main() {
380380
}
381381
vote.Options[c.PostForm("writeinOption")] = rank
382382
}
383+
// Perform checks, vote does not change beyond this
384+
385+
optionCount := len(vote.Options)
386+
voted := make([]bool, optionCount)
383387

384-
maxNum := len(vote.Options)
385-
voted := make([]bool, maxNum)
388+
// Make sure vote is not empty
389+
if optionCount == 0 {
390+
c.JSON(http.StatusBadRequest, gin.H{"error": "You did not rank any options"})
391+
return
392+
}
386393

394+
// Duplicate ranks and range check
387395
for _, rank := range vote.Options {
388-
if rank > 0 && rank <= maxNum {
396+
if rank > 0 && rank <= optionCount {
389397
if voted[rank-1] {
390398
c.JSON(http.StatusBadRequest, gin.H{"error": "You ranked two or more candidates at the same level"})
391399
return
392400
}
393401
voted[rank-1] = true
394402
} else {
395-
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("votes must be from 1 - %d", maxNum)})
403+
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Candidates chosen must be from 1 to %d", optionCount)})
396404
return
397405
}
398406
}
399407

400-
rankedCandidates := len(vote.Options)
401-
for _, voteOpt := range vote.Options {
402-
if voteOpt > rankedCandidates {
403-
c.JSON(http.StatusBadRequest, gin.H{"error": "Rank choice is more than the amount of candidates ranked"})
404-
return
405-
}
406-
}
408+
// Submit Vote
407409
database.CastRankedVote(c, &vote, &voter)
408410
} else {
409411
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unknown Poll Type"})

0 commit comments

Comments
 (0)