From c953b0496ef205ddda0defd70f376623bf13db61 Mon Sep 17 00:00:00 2001 From: nsfisis Date: Sun, 28 Jul 2024 16:00:22 +0900 Subject: feat(backend): handle JWT validation manually --- backend/api/handlers.go | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'backend/api') diff --git a/backend/api/handlers.go b/backend/api/handlers.go index 57aaabb..ee0a97a 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -3,6 +3,7 @@ package api import ( "context" "net/http" + "strings" "github.com/labstack/echo/v4" @@ -60,3 +61,27 @@ func _assertJwtPayloadIsCompatibleWithJWTClaims() { p.IsAdmin = c.IsAdmin _ = p } + +func NewJWTMiddleware() StrictMiddlewareFunc { + return func(handler StrictHandlerFunc, operationID string) StrictHandlerFunc { + if operationID == "PostApiLogin" { + return handler + } else { + return func(c echo.Context, request interface{}) (response interface{}, err error) { + authorization := c.Request().Header.Get("Authorization") + const prefix = "Bearer " + if !strings.HasPrefix(authorization, prefix) { + return nil, echo.NewHTTPError(http.StatusUnauthorized) + } + token := authorization[len(prefix):] + + claims, err := auth.ParseJWT(token) + if err != nil { + return nil, echo.NewHTTPError(http.StatusUnauthorized) + } + c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), "user", claims))) + return handler(c, request) + } + } + } +} -- cgit v1.2.3-70-g09d2