Skip to content

Commit

Permalink
refactor: make tenant UUIDMiddleware a true middleware func
Browse files Browse the repository at this point in the history
  • Loading branch information
kernle32dll committed Apr 21, 2024
1 parent 8cbb81a commit a73d7f6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 22 deletions.
2 changes: 1 addition & 1 deletion tenant/composition.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ func resourcePreHandler(
) alice.Chain {
authHeaderMiddleware := turtleware.AuthBearerHeaderMiddleware
authMiddleware := turtleware.AuthClaimsMiddleware(keySet)
tenantUUIDMiddleware := UUIDMiddleware()
tenantUUIDMiddleware := UUIDMiddleware

return alice.New(
authHeaderMiddleware,
Expand Down
40 changes: 19 additions & 21 deletions tenant/middleware_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,27 +27,25 @@ var (

// UUIDMiddleware is a http middleware for checking tenant authentication details, and
// passing down the tenant UUID if existing, or bailing out otherwise.
func UUIDMiddleware() func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, err := turtleware.AuthClaimsFromRequestContext(r.Context())
if err != nil {
turtleware.WriteError(r.Context(), w, r, http.StatusInternalServerError, err)
return
}

tenantUUID, ok := claims["tenant_uuid"].(string)
if !ok || tenantUUID == "" {
turtleware.WriteError(r.Context(), w, r, http.StatusBadRequest, ErrTokenMissingTenantUUID)
return
}

h.ServeHTTP(
w,
r.WithContext(context.WithValue(r.Context(), ctxTenantUUID, tenantUUID)),
)
})
}
func UUIDMiddleware(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, err := turtleware.AuthClaimsFromRequestContext(r.Context())
if err != nil {
turtleware.WriteError(r.Context(), w, r, http.StatusInternalServerError, err)
return
}

tenantUUID, ok := claims["tenant_uuid"].(string)
if !ok || tenantUUID == "" {
turtleware.WriteError(r.Context(), w, r, http.StatusBadRequest, ErrTokenMissingTenantUUID)
return
}

h.ServeHTTP(
w,
r.WithContext(context.WithValue(r.Context(), ctxTenantUUID, tenantUUID)),
)
})
}

func UUIDFromRequestContext(ctx context.Context) (string, error) {
Expand Down

0 comments on commit a73d7f6

Please sign in to comment.