diff options
-rw-r--r-- | derelict.go | 58 |
1 files changed, 50 insertions, 8 deletions
diff --git a/derelict.go b/derelict.go index aac7c10..641d8ed 100644 --- a/derelict.go +++ b/derelict.go @@ -1,13 +1,17 @@ package main import ( + "crypto/sha1" "embed" + "encoding/json" + "encoding/hex" "github.com/gorilla/mux" "html/template" "io/ioutil" "log" "net/http" "os" + "regexp" "sort" ) @@ -17,13 +21,17 @@ var content embed.FS //go:embed *.tmpl var internal embed.FS -var templates *template.Template - -var root string +var ( + templates *template.Template + root string + validToken *regexp.Regexp +) func main() { initRoot() + validToken = regexp.MustCompile(`[a-fA-F0-9]+`) + port := os.Getenv("DERELICTPORT") if port == "" { port = "8080" @@ -33,11 +41,10 @@ func main() { router := mux.NewRouter() router.HandleFunc("/", handleRecent).Methods("GET") - router.HandleFunc("/view/{id:[_0-9]+}", handleView).Methods("GET") - router.HandleFunc("/battles/", handleBattlesPost).Methods("POST") - router.HandleFunc("/battles/{id:[_0-9]+}", handleBattlesId).Methods("GET") + router.HandleFunc("/view/{id:[_0-9a-f]+}", handleView).Methods("GET") + router.HandleFunc("/battles", handleBattlesPost).Methods("POST") + router.HandleFunc("/battles/{id:[_0-9a-f]+}", handleBattlesId).Methods("GET") router.PathPrefix("/").Handler(http.FileServer(http.FS(content))) - log.Fatal(http.ListenAndServe(":"+port, router)) } @@ -48,10 +55,45 @@ func initRoot() { } os.Mkdir(root, 0755) os.Mkdir(root+"/battles", 0755) + os.Mkdir(root+"/tokens", 0700) } func handleBattlesPost(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusNotImplemented) + token := r.Header.Get("Derelict-Token") + if !validToken.MatchString(token) { + http.Error(w, "Invalid token", http.StatusBadRequest) + return + } + _, err := os.Stat(root + "/tokens/" + token) + if _, ok := err.(*os.PathError); ok { + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + if err != nil { + http.Error(w, "Unexpected error 1", http.StatusInternalServerError) + return + } + type wreck struct { + Team int `json:"team"` + Id string `json:"id"` + Hash string `json:"hash"` + } + var wrecks []wreck + data, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Unexpected error 2", http.StatusInternalServerError) + return + } + err = json.Unmarshal(data, &wrecks) + if err != nil { + http.Error(w, "Error in body", http.StatusBadRequest) + return + } + hash := sha1.Sum(data) + name := hex.EncodeToString(hash[:]) + ioutil.WriteFile(root+"/battles/"+name, data, 0644) + w.WriteHeader(http.StatusOK) + w.Write([]byte(name)) } func handleBattlesId(w http.ResponseWriter, r *http.Request) { |