diff options
| author | nsfisis <nsfisis@gmail.com> | 2024-07-28 16:00:22 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2024-07-28 16:01:01 +0900 |
| commit | c953b0496ef205ddda0defd70f376623bf13db61 (patch) | |
| tree | 80ddd24c45612dc1971ddb0b268440bfd2efc067 /backend/api/handlers.go | |
| parent | d85cf0be57dd4394c588c340fbfa8483d981da02 (diff) | |
| download | phperkaigi-2025-albatross-c953b0496ef205ddda0defd70f376623bf13db61.tar.gz phperkaigi-2025-albatross-c953b0496ef205ddda0defd70f376623bf13db61.tar.zst phperkaigi-2025-albatross-c953b0496ef205ddda0defd70f376623bf13db61.zip | |
feat(backend): handle JWT validation manually
Diffstat (limited to 'backend/api/handlers.go')
| -rw-r--r-- | backend/api/handlers.go | 25 |
1 files changed, 25 insertions, 0 deletions
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) + } + } + } +} |
