package vote import ( "encoding/json" "log" "net/http" "tomatentum.net/outfit-voting-abi26/internal/auth" "tomatentum.net/outfit-voting-abi26/internal/database" ) type StateChangeRequest struct { Value bool } func SetVoteLockedEndpoint(w http.ResponseWriter, r *http.Request) { var request StateChangeRequest if err := json.NewDecoder(r.Body).Decode(&request); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } r.Body.Close() if err := database.SetVoteLocked(request.Value); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Printf("Updated Vote Lock state to %t\n", request.Value) w.WriteHeader(http.StatusOK) } func SetResultLockedEndpoint(w http.ResponseWriter, r *http.Request) { var request StateChangeRequest if err := json.NewDecoder(r.Body).Decode(&request); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } r.Body.Close() if err := database.SetResultLocked(request.Value); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } log.Printf("Updated Result Lock state to %t\n", request.Value) w.WriteHeader(http.StatusOK) } func VoteLockedEndpoint(w http.ResponseWriter, r *http.Request) { locked, err := database.GetVoteLocked() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Add("Content-Type", "application/json") json.NewEncoder(w).Encode(locked) } func ResultLockedEndpoint(w http.ResponseWriter, r *http.Request) { locked, err := database.GetResultLocked() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Add("Content-Type", "application/json") json.NewEncoder(w).Encode(locked) } func VoteLockMiddleware(next http.HandlerFunc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ok, err := auth.IsAuth(r) if ok { next.ServeHTTP(w, r) return } log.Println("DEBUG: User not authenticated so vote lock is not bypassed", err) locked, err := database.GetVoteLocked() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if locked { w.WriteHeader(http.StatusLocked) w.Write([]byte("Vote currently locked!")) return } next.ServeHTTP(w, r) }) } func ResultLockMiddleware(next http.HandlerFunc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ok, err := auth.IsAuth(r) if ok { next.ServeHTTP(w, r) return } log.Println("DEBUG: User not authenticated so result lock is not bypassed", err) locked, err := database.GetResultLocked() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } if locked { w.WriteHeader(http.StatusLocked) w.Write([]byte("Results currently locked!")) return } next.ServeHTTP(w, r) }) }