Repository navigation
Expand file tree
/
Copy pathrefresh.go
More file actions
74 lines (63 loc) · 2.22 KB
/
Copy pathrefresh.go
File metadata and controls
74 lines (63 loc) · 2.22 KB
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
65
66
67
68
69
70
71
72
73
74
package oauth
import (
"errors"
"fmt"
"net/http"
"net/url"
"github.com/cli/oauth/api"
)
// ErrRefreshTokenInvalid is returned when the server rejects a refresh token because it is invalid,
// expired, or already used.
var ErrRefreshTokenInvalid = errors.New("refresh token is invalid or expired")
// RefreshOptions specifies parameters for exchanging a refresh token for a new token pair.
type RefreshOptions struct {
// Host contains the token endpoint used for the refresh request.
Host *Host
// ClientID is the OAuth application ID.
ClientID string
// ClientSecret is the OAuth application secret. It is not required for device flow tokens.
ClientSecret string
// RefreshToken is the refresh token issued with the current access token.
RefreshToken string
// HTTPClient is the client used for the refresh request. It defaults to http.DefaultClient.
HTTPClient httpClient
}
// Refresh exchanges a refresh token for a new access token and refresh token. If the server omits a refresh token
// from the response, the returned token carries the refresh token from opts, since RFC 6749 section 6 allows the
// server to keep the previous one valid. Applications that require rotation must enforce it themselves.
func Refresh(opts RefreshOptions) (*api.AccessToken, error) {
if opts.Host == nil {
return nil, errors.New("host is required")
}
if opts.RefreshToken == "" {
return nil, fmt.Errorf("%w: refresh token is empty", ErrRefreshTokenInvalid)
}
httpClient := opts.HTTPClient
if httpClient == nil {
httpClient = http.DefaultClient
}
values := url.Values{
"client_id": {opts.ClientID},
"refresh_token": {opts.RefreshToken},
"grant_type": {"refresh_token"},
}
if opts.ClientSecret != "" {
values.Set("client_secret", opts.ClientSecret)
}
resp, err := api.PostForm(httpClient, opts.Host.TokenURL, values)
if err != nil {
return nil, err
}
token, err := resp.AccessToken()
if err != nil {
var apiError *api.Error
if errors.As(err, &apiError) && (apiError.Code == "bad_refresh_token" || apiError.Code == "invalid_grant") {
return nil, fmt.Errorf("%w: %w", ErrRefreshTokenInvalid, err)
}
return nil, err
}
if token.RefreshToken == "" {
token.RefreshToken = opts.RefreshToken
}
return token, nil
}