diff options
Diffstat (limited to 'backend/api/handlers.go')
| -rw-r--r-- | backend/api/handlers.go | 46 |
1 files changed, 32 insertions, 14 deletions
diff --git a/backend/api/handlers.go b/backend/api/handlers.go index cd8b3b5..c4810a0 100644 --- a/backend/api/handlers.go +++ b/backend/api/handlers.go @@ -50,6 +50,17 @@ func (h *ApiHandler) PostLogin(ctx context.Context, request PostLoginRequestObje }, nil } +func (h *ApiHandler) GetToken(ctx context.Context, request GetTokenRequestObject) (GetTokenResponseObject, error) { + user := ctx.Value("user").(*auth.JWTClaims) + newToken, err := auth.NewShortLivedJWT(user) + if err != nil { + return nil, echo.NewHTTPError(http.StatusInternalServerError, err.Error()) + } + return GetToken200JSONResponse{ + Token: newToken, + }, nil +} + func (h *ApiHandler) GetGames(ctx context.Context, request GetGamesRequestObject) (GetGamesResponseObject, error) { user := ctx.Value("user").(*auth.JWTClaims) playerId := request.Params.PlayerId @@ -179,26 +190,33 @@ 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.SetRequest(c.Request().WithContext(context.WithValue(c.Request().Context(), "user", claims))) + return nil +} + 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) } } } |
