/
refresh_token.go
90 lines (79 loc) · 2.71 KB
/
refresh_token.go
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package cmd
import (
"context"
"errors"
"code.cloudfoundry.org/uaa-cli/cli"
"code.cloudfoundry.org/uaa-cli/config"
"code.cloudfoundry.org/uaa-cli/help"
"code.cloudfoundry.org/uaa-cli/utils"
"github.com/cloudfoundry-community/go-uaa"
"github.com/spf13/cobra"
)
func RefreshTokenCmd(cfg config.Config, log cli.Logger, tokenFormat string) error {
//TODO: use library function to perform conversion
format := uaa.JSONWebToken
if tokenFormat == "opaque" {
format = uaa.OpaqueToken
}
api, err := uaa.New(
cfg.GetActiveTarget().BaseUrl,
uaa.WithRefreshToken(
cfg.GetActiveContext().ClientId,
clientSecret,
cfg.GetActiveContext().Token.RefreshToken,
format,
),
uaa.WithZoneID(cfg.ZoneSubdomain),
uaa.WithSkipSSLValidation(cfg.GetActiveTarget().SkipSSLValidation),
uaa.WithVerbosity(verbose),
)
log.Infof("Using the refresh_token from the active context to request a new access token for client %v.", utils.Emphasize(cfg.GetActiveContext().ClientId))
if err != nil {
return err
}
ctx := cfg.GetActiveContext()
token, err := api.Token(context.Background()) //TODO: stop making this request for a second time
if err != nil {
return err
}
ctx.Token = *token
cfg.AddContext(ctx)
config.WriteConfig(cfg)
log.Info("Access token successfully fetched and added to active context.")
return nil
}
func RefreshTokenValidations(cfg config.Config, clientSecret string) error {
if err := cli.EnsureContextInConfig(cfg); err != nil {
return err
}
if clientSecret == "" {
return cli.MissingArgumentError("client_secret")
}
if cfg.GetActiveContext().ClientId == "" {
return errors.New("A client_id was not found in the active context.")
}
if GetSavedConfig().GetActiveContext().Token.RefreshToken == "" {
return errors.New("A refresh_token was not found in the active context.")
}
return validateTokenFormatError(tokenFormat)
}
var refreshTokenCmd = &cobra.Command{
Use: "refresh-token -s CLIENT_SECRET",
Short: "Obtain an access token using the refresh_token grant type",
Long: help.RefreshToken(),
PreRun: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
cli.NotifyValidationErrors(RefreshTokenValidations(cfg, clientSecret), cmd, log)
},
Run: func(cmd *cobra.Command, args []string) {
cfg := GetSavedConfig()
cli.NotifyErrorsWithRetry(RefreshTokenCmd(cfg, log, tokenFormat), log, GetSavedConfig())
},
}
func init() {
RootCmd.AddCommand(refreshTokenCmd)
refreshTokenCmd.Annotations = make(map[string]string)
refreshTokenCmd.Annotations[TOKEN_CATEGORY] = "true"
refreshTokenCmd.Flags().StringVarP(&clientSecret, "client_secret", "s", "", "client secret")
refreshTokenCmd.Flags().StringVarP(&tokenFormat, "format", "", "jwt", "available formats include "+availableFormatsStr())
}