From 60a2f794f1e04f9cc106d0df555d35c14afb3082 Mon Sep 17 00:00:00 2001 From: Aki Date: Sat, 24 Apr 2021 03:22:22 +0200 Subject: Moved token handling to storage --- derelict.go | 17 +++++------------ storage.go | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/derelict.go b/derelict.go index d084e49..d72bfb8 100644 --- a/derelict.go +++ b/derelict.go @@ -8,7 +8,6 @@ import ( "log" "net/http" "os" - "regexp" "github.com/gorilla/mux" ) @@ -20,9 +19,8 @@ var content embed.FS var internal embed.FS var ( - storage Storage - templates *template.Template - validToken = regexp.MustCompile(`[a-fA-F0-9]+`) + storage Storage + templates *template.Template ) func main() { @@ -50,20 +48,15 @@ func main() { } func handleBattlesPost(w http.ResponseWriter, r *http.Request) { - token := r.Header.Get("Derelict-Token") - if !validToken.MatchString(token) { + authorized, err := storage.CanPost(r.Header.Get("Derelict-Token")) + if err != nil { http.Error(w, "Invalid token", http.StatusBadRequest) return } - _, err := os.Stat(storage.Path + "/tokens/" + token) - if _, ok := err.(*os.PathError); ok { + if !authorized { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } - if err != nil { - http.Error(w, "Unexpected error 1", http.StatusInternalServerError) - return - } var wrecks []Wreck data, err := ioutil.ReadAll(r.Body) if err != nil { diff --git a/storage.go b/storage.go index ec2d33e..22a226d 100644 --- a/storage.go +++ b/storage.go @@ -3,9 +3,11 @@ package main import ( "crypto/sha1" "encoding/hex" + "errors" "io/ioutil" "net/http" "os" + "regexp" "sort" ) @@ -13,6 +15,10 @@ type Storage struct { Path string } +var ( + tokenPattern = regexp.MustCompile(`[a-fA-F0-9]{10,}`) +) + func (s *Storage) MustInit() error { os.Mkdir(s.Path, 0755) os.Mkdir(s.Path+"/battles", 0755) @@ -20,6 +26,14 @@ func (s *Storage) MustInit() error { return nil } +func (s *Storage) CanPost(token string) (bool, error) { + if !tokenPattern.MatchString(token) { + return false, errors.New("invalid token") + } + _, err := os.Stat(s.Path + "/tokens/" + token) + return err == nil, nil +} + func (s *Storage) AddBattle(data []byte) (string, error) { hash := sha1.Sum(data) id := hex.EncodeToString(hash[:]) -- cgit v1.1