Skip to content

Commit

Permalink
feat: let quickstart use session validate endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
FreddyDevelop committed Dec 20, 2024
1 parent 26562d9 commit 5254b92
Showing 1 changed file with 46 additions and 8 deletions.
54 changes: 46 additions & 8 deletions quickstart/middleware/session.go
Original file line number Diff line number Diff line change
@@ -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")
Expand All @@ -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"`
}

0 comments on commit 5254b92

Please sign in to comment.