38 lines
778 B
Go
38 lines
778 B
Go
|
|
package design
|
||
|
|
|
||
|
|
import (
|
||
|
|
"context"
|
||
|
|
"strings"
|
||
|
|
|
||
|
|
"github.com/google/uuid"
|
||
|
|
)
|
||
|
|
|
||
|
|
const DefaultUserID = "00000000-0000-0000-0000-000000000001"
|
||
|
|
|
||
|
|
type userIDContextKey struct{}
|
||
|
|
|
||
|
|
func ContextWithUserID(ctx context.Context, userID string) context.Context {
|
||
|
|
return context.WithValue(ctx, userIDContextKey{}, NormalizeUserID(userID))
|
||
|
|
}
|
||
|
|
|
||
|
|
func UserIDFromContext(ctx context.Context) string {
|
||
|
|
if ctx == nil {
|
||
|
|
return DefaultUserID
|
||
|
|
}
|
||
|
|
if value, ok := ctx.Value(userIDContextKey{}).(string); ok {
|
||
|
|
return NormalizeUserID(value)
|
||
|
|
}
|
||
|
|
return DefaultUserID
|
||
|
|
}
|
||
|
|
|
||
|
|
func NormalizeUserID(userID string) string {
|
||
|
|
userID = strings.TrimSpace(userID)
|
||
|
|
if userID == "" {
|
||
|
|
return DefaultUserID
|
||
|
|
}
|
||
|
|
if _, err := uuid.Parse(userID); err != nil {
|
||
|
|
return DefaultUserID
|
||
|
|
}
|
||
|
|
return strings.ToLower(userID)
|
||
|
|
}
|