summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorAki <please@ignore.pl>2021-04-24 03:22:22 +0200
committerAki <please@ignore.pl>2021-04-24 03:22:22 +0200
commit60a2f794f1e04f9cc106d0df555d35c14afb3082 (patch)
tree7c8ede70f52a6ba009c71b6c2c4224254cb7810e
parentd6226a4a928a386a29e173f7516e3c3d09681dc0 (diff)
downloadfield-60a2f794f1e04f9cc106d0df555d35c14afb3082.zip
field-60a2f794f1e04f9cc106d0df555d35c14afb3082.tar.gz
field-60a2f794f1e04f9cc106d0df555d35c14afb3082.tar.bz2
Moved token handling to storage
-rw-r--r--derelict.go17
-rw-r--r--storage.go14
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[:])