-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathapi.go
More file actions
587 lines (516 loc) · 16.3 KB
/
api.go
File metadata and controls
587 lines (516 loc) · 16.3 KB
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
package main
import (
"context"
"encoding/json"
"fmt"
"math"
"net/http"
"slices"
"sort"
"strconv"
"strings"
"time"
cshAuth "github.com/computersciencehouse/csh-auth"
"github.com/computersciencehouse/vote/database"
"github.com/computersciencehouse/vote/logging"
"github.com/computersciencehouse/vote/sse"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/bson/primitive"
)
// Gets the number of people eligible to vote in a poll
func GetVoterCount(poll database.Poll) int {
return len(poll.AllowedUsers)
}
// Calculates the number of votes required for quorum in a poll
func CalculateQuorum(poll database.Poll) int {
voterCount := GetVoterCount(poll)
return int(math.Ceil(float64(voterCount) * poll.QuorumType))
}
// GetHomepage Displays the main page of the application, containing a list of all currently open polls
func GetHomepage(c *gin.Context) {
// This is intentionally left unprotected
// A user may be unable to vote but should still be able to see a list of polls
user := GetUserData(c)
polls, err := database.GetOpenPolls(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
sort.Slice(polls, func(i, j int) bool {
return polls[i].Id > polls[j].Id
})
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"Polls": polls,
"Username": user.Username,
"FullName": user.FullName,
"EBoard": IsEboard(user),
})
}
// GetClosedPolls Displays a page containing a list of all closed polls that the user created or voted in
func GetClosedPolls(c *gin.Context) {
user := GetUserData(c)
closedPolls, err := database.GetClosedVotedPolls(c, user.Username)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
ownedPolls, err := database.GetClosedOwnedPolls(c, user.Username)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
closedPolls = append(closedPolls, ownedPolls...)
sort.Slice(closedPolls, func(i, j int) bool {
return closedPolls[i].Id > closedPolls[j].Id
})
closedPolls = uniquePolls(closedPolls)
c.HTML(http.StatusOK, "closed.tmpl", gin.H{
"ClosedPolls": closedPolls,
"Username": user.Username,
"FullName": user.FullName,
"EBoard": IsEboard(user),
})
}
// GetPollById Retreives the information about a specific poll and displays it on the page, allowing the user to cast a ballot
//
// If the user is not eligible to vote in a particular poll, they are automatically redirected to the results page for that poll
func GetPollById(c *gin.Context) {
user := GetUserData(c)
// This is intentionally left unprotected
// We will check if a user can vote and redirect them to results if not later
poll, err := database.GetPoll(c, c.Param("id"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// If the user can't vote, just show them results
if canVote(user, *poll, poll.AllowedUsers) > 0 || !poll.Open {
c.Redirect(http.StatusFound, "/results/"+poll.Id)
return
}
writeInAdj := 0
if poll.AllowWriteIns {
writeInAdj = 1
}
canModify := IsActiveRTP(user) || IsEboard(user) || ownsPoll(poll, user)
c.HTML(200, "poll.tmpl", gin.H{
"Id": poll.Id,
"Title": poll.Title,
"Description": poll.Description,
"Options": poll.Options,
"PollType": poll.VoteType,
"RankedMax": fmt.Sprint(len(poll.Options) + writeInAdj),
"AllowWriteIns": poll.AllowWriteIns,
"CanModify": canModify,
"Username": user.Username,
"FullName": user.FullName,
"EBoard": IsEboard(user),
})
}
// CreatePoll Submits the specific details of a new poll that a user wants to create to the database
func CreatePoll(c *gin.Context) {
user := GetUserData(c)
// If user is not active, display the unauthorized screen
if !IsActive(user) {
c.HTML(http.StatusForbidden, "unauthorized.tmpl", gin.H{
"Username": user.Username,
"FullName": user.FullName,
"EBoard": IsEboard(user),
})
return
}
quorumType := c.PostForm("quorumType")
quorum, err := strconv.ParseFloat(quorumType, 64)
quorum = quorum / 100
poll := &database.Poll{
Id: "",
CreatedBy: user.Username,
Title: c.PostForm("title"),
Description: c.PostForm("description"),
VoteType: database.POLL_TYPE_SIMPLE,
OpenedTime: time.Now(),
Open: true,
QuorumType: quorum,
Gatekeep: c.PostForm("gatekeep") == "true",
AllowWriteIns: c.PostForm("allowWriteIn") == "true",
Hidden: c.PostForm("hidden") == "true",
}
if c.PostForm("rankedChoice") == "true" {
poll.VoteType = database.POLL_TYPE_RANKED
}
switch c.PostForm("options") {
case "pass-fail-conditional":
poll.Options = []string{"Pass", "Fail/Conditional", "Abstain"}
case "fail-conditional":
poll.Options = []string{"Fail", "Conditional", "Abstain"}
case "custom":
poll.Options = []string{}
for opt := range strings.SplitSeq(c.PostForm("customOptions"), ",") {
poll.Options = append(poll.Options, strings.TrimSpace(opt))
if !slices.Contains(poll.Options, "Abstain") && (poll.VoteType == database.POLL_TYPE_SIMPLE) {
poll.Options = append(poll.Options, "Abstain")
}
}
case "pass-fail":
default:
poll.Options = []string{"Pass", "Fail", "Abstain"}
}
if poll.Gatekeep {
if !IsEboard(user) {
c.HTML(http.StatusForbidden, "unauthorized.tmpl", gin.H{
"Username": user.Username,
"FullName": user.FullName,
"EBoard": IsEboard(user),
})
return
}
poll.AllowedUsers = GetEligibleVoters()
for user := range strings.SplitSeq(c.PostForm("waivedUsers"), ",") {
poll.AllowedUsers = append(poll.AllowedUsers, strings.TrimSpace(user))
}
}
pollId, err := database.CreatePoll(c, poll)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.Redirect(http.StatusFound, "/poll/"+pollId)
}
// GetCreatePage Displays the poll creation page to the user
func GetCreatePage(c *gin.Context) {
user := GetUserData(c)
// If the user is not active, display the unauthorized page
if !IsActive(user) {
c.HTML(http.StatusForbidden, "unauthorized.tmpl", gin.H{
"Username": user.Username,
"FullName": user.FullName,
"EBoard": IsEboard(user),
})
return
}
c.HTML(http.StatusOK, "create.tmpl", gin.H{
"Username": user.Username,
"FullName": user.FullName,
"EBoard": IsEboard(user),
})
}
// GetPollResults Displays the results page for a specific poll
func GetPollResults(c *gin.Context) {
user := GetUserData(c)
// This is intentionally left unprotected
// A user may be unable to vote but still interested in the results of a poll
poll, err := database.GetPoll(c, c.Param("id"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
results, err := poll.GetResult(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
canModify := IsActiveRTP(user) || IsEboard(user) || ownsPoll(poll, user)
if poll.Hidden && poll.Open {
c.HTML(http.StatusUnauthorized, "hidden.tmpl", gin.H{
"Id": poll.Id,
"Title": poll.Title,
"Description": poll.Description,
"Username": user.Username,
"FullName": user.FullName,
})
return
}
numVotes := 0
for _, v := range results {
for key := range v {
numVotes += v[key]
}
}
c.HTML(http.StatusOK, "result.tmpl", gin.H{
"Id": poll.Id,
"Title": poll.Title,
"Description": poll.Description,
"VoteType": poll.VoteType,
"Results": results,
"NumVotes": numVotes,
"IsOpen": poll.Open,
"IsHidden": poll.Hidden,
"CanModify": canModify,
"CanVote": canVote(user, *poll, poll.AllowedUsers),
"Username": user.Username,
"FullName": user.FullName,
"EBoard": IsEboard(user),
"Gatekeep": poll.Gatekeep,
"Quorum": strconv.FormatFloat(poll.QuorumType*100.0, 'f', 0, 64),
"EligibleVoters": poll.AllowedUsers,
"VotesNeededForQuorum": CalculateQuorum(*poll),
})
}
// VoteInPoll Submits a users' vote in a specific poll
func VoteInPoll(c *gin.Context) {
user := GetUserData(c)
poll, err := database.GetPoll(c, c.Param("id"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if canVote(user, *poll, poll.AllowedUsers) > 0 || !poll.Open {
c.Redirect(http.StatusFound, "/results/"+poll.Id)
return
}
pId, err := primitive.ObjectIDFromHex(poll.Id)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if poll.VoteType == database.POLL_TYPE_SIMPLE {
processSimpleVote(c, poll, pId, user)
} else if poll.VoteType == database.POLL_TYPE_RANKED {
processRankedVote(c, poll, pId, user)
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Unknown Poll Type"})
return
}
if poll, err := database.GetPoll(c, c.Param("id")); err == nil {
if results, err := poll.GetResult(c); err == nil {
if bytes, err := json.Marshal(results); err == nil {
broker.Notifier <- sse.NotificationEvent{
EventName: poll.Id,
Payload: string(bytes),
}
}
}
}
c.Redirect(http.StatusFound, "/results/"+poll.Id)
}
// HidePollResults Makes the results for a particular poll hidden until the poll closes
//
// If results are hidden, navigating to the results page of that poll will show
// a page informing the user that the results are hidden, instead of the actual results
func HidePollResults(c *gin.Context) {
user := GetUserData(c)
poll, err := database.GetPoll(c, c.Param("id"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if !ownsPoll(poll, user) {
c.JSON(http.StatusForbidden, gin.H{"error": "Only the creator can hide a poll result"})
return
}
err = poll.Hide(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
pId, _ := primitive.ObjectIDFromHex(poll.Id)
action := database.Action{
Id: "",
PollId: pId,
Date: primitive.NewDateTimeFromTime(time.Now()),
User: user.Username,
Action: "Hide Results",
}
err = database.WriteAction(c, &action)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.Redirect(http.StatusFound, "/results/"+poll.Id)
}
// ClosePoll Sets a poll to no longer allow votes to be cast
func ClosePoll(c *gin.Context) {
user := GetUserData(c)
// This is intentionally left unprotected
// A user should be able to end their own polls, regardless of if they can vote
poll, err := database.GetPoll(c, c.Param("id"))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
if poll.Gatekeep {
c.JSON(http.StatusForbidden, gin.H{"error": "This poll cannot be closed manually"})
return
}
if !ownsPoll(poll, user) {
if !IsActiveRTP(user) && !IsEboard(user) {
c.JSON(http.StatusForbidden, gin.H{"error": "You cannot end this poll."})
return
}
}
err = poll.Close(c)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
pId, _ := primitive.ObjectIDFromHex(poll.Id)
action := database.Action{
Id: "",
PollId: pId,
Date: primitive.NewDateTimeFromTime(time.Now()),
User: user.Username,
Action: "Close/End Poll",
}
err = database.WriteAction(c, &action)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.Redirect(http.StatusFound, "/results/"+poll.Id)
}
// ProcessSimpleVote Parses a simple ballot, validates it, and sends it to the database
func processSimpleVote(c *gin.Context, poll *database.Poll, pId primitive.ObjectID, user cshAuth.CSHUserInfo) {
vote := database.SimpleVote{
Id: "",
PollId: pId,
Option: c.PostForm("option"),
}
voter := database.Voter{
PollId: pId,
UserId: user.Username,
}
if hasOption(poll, c.PostForm("option")) {
vote.Option = c.PostForm("option")
} else if poll.AllowWriteIns && c.PostForm("option") == "writein" {
vote.Option = c.PostForm("writeinOption")
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Option"})
return
}
database.CastSimpleVote(c, &vote, &voter)
}
// ProcessRankedVote Parses the ranked choice ballot, validates it, and then sends it to the database
func processRankedVote(c *gin.Context, poll *database.Poll, pId primitive.ObjectID, user cshAuth.CSHUserInfo) {
vote := database.RankedVote{
Id: "",
PollId: pId,
Options: make(map[string]int),
}
voter := database.Voter{
PollId: pId,
UserId: user.Username,
}
// Populate vote
for _, option := range poll.Options {
optionRankStr := c.PostForm(option)
optionRank, err := strconv.Atoi(optionRankStr)
if len(optionRankStr) < 1 {
continue
}
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "non-number ranking"})
return
}
vote.Options[option] = optionRank
}
// process write-in
if c.PostForm("writeinOption") != "" && c.PostForm("writein") != "" {
for candidate := range vote.Options {
if strings.EqualFold(candidate, strings.TrimSpace(c.PostForm("writeinOption"))) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Write-in is already an option"})
return
}
}
rank, err := strconv.Atoi(c.PostForm("writein"))
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Write-in rank is not numerical"})
return
}
if rank < 1 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Write-in rank is not positive"})
return
}
vote.Options[c.PostForm("writeinOption")] = rank
}
validateRankedBallot(c, vote)
// Submit Vote
database.CastRankedVote(c, &vote, &voter)
}
// ValidateRankedBallot Verifies that the ranked choice ballot a user is attempting to submit is a valid ranked choice vote
//
// Specifically, it checks that the ballot is not empty, that there are no duplicate rankings, and that all rankings are between 1 and the total number of candidates
func validateRankedBallot(c *gin.Context, vote database.RankedVote) {
// Perform checks, vote does not change beyond this
optionCount := len(vote.Options)
voted := make([]bool, optionCount)
// Make sure vote is not empty
if optionCount == 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "You did not rank any options"})
return
}
// Duplicate ranks and range check
for _, rank := range vote.Options {
if rank > 0 && rank <= optionCount {
if rank > optionCount {
c.JSON(http.StatusBadRequest, gin.H{"error": "Rank choice is more than the amount of candidates ranked"})
return
}
if voted[rank-1] {
c.JSON(http.StatusBadRequest, gin.H{"error": "You ranked two or more candidates at the same level"})
return
}
voted[rank-1] = true
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("Candidates chosen must be from 1 to %d", optionCount)})
return
}
}
}
// canVote determines whether a user can cast a vote.
//
// Returns an integer value that indicates what the result is
// 0 -> User is allowed to vote (success)
// 1 -> Database error
// 3 -> User is not active
// 4 -> User doesnt meet gatekeep
// 9 -> User has already voted
func canVote(user cshAuth.CSHUserInfo, poll database.Poll, allowedUsers []string) int {
// always false if user is not active
if !DEV_DISABLE_ACTIVE_FILTERS && !IsActive(user) {
return 3
}
voted, err := database.HasVoted(context.Background(), poll.Id, user.Username)
if err != nil {
logging.Logger.WithFields(logrus.Fields{"method": "canVote"}).Error(err)
return 1
}
if voted {
return 9
}
if poll.Gatekeep { //if gatekeep is enabled, but they aren't allowed to vote in the poll, false
if !slices.Contains(allowedUsers, user.Username) {
return 4
}
} //otherwise true
return 0
}
// ownsPoll Returns whether a user is the owner of a particular poll
func ownsPoll(poll *database.Poll, user cshAuth.CSHUserInfo) bool {
return poll.CreatedBy == user.Username
}
func uniquePolls(polls []*database.Poll) []*database.Poll {
var unique []*database.Poll
for _, poll := range polls {
if !containsPoll(unique, poll) {
unique = append(unique, poll)
}
}
return unique
}
func containsPoll(polls []*database.Poll, poll *database.Poll) bool {
for _, p := range polls {
if p.Id == poll.Id {
return true
}
}
return false
}
func hasOption(poll *database.Poll, option string) bool {
for _, opt := range poll.Options {
if opt == option {
return true
}
}
return false
}