1
0
mirror of https://github.com/fumiama/imoto.git synced 2026-06-07 19:40:33 +08:00

feat: add Authorization

This commit is contained in:
源文雨
2023-11-17 13:33:56 +09:00
parent a488786d31
commit 1679eb0809
6 changed files with 206 additions and 49 deletions

View File

@@ -3,6 +3,9 @@ package main
import (
"bytes"
"crypto/md5"
"crypto/rand"
"encoding/hex"
"errors"
"flag"
"io"
"net/http"
@@ -23,10 +26,32 @@ type imagebody struct {
dat []byte
}
var (
errInvalidTokenLength = errors.New("invalid token length")
errInvalidToken = errors.New("invalid token")
)
func main() {
cachetime := flag.Uint("t", 60, "cache time (s)")
endpoint := flag.String("e", "127.0.0.1:8000", "listening endpoint")
var tok [32]byte
_, err := rand.Read(tok[:])
if err != nil {
panic(err)
}
token := flag.String("k", hex.EncodeToString(tok[:]), "put/delete token")
flag.Parse()
if len(*token) != 64 {
panic(errInvalidTokenLength)
}
n, err := hex.Decode(tok[:], imoto.StringToBytes(*token))
if err != nil {
panic(err)
}
if n != 32 {
panic(errInvalidToken)
}
logrus.Infoln("listening to", *endpoint, "with token", hex.EncodeToString(tok[:]))
imgcache = ttl.NewCache[uint64, *imagebody](time.Second * time.Duration(*cachetime))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
m, err := imoto.GetMD5(r.URL.Path)
@@ -54,6 +79,15 @@ func main() {
w.Header().Set("Content-Type", "image/"+img.typ)
_, _ = w.Write(img.dat)
case http.MethodPut:
err := checktoken(&tok, r)
if err != nil {
http.Error(w, "400 Bad Request: "+err.Error(), http.StatusBadRequest)
return
}
if imgcache.Get(p) != nil {
w.WriteHeader(http.StatusOK)
return
}
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "500 Internal Server Error: "+err.Error(), http.StatusInternalServerError)
@@ -76,6 +110,11 @@ func main() {
})
w.WriteHeader(http.StatusOK)
case http.MethodDelete:
err := checktoken(&tok, r)
if err != nil {
http.Error(w, "400 Bad Request: "+err.Error(), http.StatusBadRequest)
return
}
img := imgcache.Get(p)
if img == nil {
w.WriteHeader(http.StatusNotFound)
@@ -95,3 +134,18 @@ func main() {
})
logrus.Errorln(http.ListenAndServe(*endpoint, nil))
}
func checktoken(tok *[32]byte, r *http.Request) error {
t := r.Header.Get("Authorization")
if len(t) != 64 {
return errInvalidTokenLength
}
usrtok, err := hex.DecodeString(t)
if err != nil {
return err
}
if !bytes.Equal(usrtok, tok[:]) {
return errInvalidToken
}
return nil
}