github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/pkg/scope/context.go (about) 1 package scope 2 3 import ( 4 "context" 5 6 "github.com/kyma-incubator/compass/components/director/pkg/apperrors" 7 ) 8 9 type key int 10 11 // ScopesContextKey is the key under which the scopes are saved in a given context.Context. 12 const ScopesContextKey key = iota 13 14 // LoadFromContext retrieves the scopes from the provided context. It returns error if they cannot be found 15 func LoadFromContext(ctx context.Context) ([]string, error) { 16 value := ctx.Value(ScopesContextKey) 17 scopes, ok := value.([]string) 18 if !ok { 19 return nil, apperrors.NewNoScopesInContextError() 20 } 21 return scopes, nil 22 } 23 24 // SaveToContext returns a child context of the provided context, including the provided scopes information 25 func SaveToContext(ctx context.Context, scopes []string) context.Context { 26 return context.WithValue(ctx, ScopesContextKey, scopes) 27 } 28 29 // Contains returns whether an input scope is present in the provided scopes in the context. It returns error if scopes cannot be found 30 func Contains(ctx context.Context, scope string) (bool, error) { 31 value := ctx.Value(ScopesContextKey) 32 scopes, ok := value.([]string) 33 if !ok { 34 return false, apperrors.NewNoScopesInContextError() 35 } 36 37 for _, s := range scopes { 38 if s == scope { 39 return true, nil 40 } 41 } 42 return false, nil 43 }