error.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright 2022 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package google
  5. import (
  6. "errors"
  7. "golang.org/x/oauth2"
  8. )
  9. // AuthenticationError indicates there was an error in the authentication flow.
  10. //
  11. // Use (*AuthenticationError).Temporary to check if the error can be retried.
  12. type AuthenticationError struct {
  13. err *oauth2.RetrieveError
  14. }
  15. func newAuthenticationError(err error) error {
  16. re := &oauth2.RetrieveError{}
  17. if !errors.As(err, &re) {
  18. return err
  19. }
  20. return &AuthenticationError{
  21. err: re,
  22. }
  23. }
  24. // Temporary indicates that the network error has one of the following status codes and may be retried: 500, 503, 408, or 429.
  25. func (e *AuthenticationError) Temporary() bool {
  26. if e.err.Response == nil {
  27. return false
  28. }
  29. sc := e.err.Response.StatusCode
  30. return sc == 500 || sc == 503 || sc == 408 || sc == 429
  31. }
  32. func (e *AuthenticationError) Error() string {
  33. return e.err.Error()
  34. }
  35. func (e *AuthenticationError) Unwrap() error {
  36. return e.err
  37. }
  38. type errWrappingTokenSource struct {
  39. src oauth2.TokenSource
  40. }
  41. func newErrWrappingTokenSource(ts oauth2.TokenSource) oauth2.TokenSource {
  42. return &errWrappingTokenSource{src: ts}
  43. }
  44. // Token returns the current token if it's still valid, else will
  45. // refresh the current token (using r.Context for HTTP client
  46. // information) and return the new one.
  47. func (s *errWrappingTokenSource) Token() (*oauth2.Token, error) {
  48. t, err := s.src.Token()
  49. if err != nil {
  50. return nil, newAuthenticationError(err)
  51. }
  52. return t, nil
  53. }