about summary refs log tree commit diff
diff options
context:
space:
mode:
authorEmile <hanemile@protonmail.com>2019-10-20 01:00:26 +0200
committerEmile <hanemile@protonmail.com>2019-10-20 01:00:26 +0200
commitf39402fab1eea440d76c1338c9256cf0305f3e43 (patch)
tree488c8afead93f79467ded69a1b9a4fe83dbf8519
parent2c5f6f4e7d3aa933273811c4606e9cb1d729682d (diff)
getChallenges endpoint
-rw-r--r--src/http.go50
1 files changed, 45 insertions, 5 deletions
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
 }