diff options
| author | nsfisis <nsfisis@gmail.com> | 2024-07-29 03:44:10 +0900 |
|---|---|---|
| committer | nsfisis <nsfisis@gmail.com> | 2024-07-29 19:38:39 +0900 |
| commit | d73fd8bf5bf589a4a391c867e980761fadb647ce (patch) | |
| tree | 15f2454b48cae461a6d8acc7edb2c2111d445d3e /backend/api/handlers.go | |
| parent | 3f95e0e6d62267cf8863e98f3ab7de8971a91000 (diff) | |
| download | iosdc-japan-2025-albatross-d73fd8bf5bf589a4a391c867e980761fadb647ce.tar.gz iosdc-japan-2025-albatross-d73fd8bf5bf589a4a391c867e980761fadb647ce.tar.zst iosdc-japan-2025-albatross-d73fd8bf5bf589a4a391c867e980761fadb647ce.zip | |
feat: partially implement watching
Diffstat (limited to 'backend/api/handlers.go')
| -rw-r--r-- | backend/api/handlers.go | 48 |
1 files changed, 34 insertions, 14 deletions
diff --git a/backend/api/handlers.go b/backend/api/handlers.go index cd8b3b5..f50558d 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -179,26 +179,46 @@ func _assertJwtPayloadIsCompatibleWithJWTClaims() { _ = p } +func setupJWTFromAuthorizationHeader(c echo.Context) error { + authorization := c.Request().Header.Get("Authorization") + const prefix = "Bearer " + if !strings.HasPrefix(authorization, prefix) { + return echo.NewHTTPError(http.StatusUnauthorized) + } + token := authorization[len(prefix):] + claims, err := auth.ParseJWT(token) + if err != nil { + return echo.NewHTTPError(http.StatusUnauthorized, err.Error()) + } + c.Set("user", claims) + c.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), "user", claims))) + return nil +} + +func NewEchoJWTMiddleware() echo.MiddlewareFunc { + return func(next echo.HandlerFunc) echo.HandlerFunc { + return func(c echo.Context) error { + err := setupJWTFromAuthorizationHeader(c) + if err != nil { + return echo.NewHTTPError(http.StatusUnauthorized, err.Error()) + } + return next(c) + } + } +} + func NewJWTMiddleware() StrictMiddlewareFunc { return func(handler StrictHandlerFunc, operationID string) StrictHandlerFunc { if operationID == "PostLogin" { 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) + return func(c echo.Context, request interface{}) (interface{}, error) { + err := setupJWTFromAuthorizationHeader(c) + if err != nil { + return nil, echo.NewHTTPError(http.StatusUnauthorized, err.Error()) } + return handler(c, request) } } } |
