Feat: add preshared key check

This commit is contained in:
2025-12-07 19:14:06 +08:00
parent f4c92504e8
commit cada4d25fa
3 changed files with 49 additions and 1 deletions

View File

@@ -0,0 +1,32 @@
package middlewares
import (
"net/http"
"strings"
"github.com/spf13/viper"
"github.com/uptrace/bunrouter"
)
func (self *Handlers) CheckPresharedKey(
next bunrouter.HandlerFunc,
) bunrouter.HandlerFunc {
return func(w http.ResponseWriter, req bunrouter.Request) error {
authHeader := strings.Split(req.Header.Get("Authorization"), " ")
if len(authHeader) != 2 || authHeader[0] != "Bearer" {
return HTTPError{
StatusCode: http.StatusUnauthorized,
Message: "missing preshared key",
}
}
if authHeader[1] != viper.GetString("preshared-key") {
return HTTPError{
StatusCode: http.StatusUnauthorized,
Message: "preshared key mismatched",
}
}
return next(w, req)
}
}