From f39402fab1eea440d76c1338c9256cf0305f3e43 Mon Sep 17 00:00:00 2001 From: Emile Date: Sun, 20 Oct 2019 01:00:26 +0200 Subject: getChallenges endpoint --- src/http.go | 50 +++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/http.go b/src/http.go index fe38a8e..d3dd15a 100644 --- a/src/http.go +++ b/src/http.go @@ -1,6 +1,8 @@ package main import ( + "crypto/sha256" + "encoding/json" "flag" "fmt" "html/template" @@ -94,7 +96,7 @@ func createPostHandler(w http.ResponseWriter, r *http.Request) { // viewGetHandler returns a list of all challenges in the database func viewGetHandler(w http.ResponseWriter, r *http.Request) { // get all challenges from the db - challs := dbGetAllChallenges(db) + challs := dbGetAllChallenges() // define a challenges struct storing the challenges. // This struct can be used in a template @@ -209,9 +211,47 @@ func readFileToResponse(w http.ResponseWriter, path string) { // getChallenges returns all challenges func getChallenges(w http.ResponseWriter, r *http.Request) { - // Steps: - // - get all challenges from the database - // - marshal the challenges to json - // - return the json + challenges := dbGetAllChallenges() + var strippedChallenges []StrippedChallenge + categories := map[string]int{} + + // build the strippedChallenges list + for _, challenge := range challenges { + strippedChallenges = append(strippedChallenges, stripChallenge(challenge)) + + categories[challenge.Category]++ + } + + // marshal the challenges to json + marshalled, marshalError := json.Marshal(map[string]interface{}{ + "challenges": strippedChallenges, + "categories": categories, + }) + if marshalError != nil { + log.Println(marshalError) + return + } + + // set the json header and write the marshaled challenges to the response + // writer + w.Header().Set("Content-Type", "application/json") + fmt.Fprintf(w, string(marshalled)) +} + +func stripChallenge(challenge Challenge) StrippedChallenge { + // Hash the flag using sha256 + FlagSha256Sum := fmt.Sprintf("%x", sha256.Sum256([]byte(challenge.Flag))) + + strippedChallenge := StrippedChallenge{ + Name: challenge.Name, + Description: challenge.Description, + FlagHash: FlagSha256Sum, + Container: challenge.Container, + Category: challenge.Category, + Points: challenge.Points, + Static: challenge.Static, + } + + return strippedChallenge } -- cgit 1.4.1