tokenmanager.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. *
  3. * Copyright 2021 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * https://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package tokenmanager provides tokens for authenticating to S2A.
  19. package tokenmanager
  20. import (
  21. "fmt"
  22. "os"
  23. commonpb "github.com/google/s2a-go/internal/proto/common_go_proto"
  24. )
  25. const (
  26. s2aAccessTokenEnvironmentVariable = "S2A_ACCESS_TOKEN"
  27. )
  28. // AccessTokenManager manages tokens for authenticating to S2A.
  29. type AccessTokenManager interface {
  30. // DefaultToken returns a token that an application with no specified local
  31. // identity must use to authenticate to S2A.
  32. DefaultToken() (token string, err error)
  33. // Token returns a token that an application with local identity equal to
  34. // identity must use to authenticate to S2A.
  35. Token(identity *commonpb.Identity) (token string, err error)
  36. }
  37. type singleTokenAccessTokenManager struct {
  38. token string
  39. }
  40. // NewSingleTokenAccessTokenManager returns a new AccessTokenManager instance
  41. // that will always manage the same token.
  42. //
  43. // The token to be managed is read from the s2aAccessTokenEnvironmentVariable
  44. // environment variable. If this environment variable is not set, then this
  45. // function returns an error.
  46. func NewSingleTokenAccessTokenManager() (AccessTokenManager, error) {
  47. token, variableExists := os.LookupEnv(s2aAccessTokenEnvironmentVariable)
  48. if !variableExists {
  49. return nil, fmt.Errorf("%s environment variable is not set", s2aAccessTokenEnvironmentVariable)
  50. }
  51. return &singleTokenAccessTokenManager{token: token}, nil
  52. }
  53. // DefaultToken always returns the token managed by the
  54. // singleTokenAccessTokenManager.
  55. func (m *singleTokenAccessTokenManager) DefaultToken() (string, error) {
  56. return m.token, nil
  57. }
  58. // Token always returns the token managed by the singleTokenAccessTokenManager.
  59. func (m *singleTokenAccessTokenManager) Token(*commonpb.Identity) (string, error) {
  60. return m.token, nil
  61. }