Selaa lähdekoodia

Move user ID handling to `userid` package

Herman Slatman 2 vuotta sitten
vanhempi
sitoutus
06696e6492
3 muutettua tiedostoa jossa 22 lisäystä ja 20 poistoa
  1. 20 0
      internal/userid/userid.go
  2. 0 19
      logging/context.go
  3. 2 1
      logging/handler.go

+ 20 - 0
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 != ""
+}

+ 0 - 19
logging/context.go

@@ -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 != ""
-}

+ 2 - 1
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
 	}