Skip to content

Commit

Permalink
Propagate Access Key (#26)
Browse files Browse the repository at this point in the history
* Always set access key

* Propagate middleware

* Add comment
  • Loading branch information
klaidliadon authored Nov 18, 2024
1 parent 0f42df9 commit f5ebb9d
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package authcontrol

import (
"cmp"
"context"
"errors"
"net/http"
"strings"
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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))
})
}
}

0 comments on commit f5ebb9d

Please sign in to comment.