authorizer.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package cloud
  2. import (
  3. "fmt"
  4. "github.com/opencost/opencost/pkg/util/json"
  5. )
  6. // AuthorizerTypeProperty is the property where the id of an Authorizer should be placed in its custom MarshalJSON function
  7. const AuthorizerTypeProperty = "authorizerType"
  8. type Authorizer interface {
  9. Config
  10. json.Marshaler
  11. }
  12. // AuthorizerSelectorFn implementations of this function should be a simple switch
  13. // and acts as a register for the Authorizer types, returned Authorizer should be empty
  14. // except for its default type property and will have other values marshalled into it
  15. type AuthorizerSelectorFn[T Authorizer] func(string) (T, error)
  16. // AuthorizerFromInterface this generic function provides Authorizer unmarshalling for all providers
  17. func AuthorizerFromInterface[T Authorizer](f any, authSelectFn AuthorizerSelectorFn[T]) (T, error) {
  18. var emptyAuth T
  19. if f == nil {
  20. return emptyAuth, nil
  21. }
  22. fmap, ok := f.(map[string]interface{})
  23. if !ok {
  24. return emptyAuth, fmt.Errorf("AuthorizerFromInterface: could not cast interface as map")
  25. }
  26. authType, err := GetInterfaceValue[string](fmap, AuthorizerTypeProperty)
  27. if err != nil {
  28. return emptyAuth, fmt.Errorf("AuthorizerFromInterface: could not retrieve type property: %w", err)
  29. }
  30. authorizer, err := authSelectFn(authType)
  31. if err != nil {
  32. return emptyAuth, fmt.Errorf("AuthorizerFromInterface: %w", err)
  33. }
  34. // convert the interface back to a []Byte so that it can be unmarshalled into the correct type
  35. fBin, err := json.Marshal(f)
  36. if err != nil {
  37. return emptyAuth, fmt.Errorf("AuthorizerFromInterface: could not marshal value %v: %w", f, err)
  38. }
  39. err = json.Unmarshal(fBin, authorizer)
  40. if err != nil {
  41. return emptyAuth, fmt.Errorf("AuthorizerFromInterface: failed to unmarshal into Authorizer type %T from value %v: %w", authorizer, f, err)
  42. }
  43. return authorizer, nil
  44. }