Files
qv/cmd/web/handlers.go

77 lines
2.1 KiB
Go
Raw Normal View History

2024-12-27 18:03:46 +01:00
package main
import (
api "code.dlmw.ch/dlmw/qv/internal"
"code.dlmw.ch/dlmw/qv/internal/validator"
"encoding/json"
"math/rand"
"net/http"
"time"
)
type createElectionRequestWithValidator struct {
api.CreateElectionRequest
validator.Validator
}
2024-12-27 18:03:46 +01:00
func (app *application) createElection(w http.ResponseWriter, r *http.Request) {
var request createElectionRequestWithValidator
2024-12-28 17:58:01 +01:00
err := app.unmarshalRequest(r, &request)
if err != nil {
app.clientError(w, http.StatusBadRequest, err.Error())
return
}
request.CheckField(validator.NotBlank(request.Name), "name", "must not be blank")
request.CheckField(validator.GreaterThan(request.Tokens, 0), "tokens", "must be greater than 0")
request.CheckField(validator.After(request.ExpiresAt, time.Now()), "expiresAt", "must expire in a future date")
request.CheckField(validator.GreaterThan(len(request.Choices), 1), "choices", "there must be more than 1 choice")
request.CheckField(
!(request.AreVotersKnown && request.MaxVoters < 1),
"maxVoters",
"must be greater than 0 when voters are known",
)
if !request.Valid() {
app.unprocessableEntityError(w, request.Validator)
return
}
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
}
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)
}
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)
2024-12-27 18:03:46 +01:00
}