ffe4d335aa
Introduces current-workspace context helpers plus a WorkspaceScope middleware that validates X-Workspace-ID against workspace memberships, defaulting to the actor's primary workspace. Prepares monitoring paths to resolve quota/access-state per request workspace instead of per tenant. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
54 lines
1.2 KiB
Go
54 lines
1.2 KiB
Go
package auth
|
|
|
|
import "context"
|
|
|
|
type Actor struct {
|
|
UserID int64
|
|
TenantID int64
|
|
PrimaryWorkspaceID int64
|
|
Role string
|
|
}
|
|
|
|
type actorKey struct{}
|
|
type currentWorkspaceIDKey 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
|
|
}
|