From 06696e64926f5247b9e1dea2a8839b398f731fbd Mon Sep 17 00:00:00 2001 From: Herman Slatman Date: Wed, 28 Feb 2024 13:37:51 +0100 Subject: [PATCH] Move user ID handling to `userid` package --- internal/userid/userid.go | 20 ++++++++++++++++++++ logging/context.go | 19 ------------------- logging/handler.go | 3 ++- 3 files changed, 22 insertions(+), 20 deletions(-) create mode 100644 internal/userid/userid.go delete mode 100644 logging/context.go 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 }