diff --git a/middleware.go b/middleware.go index c0aabcb..b2da2c1 100644 --- a/middleware.go +++ b/middleware.go @@ -2,6 +2,7 @@ package authcontrol import ( "cmp" + "context" "errors" "net/http" "strings" @@ -158,7 +159,7 @@ func Session(cfg Options) func(next http.Handler) http.Handler { } } - if accessKey != "" && sessionType < proto.SessionType_Admin { + if accessKey != "" { ctx = WithAccessKey(ctx, accessKey) sessionType = max(sessionType, proto.SessionType_AccessKey) } @@ -196,3 +197,24 @@ func AccessControl(acl Config[ACL], cfg Options) func(next http.Handler) http.Ha }) } } + +// PropagateAccessKey propagates the access key from the context to other webrpc packages. +// It expectes the function `WithHTTPRequestHeaders` from the proto package that requires the access key propogation. +func PropagateAccessKey(headerContextFuncs ...func(context.Context, http.Header) (context.Context, error)) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + + if accessKey, ok := GetAccessKey(ctx); ok { + h := http.Header{ + HeaderAccessKey: []string{accessKey}, + } + for _, fn := range headerContextFuncs { + ctx, _ = fn(ctx, h) + } + } + + next.ServeHTTP(w, r.WithContext(ctx)) + }) + } +}