mirror of
https://github.com/simon987/ws_bucket.git
synced 2025-12-14 07:09:07 +00:00
Auth with global secret for admin endpoints
This commit is contained in:
63
api/auth.go
63
api/auth.go
@@ -1 +1,64 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto"
|
||||
"crypto/hmac"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"github.com/valyala/fasthttp"
|
||||
"math"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
var Secret = []byte(getApiSecret())
|
||||
|
||||
func getApiSecret() string {
|
||||
|
||||
secret := os.Getenv("WS_BUCKET_SECRET")
|
||||
if secret == "" {
|
||||
return "default_secret"
|
||||
} else {
|
||||
return secret
|
||||
}
|
||||
}
|
||||
|
||||
func validateRequest(ctx *fasthttp.RequestCtx) error {
|
||||
|
||||
signature := ctx.Request.Header.Peek("X-Signature")
|
||||
timeStampStr := string(ctx.Request.Header.Peek("Timestamp"))
|
||||
|
||||
if timeStampStr == "" {
|
||||
return errors.New("date is not specified")
|
||||
}
|
||||
|
||||
timestamp, err := time.Parse(time.RFC1123, timeStampStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if math.Abs(float64(timestamp.Unix()-time.Now().Unix())) > 60 {
|
||||
return errors.New("invalid Timestamp")
|
||||
}
|
||||
|
||||
var body []byte
|
||||
if ctx.Request.Header.IsGet() {
|
||||
body = ctx.Request.RequestURI()
|
||||
} else {
|
||||
body = ctx.Request.Body()
|
||||
}
|
||||
|
||||
mac := hmac.New(crypto.SHA256.New, Secret)
|
||||
mac.Write(body)
|
||||
mac.Write([]byte(timeStampStr))
|
||||
|
||||
expectedMac := make([]byte, 64)
|
||||
hex.Encode(expectedMac, mac.Sum(nil))
|
||||
matches := bytes.Compare(expectedMac, signature) == 0
|
||||
|
||||
if !matches {
|
||||
return errors.New("signature does not match")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ import (
|
||||
)
|
||||
|
||||
type GenericResponse struct {
|
||||
Ok bool `json:"ok"`
|
||||
Ok bool `json:"ok"`
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
type AllocateUploadSlotRequest struct {
|
||||
|
||||
12
api/slot.go
12
api/slot.go
@@ -22,10 +22,18 @@ var upgrader = websocket.FastHTTPUpgrader{
|
||||
|
||||
func (api *WebApi) AllocateUploadSlot(ctx *fasthttp.RequestCtx) {
|
||||
|
||||
//todo auth
|
||||
err := validateRequest(ctx)
|
||||
if err != nil {
|
||||
ctx.Response.Header.SetStatusCode(401)
|
||||
Json(GenericResponse{
|
||||
Ok: false,
|
||||
Message: err.Error(),
|
||||
}, ctx)
|
||||
return
|
||||
}
|
||||
|
||||
req := &AllocateUploadSlotRequest{}
|
||||
err := json.Unmarshal(ctx.Request.Body(), req)
|
||||
err = json.Unmarshal(ctx.Request.Body(), req)
|
||||
if err != nil {
|
||||
ctx.Response.Header.SetStatusCode(400)
|
||||
Json(GenericResponse{
|
||||
|
||||
Reference in New Issue
Block a user