Generate voter data for known elections and simplify MaxVoters (0 = no maximum)
This commit is contained in:
@ -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)
|
||||
}
|
||||
|
Reference in New Issue
Block a user