about summary refs log tree commit diff
path: root/src/http.go
blob: e7e874dcb8e7bbd7ab276565fc13a6498e3a2321 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package main

import (
	"crypto/sha256"
	"encoding/json"
	"flag"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"strconv"
	"strings"

	"github.com/gorilla/mux"
)

var (
	port *int
)

func registerHTTPFlags() {
	port = flag.Int("port", 8080, "The port for HTTP")
}

func setupHTTPServer() http.Server {
	r := mux.NewRouter()

	r.HandleFunc("/", indexHandler)
	r.HandleFunc("/create", createGetHandler).Methods("GET")
	r.HandleFunc("/create", createPostHandler).Methods("POST")
	r.HandleFunc("/view", viewGetHandler).Methods("GET")
	r.HandleFunc("/edit", editGetHandler).Methods("GET")
	r.HandleFunc("/edit", editPostHandler).Methods("POST")
	r.HandleFunc("/delete", deleteHandler)
	r.HandleFunc("/editSelect", editSelectGetHandler).Methods("GET")
	r.HandleFunc("/api/getChallenges", getChallenges).Methods("GET")

	return http.Server{
		Addr:    fmt.Sprintf("0.0.0.0:%d", *port),
		Handler: r,
	}
}

// Host the index file
func indexHandler(w http.ResponseWriter, r *http.Request) {
	readFileToResponse(w, "/index.html")
}

func createGetHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("create GET")
	readFileToResponse(w, "/create.html")
}

// createPostHandler handles HTTP POST requests to the /create endpoint creating
// new challenges in the database
func createPostHandler(w http.ResponseWriter, r *http.Request) {

	// parse the Post Request form
	r.ParseForm()

	points, err := strconv.ParseInt(r.Form.Get("challengePoints"), 10, 64)
	if err != nil {
		log.Printf("Could not parse points: %v", err)
		return
	}

	var static bool
	if r.Form.Get("challengeStatic") == "on" {
		static = true
	} else if r.Form.Get("challengeStatic") == "off" {
		static = false
	} else {
		log.Println("Could not parse static: %v", r.Form.Get("challengeStatic"))
		return
	}

	// Define the new challenge
	newChallenge := Challenge{
		Name:        r.Form.Get("challengeName"),
		Description: r.Form.Get("challengeDescription"),
		Flag:        r.Form.Get("challengeFlag"),
		Container:   r.Form.Get("challengeContainer"),
		Category:    r.Form.Get("challengeCategory"),
		Points:      int(points),
		Static:      static,
	}

	// Create the new challenge in the database
	uuid, err := dbNewChallenge(newChallenge)
	if err != nil {
		log.Println(err)
		return
	}
	log.Printf("Create a new challenge. UUID: %s", uuid)
	http.Redirect(w, r, "/view", http.StatusSeeOther)
}

// 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()

	// define a challenges struct storing the challenges.
	// This struct can be used in a template
	challenges := Challenges{}

	for _, chal := range challs {
		challenges.Challenge = append(challenges.Challenge, chal)
	}

	// define a new template to render the challenges in
	t := template.New("")
	t, err := t.ParseFiles("./hosted/view.html")
	if err != nil {
		log.Println(err)
		return
	}

	// execure the template using the challenges struct
	t.ExecuteTemplate(w, "view", challenges)
}

func editSelectGetHandler(w http.ResponseWriter, r *http.Request) {
	// get all challenges from the db
	challs := dbGetAllChallenges()

	// define a challenges struct storing the challenges.
	// This struct can be used in a template
	challenges := Challenges{}

	for _, chal := range challs {
		challenges.Challenge = append(challenges.Challenge, chal)
	}

	// define a new template to render the challenges in
	t := template.New("")
	t, err := t.ParseFiles("./hosted/edit.html")
	if err != nil {
		log.Println(err)
		return
	}

	// execure the template using the challenges struct
	t.ExecuteTemplate(w, "edit", challenges)
}

func editGetHandler(w http.ResponseWriter, r *http.Request) {
	var uuid string

	if r.URL.Query()["uuid"] == nil {
		log.Println("editnoparam")
		http.Redirect(w, r, "/editSelect", http.StatusSeeOther)
		return
	}
	uuid = r.URL.Query()["uuid"][0]

	log.Printf("fetching challenge with the uuid %s", uuid)

	chall, err := dbGetChallengeByUUID(uuid)
	if err != nil {
		log.Println(err)
	}

	// define a new template to render the challenges in
	t := template.New("")
	t, err = t.ParseFiles("./hosted/edit_uuid.html")
	if err != nil {
		log.Println(err)
		return
	}

	// execute the template using the challenges struct
	t.ExecuteTemplate(w, "edit_uuid", chall)
	return
}

func editPostHandler(w http.ResponseWriter, r *http.Request) {
	log.Println("edit POST")
	// parse the Post Request form
	err := r.ParseForm()
	if err != nil {
		log.Println("could not parse the http post form!")
		return
	}

	// parse the challenge points
	points, err := strconv.ParseInt(r.PostFormValue("challengePoints"), 10, 64)
	if err != nil {
		log.Printf("Could not parse points: %v (%#v)", err, r.Form.Get("challengePoints"))
		return
	}

	// parse the static value
	var static bool
	if r.Form.Get("challengeStatic") == "true" {
		static = true
	} else if r.Form.Get("challengeStatic") == "false" {
		static = false
	} else {
		log.Println("[edit POST] Could not parse static: %v", r.Form.Get("challengeStatic"))
		return
	}

	// define the new edited challenge
	editedChallenge := Challenge{
		UUID:        r.Form.Get("challengeUUID"),
		Name:        r.Form.Get("challengeName"),
		Description: r.Form.Get("challengeDescription"),
		Flag:        r.Form.Get("challengeFlag"),
		Container:   r.Form.Get("challengeContainer"),
		Category:    r.Form.Get("challengeCategory"),
		Points:      int(points),
		Static:      static,
	}

	// update the challenge in the database
	EditError := dbEditChallengeUUID(r.Form.Get("challengeUUID"), editedChallenge)
	if EditError != nil {
		log.Println("Could not edit:")
		log.Println(EditError)
	}

	log.Println("done editing challenge!")

	http.Redirect(w, r, "/edit", http.StatusSeeOther)
}

func deleteHandler(w http.ResponseWriter, r *http.Request) {
	err := r.ParseForm()
	if err != nil {
		log.Println("deleteHandler could not parse the form")
		log.Println(err)
	}

	if r.URL.Query()["uuid"] == nil {
		log.Println("delete: no uuid given")
		return
	}
	uuid := r.URL.Query()["uuid"][0]
	log.Printf("Deleteing challenge with uuid %s\n", uuid)

	dbDeleteChallengeByUUID(uuid)
	http.Redirect(w, r, "/editSelect", http.StatusSeeOther)
}

// Helper function to host files off of "hosted/" directory
func readFileToResponse(w http.ResponseWriter, path string) {
	requestedFile := strings.Replace(path, "..", "", -1)

	contents, readError := ioutil.ReadFile(fmt.Sprintf("hosted/%s", requestedFile))

	if readError != nil {
		w.Write([]byte(fmt.Sprintf("unable to read %s", requestedFile)))
	} else {
		w.Write([]byte(contents))
	}
}

// getChallenges returns all challenges
func getChallenges(w http.ResponseWriter, r *http.Request) {
	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
}