Move user ID handling to `userid` package
parent
7e5f10927f
commit
06696e6492
@ -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 != ""
|
||||||
|
}
|
@ -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 != ""
|
|
||||||
}
|
|
Loading…
Reference in New Issue