backend/pkg/permission/domain/token/context.go

51 lines
1.4 KiB
Go

package token
import (
"context"
)
type ContextKey string
func (c ContextKey) String() string {
return string(c)
}
const (
KeyRole ContextKey = "role"
KeyDeviceID ContextKey = "device_id"
KeyScope ContextKey = "scope"
KeyUID ContextKey = "uid"
KeyLoginID ContextKey = "login_id"
)
func UID(ctx context.Context) string { return getString(ctx, KeyUID) }
func Scope(ctx context.Context) string { return getString(ctx, KeyScope) }
func Role(ctx context.Context) string { return getString(ctx, KeyRole) }
func DeviceID(ctx context.Context) string { return getString(ctx, KeyDeviceID) }
func LoginID(ctx context.Context) string { return getString(ctx, KeyLoginID) }
func WithUID(ctx context.Context, uid string) context.Context {
return context.WithValue(ctx, KeyUID, uid)
}
func WithScope(ctx context.Context, scope string) context.Context {
return context.WithValue(ctx, KeyScope, scope)
}
func WithRole(ctx context.Context, role string) context.Context {
return context.WithValue(ctx, KeyRole, role)
}
func WithDeviceID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, KeyDeviceID, id)
}
func WithLoginID(ctx context.Context, login string) context.Context {
return context.WithValue(ctx, KeyLoginID, login)
}
// --- Internal helper ---
func getString(ctx context.Context, key ContextKey) string {
if v, ok := ctx.Value(key).(string); ok {
return v
}
return ""
}