feat: add jwt auth middleware

This commit is contained in:
Derrick Hammer 2024-01-17 08:16:03 -05:00
parent 1054c52e2f
commit ae0bddf3d1
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
2 changed files with 48 additions and 3 deletions

View File

@ -21,14 +21,14 @@ func NewS5() *S5API {
func (s S5API) Initialize(portal interfaces.Portal, protocol interfaces.Protocol) error {
s5protocol := protocol.(*protocols.S5Protocol)
s5http := s5.NewHttpHandler(portal)
registerProtocolSubdomain(portal, s5protocol.Node().Services().HTTP().GetHttpRouter(getRoutes(s5http)), "s5")
registerProtocolSubdomain(portal, s5protocol.Node().Services().HTTP().GetHttpRouter(getRoutes(s5http, portal)), "s5")
return nil
}
func getRoutes(h *s5.HttpHandler) map[string]jape.Handler {
func getRoutes(h *s5.HttpHandler, portal interfaces.Portal) map[string]jape.Handler {
return map[string]jape.Handler{
"POST /s5/upload": h.SmallFileUpload,
"POST /s5/upload": s5.AuthMiddleware(h.SmallFileUpload, portal),
"GET /s5/account/register": h.AccountRegisterChallenge,
"POST /s5/account/register": h.AccountRegister,
"GET /s5/account/login": h.AccountLoginChallenge,

45
api/s5/middleware.go Normal file
View File

@ -0,0 +1,45 @@
package s5
import (
"fmt"
"git.lumeweb.com/LumeWeb/portal/interfaces"
"github.com/golang-jwt/jwt/v5"
"go.sia.tech/jape"
"net/http"
"strings"
)
func AuthMiddleware(handler jape.Handler, portal interfaces.Portal) jape.Handler {
return jape.Adapt(func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Authorization header is required", http.StatusBadRequest)
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodEd25519); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
publicKey := portal.Identity()
return publicKey, nil
})
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
h.ServeHTTP(w, r)
} else {
http.Error(w, "Invalid JWT", http.StatusUnauthorized)
}
})
})(handler)
}