diff --git a/internal/userid/userid.go b/internal/userid/userid.go new file mode 100644 index 00000000..bab4908f --- /dev/null +++ b/internal/userid/userid.go @@ -0,0 +1,20 @@ +package userid + +import "context" + +type userIDKey struct{} + +// NewContext returns a new context with the given user ID added to the +// context. +// TODO(hs): this doesn't seem to be used / set currently; implement +// when/where it makes sense. +func NewContext(ctx context.Context, userID string) context.Context { + return context.WithValue(ctx, userIDKey{}, userID) +} + +// FromContext returns the user ID from the context if it exists +// and is not empty. +func FromContext(ctx context.Context) (string, bool) { + v, ok := ctx.Value(userIDKey{}).(string) + return v, ok && v != "" +} diff --git a/logging/context.go b/logging/context.go deleted file mode 100644 index 212e2560..00000000 --- a/logging/context.go +++ /dev/null @@ -1,19 +0,0 @@ -package logging - -import ( - "context" -) - -type userIDKey struct{} - -// WithUserID decodes the token, extracts the user from the payload and stores -// it in the context. -func WithUserID(ctx context.Context, userID string) context.Context { - return context.WithValue(ctx, userIDKey{}, userID) -} - -// GetUserID returns the request id from the context if it exists. -func GetUserID(ctx context.Context) (string, bool) { - v, ok := ctx.Value(userIDKey{}).(string) - return v, ok && v != "" -} diff --git a/logging/handler.go b/logging/handler.go index 77287690..a29383b2 100644 --- a/logging/handler.go +++ b/logging/handler.go @@ -10,6 +10,7 @@ import ( "github.com/sirupsen/logrus" "github.com/smallstep/certificates/internal/requestid" + "github.com/smallstep/certificates/internal/userid" ) // LoggerHandler creates a logger handler @@ -60,7 +61,7 @@ func (l *LoggerHandler) writeEntry(w ResponseLogger, r *http.Request, t time.Tim if v, ok := requestid.FromContext(ctx); ok { requestID = v } - if v, ok := GetUserID(ctx); ok && v != "" { + if v, ok := userid.FromContext(ctx); ok { userID = v }