github.com/clerkinc/clerk-sdk-go@v1.49.1/clerk/middleware.go (about)

     1  package clerk
     2  
     3  import (
     4  	"context"
     5  	"net/http"
     6  	"strings"
     7  )
     8  
     9  const (
    10  	ActiveSession = iota
    11  	ActiveSessionClaims
    12  
    13  // TODO: we should use a type alias instead of int, so as to avoid collisions
    14  // with other packages
    15  )
    16  
    17  // Deprecated: this middleware handles the old authentication scheme. Use
    18  // WithSessionV2 instead.
    19  func WithSession(client Client) func(handler http.Handler) http.Handler {
    20  	return func(next http.Handler) http.Handler {
    21  		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    22  			if token, isAuthV2 := isAuthV2Request(r, client); isAuthV2 {
    23  				// Validate using session token
    24  				claims, err := client.VerifyToken(token)
    25  				if err != nil {
    26  					w.WriteHeader(http.StatusUnauthorized)
    27  					_, _ = w.Write([]byte(err.Error()))
    28  					return
    29  				}
    30  
    31  				ctx := context.WithValue(r.Context(), ActiveSessionClaims, claims)
    32  				next.ServeHTTP(w, r.WithContext(ctx))
    33  			} else {
    34  				// Validate using session verify request
    35  				session, err := client.Verification().Verify(r)
    36  				if err != nil {
    37  					w.WriteHeader(http.StatusBadRequest)
    38  					_, _ = w.Write([]byte(err.Error()))
    39  					return
    40  				}
    41  
    42  				ctx := context.WithValue(r.Context(), ActiveSession, session)
    43  				next.ServeHTTP(w, r.WithContext(ctx))
    44  			}
    45  		})
    46  	}
    47  }
    48  
    49  func isAuthV2Request(r *http.Request, client Client) (string, bool) {
    50  	// Try with token from header
    51  	headerToken := strings.TrimSpace(r.Header.Get("Authorization"))
    52  	headerToken = strings.TrimPrefix(headerToken, "Bearer ")
    53  
    54  	claims, err := client.DecodeToken(headerToken)
    55  	if err == nil {
    56  		return headerToken, newIssuer(claims.Issuer).IsValid()
    57  	}
    58  
    59  	// Verification from header token failed, try with token from cookie
    60  	cookieSession, err := r.Cookie(CookieSession)
    61  	if err != nil {
    62  		return "", false
    63  	}
    64  
    65  	claims, err = client.DecodeToken(cookieSession.Value)
    66  	if err != nil {
    67  		return "", false
    68  	}
    69  
    70  	return cookieSession.Value, newIssuer(claims.Issuer).IsValid()
    71  }