From 5254b92c1b0fcfd74c71de37b4347aeb38e4fbe8 Mon Sep 17 00:00:00 2001 From: Frederic Jahn Date: Fri, 20 Dec 2024 09:47:46 +0100 Subject: [PATCH] feat: let quickstart use session validate endpoint --- quickstart/middleware/session.go | 54 +++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 8 deletions(-) diff --git a/quickstart/middleware/session.go b/quickstart/middleware/session.go index 752d371bc..17f86bcb9 100644 --- a/quickstart/middleware/session.go +++ b/quickstart/middleware/session.go @@ -1,16 +1,17 @@ package middleware import ( - "context" + "bytes" + "encoding/json" "fmt" "github.com/labstack/echo/v4" - "github.com/lestrrat-go/jwx/v2/jwk" - "github.com/lestrrat-go/jwx/v2/jwt" + "io" "log" "net/http" ) func SessionMiddleware(hankoUrl string) echo.MiddlewareFunc { + client := http.Client{} return func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { cookie, err := c.Cookie("hanko") @@ -20,21 +21,58 @@ func SessionMiddleware(hankoUrl string) echo.MiddlewareFunc { if err != nil { return err } - set, err := jwk.Fetch(context.Background(), fmt.Sprintf("%v/.well-known/jwks.json", hankoUrl)) + + requestBody := CheckSessionRequest{SessionToken: cookie.Value} + + bodyJson, err := json.Marshal(requestBody) + if err != nil { + return fmt.Errorf("failed to marshal request body: %w", err) + } + httpReq, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/sessions/validate", hankoUrl), bytes.NewReader(bodyJson)) if err != nil { return err } + httpReq.Header.Set("Content-Type", "application/json") - token, err := jwt.Parse([]byte(cookie.Value), jwt.WithKeySet(set)) + response, err := client.Do(httpReq) if err != nil { - return c.Redirect(http.StatusTemporaryRedirect, "/unauthorized") + return err + } + defer response.Body.Close() + + if response.StatusCode != http.StatusOK { + return fmt.Errorf("failed to get session response: %d", response.StatusCode) + } + + responseBytes, err := io.ReadAll(response.Body) + if err != nil { + return err + } + + var sessionResponse CheckSessionResponse + err = json.Unmarshal(responseBytes, &sessionResponse) + if err != nil { + return err } - log.Printf("session for user '%s' verified successfully", token.Subject()) + if !sessionResponse.IsValid { + return c.Redirect(http.StatusTemporaryRedirect, "/unauthorized") + } + log.Printf("session for user '%s' verified successfully", sessionResponse.UserID) c.Set("token", cookie.Value) - c.Set("user", token.Subject()) + c.Set("user", sessionResponse.UserID) return next(c) } } } + +type CheckSessionRequest struct { + SessionToken string `json:"session_token"` +} + +type CheckSessionResponse struct { + IsValid bool `json:"is_valid"` + ExpirationTime string `json:"expiration_time"` + UserID string `json:"user_id"` +}