Files
geo/server/internal/shared/auth/context.go
T
2026-05-20 15:37:25 +08:00

74 lines
1.7 KiB
Go

package auth
import "context"
type Actor struct {
UserID int64
TenantID int64
PrimaryWorkspaceID int64
Role string
}
type actorKey struct{}
type currentWorkspaceIDKey struct{}
type currentBrandIDKey struct{}
func WithActor(ctx context.Context, actor Actor) context.Context {
return context.WithValue(ctx, actorKey{}, actor)
}
func ActorFromCtx(ctx context.Context) (Actor, bool) {
actor, ok := ctx.Value(actorKey{}).(Actor)
return actor, ok
}
func MustActor(ctx context.Context) Actor {
actor, ok := ActorFromCtx(ctx)
if !ok {
panic("auth: actor not in context")
}
return actor
}
func WithCurrentWorkspaceID(ctx context.Context, workspaceID int64) context.Context {
return context.WithValue(ctx, currentWorkspaceIDKey{}, workspaceID)
}
func CurrentWorkspaceIDFromCtx(ctx context.Context) (int64, bool) {
workspaceID, ok := ctx.Value(currentWorkspaceIDKey{}).(int64)
if !ok || workspaceID <= 0 {
return 0, false
}
return workspaceID, true
}
func CurrentWorkspaceID(ctx context.Context) int64 {
if workspaceID, ok := CurrentWorkspaceIDFromCtx(ctx); ok {
return workspaceID
}
actor, ok := ActorFromCtx(ctx)
if !ok {
return 0
}
return actor.PrimaryWorkspaceID
}
func WithCurrentBrandID(ctx context.Context, brandID int64) context.Context {
return context.WithValue(ctx, currentBrandIDKey{}, brandID)
}
func CurrentBrandIDFromCtx(ctx context.Context) (int64, bool) {
brandID, ok := ctx.Value(currentBrandIDKey{}).(int64)
if !ok || brandID <= 0 {
return 0, false
}
return brandID, true
}
func CurrentBrandID(ctx context.Context) int64 {
if brandID, ok := CurrentBrandIDFromCtx(ctx); ok {
return brandID
}
return 0
}