2026-04-01 00:58:42 +08:00
|
|
|
package auth
|
|
|
|
|
|
|
|
|
|
import "context"
|
|
|
|
|
|
|
|
|
|
type Actor struct {
|
2026-04-19 14:18:20 +08:00
|
|
|
UserID int64
|
|
|
|
|
TenantID int64
|
|
|
|
|
PrimaryWorkspaceID int64
|
|
|
|
|
Role string
|
2026-04-01 00:58:42 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type actorKey struct{}
|
2026-04-24 22:18:54 +08:00
|
|
|
type currentWorkspaceIDKey struct{}
|
2026-04-01 00:58:42 +08:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
}
|
2026-04-24 22:18:54 +08:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
}
|