Generate voter data for known elections and simplify MaxVoters (0 = no maximum)

This commit is contained in:
2024-12-30 23:01:32 +01:00
parent 218f56c060
commit 195bc7d85e
6 changed files with 132 additions and 47 deletions

View File

@ -3,6 +3,8 @@ package main
import (
api "code.dlmw.ch/dlmw/qv/internal"
"code.dlmw.ch/dlmw/qv/internal/validator"
"encoding/json"
"math/rand"
"net/http"
"time"
)
@ -26,7 +28,7 @@ func (app *application) createElection(w http.ResponseWriter, r *http.Request) {
request.CheckField(validator.GreaterThan(len(request.Choices), 1), "choices", "there must be more than 1 choice")
request.CheckField(
!(request.AreVotersKnown && (request.MaxVoters == nil || *request.MaxVoters < 1)),
!(request.AreVotersKnown && request.MaxVoters < 1),
"maxVoters",
"must be greater than 0 when voters are known",
)
@ -36,13 +38,39 @@ func (app *application) createElection(w http.ResponseWriter, r *http.Request) {
return
}
_, err = app.elections.Insert(request.Name, request.Tokens, request.AreVotersKnown, request.MaxVoters, request.Choices, request.ExpiresAt)
electionId, err := app.elections.Insert(request.Name, request.Tokens, request.AreVotersKnown, request.MaxVoters, request.Choices, request.ExpiresAt)
if err != nil {
app.serverError(w, r, err)
return
}
//TODO: if voters are known, generate voters and write them in the response (change openapi as well)
var res []byte
if request.AreVotersKnown {
voterIdentities := make([]string, 0, request.MaxVoters)
for i := 0; i < request.MaxVoters; i++ {
randomIdentity := generateRandomVoterIdentity()
_, err := app.voters.Insert(randomIdentity, electionId)
if err != nil {
app.serverError(w, r, err)
}
voterIdentities = append(voterIdentities, randomIdentity)
}
w.Write([]byte("TODO"))
res, err = json.Marshal(api.CreateElectionResponse{VoterIdentities: &voterIdentities})
if err != nil {
app.serverError(w, r, err)
return
}
}
w.Write(res)
}
func generateRandomVoterIdentity() string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, 16)
for i := range b {
b[i] = charset[rand.Intn(len(charset))]
}
return string(b)
}