aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/golang.org/x/oauth2/google/error.go
blob: d84dd00473138dd53718a6e8084e2ca14b48c9f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package google

import (
	"errors"

	"golang.org/x/oauth2"
)

// AuthenticationError indicates there was an error in the authentication flow.
//
// Use (*AuthenticationError).Temporary to check if the error can be retried.
type AuthenticationError struct {
	err *oauth2.RetrieveError
}

func newAuthenticationError(err error) error {
	re := &oauth2.RetrieveError{}
	if !errors.As(err, &re) {
		return err
	}
	return &AuthenticationError{
		err: re,
	}
}

// Temporary indicates that the network error has one of the following status codes and may be retried: 500, 503, 408, or 429.
func (e *AuthenticationError) Temporary() bool {
	if e.err.Response == nil {
		return false
	}
	sc := e.err.Response.StatusCode
	return sc == 500 || sc == 503 || sc == 408 || sc == 429
}

func (e *AuthenticationError) Error() string {
	return e.err.Error()
}

func (e *AuthenticationError) Unwrap() error {
	return e.err
}

type errWrappingTokenSource struct {
	src oauth2.TokenSource
}

func newErrWrappingTokenSource(ts oauth2.TokenSource) oauth2.TokenSource {
	return &errWrappingTokenSource{src: ts}
}

// Token returns the current token if it's still valid, else will
// refresh the current token (using r.Context for HTTP client
// information) and return the new one.
func (s *errWrappingTokenSource) Token() (*oauth2.Token, error) {
	t, err := s.src.Token()
	if err != nil {
		return nil, newAuthenticationError(err)
	}
	return t, nil
}